Added pattern check on log entries with the service_pattern table.
[gnucomo.git] / src / gcm_daemon / gcm_daemon.php
1 #!/usr/bin/php
2 <?PHP
3 /**********************************************************************************
4 **  (c) Copyright 2002, Brenno J.S.A.A.F. de Winter, De Winter Information Solutions
5 ** This is free software; you can redistribute it and/or modify it under the
6 ** terms of the GNU General Public License, see the file COPYING.
7 ***********************************************************************************/
8
9
10 /*
11    NAME          : gcm_daemon
12    AUTHOR        : Brenno J.S.A.A.F. de Winter
13                    De Winter Information Solutions
14    COPYRIGHT     : 2002 - De Winter Information Solutions,
15                    Brenno J.S.A.A.F. de Winter
16
17    * DATES *
18    First        : November 8th 2002
19    Gnucomo-0.0.3: December 6th 2002
20    Gnucomo-0.0.8: September 4th 2003
21
22  $Log: gcm_daemon.php,v $
23  Revision 1.20  2005-06-04 07:15:16  arjen
24  Added pattern check on log entries with the service_pattern table.
25
26  Revision 1.19  2004/01/10 20:04:12  arjen
27  Send email about open notifications to an object's users.
28
29  Revision 1.18  2003/12/03 08:07:21  arjen
30  Changed the type of log_adv_daemon_email.delay and log_adv_daemon_email.xdelay
31  from time to interval. These delays can be more than 24 hours.
32
33  Revision 1.17  2003/10/29 09:58:29  arjen
34  Create separate notifications for different objects in service_check().
35
36  Revision 1.16  2003/09/03 12:48:48  arjen
37  Check the log table against the servies running on an object and
38  create notifications if a service is not supposed to be available
39  or is not known at all.
40
41  Revision 1.15  2003/09/02 12:48:09  arjen
42  BUGFIX: Secondary indices on log_notification were unique.
43  Additional information in the 'usr' table: 'display_name' and 'email'.
44  Added new issues and services.
45
46  Revision 1.14  2003/09/01 06:51:07  arjen
47  Accept command argument '-c config' to use an alternate
48  gnucomo configuration.
49
50  Revision 1.13  2003/08/14 10:22:42  arjen
51  Disabled DEBUG output
52
53  Revision 1.12  2003/08/05 07:46:37  arjen
54  BUGFIX: Print an error message if a parameter does not have
55  any history.
56
57  Revision 1.11  2003/07/09 07:25:02  arjen
58  Gcm_daemon gathers statistics on parameters, notifications, etc. for all objects.
59
60  Revision 1.10  2003/03/29 08:33:58  arjen
61  In phpclasses/db.class.php: Added the database connection string as
62  an argument to the function copy_db_class.
63  Fixed the PHP member function db::db_connect(). The Postgres connection
64  string is now passed as an argument to that function.
65
66  Revision 1.9  2003/02/21 08:37:59  arjen
67  Added new table to the database: log_adv_daemon_email.
68
69
70 */
71
72 // $Id: gcm_daemon.php,v 1.20 2005-06-04 07:15:16 arjen Exp $
73
74 ini_set('include_path', '.:./classes:../phpclasses');
75 ini_set('html_errors', 'false');
76
77 define("BATCHSIZE", 200);
78
79 //Tell the log that we're up.
80 define_syslog_variables();
81
82 require_once "gnucomo_config.php";
83 require_once "db.class.php";
84 require_once "gnucomo.process_log.php";
85
86 // Set the standard variables //
87
88 $project_name   = "gnucomo";    // name of the entire project
89 $app_name       = "gcm_daemon"; // name of the application running
90 $developrelease = "FALSE";      // Indicates if special debug settings are needed
91 $db_version     = 48;           // The db_version indicates what the level of
92                                 // the database should be. If the database is
93                                 // old an update will be generated.
94 $gcmd_version   = 5;            // This value indicates the active version of
95                                 // the gcm_daemon, which is saved in the database.
96                                 // Log records that were not recognized before
97                                 // will now be recognized. The version doesn't
98                                 // mean anything in the overall gnucomo project.
99
100 //Avoid time-limit issues
101 set_time_limit(0);
102
103 //  Scan the command arguments
104
105 for ($argi = 1; $argi < $argc; $argi++)
106 {
107    switch ($argv[$argi])
108    {
109    case "-c":
110       $argi++;
111       $project_name = $argv[$argi];
112       break;
113
114    default:
115       echo "Usage: gcm_daemon [-c configname]\n";
116       exit();
117       break;
118    }
119 }
120
121 // Read the database settings //
122 $class_settings = new gnucomo_config();
123 if (!$class_settings->read($project_name))
124 {
125    echo "Can not read Gnucomo configuration file for $project_name.\n";
126    exit();
127 }
128
129 openlog("gnucomo", LOG_PID, LOG_DAEMON);
130 syslog(LOG_INFO, "gcm_daemon started");
131
132 //Open an connection to the database
133 $dbms_type = $class_settings->find_parameter("database", "type");
134 $dbms_host = $class_settings->find_parameter("database", "host");
135 $dbms_name = $class_settings->find_parameter("database", "name");
136 $dbms_user = $class_settings->find_parameter("gcm_daemon", "user");
137 $dbms_password = $class_settings->find_parameter("gcm_daemon", "password");
138
139 db_select($dbms_type);
140 $dbms = new db();
141 $dbms->db_host = $dbms_host;
142 $dbms->db_name = $dbms_name;
143 $dbms->db_user = $dbms_user;
144 $dbms->db_password = $dbms_password;
145 $dbms->db_connect($class_settings->database());
146
147 if ($dbms->have_db_connection() == "FALSE")
148 {
149    exit ("Database connection failed.");
150 }
151 else
152 {
153    // The database connection has been made.
154    $dbms_working = copy_db_class($dbms, $class_settings->database());
155 }
156
157 // Verify if the database is up-to-date by checking the versionnumber
158
159 $local_sql = "SELECT setting_value FROM db_value WHERE setting = 'db_version' ";
160 $dbms->query($local_sql);
161
162 if ($dbms->fetch_row() == "TRUE")
163 {
164   $active_version = $dbms->db_result_row[0];
165
166   // Update the database to the most recent version.
167
168   if ($active_version < $db_version)
169   {
170      include ("gnucomo_db_version.php");
171   }
172 }
173 else
174 {
175   syslog (LOG_INFO, "Couldn't initialize database version. Is this a gnucomo database?");
176   die ("Couldn't initialize database version.\n");
177 }
178
179 // If there is a new gcm_daemon_version the logrecords that couldn't be
180 // understood can be reprocessed. For this reason processed is now changed
181 // to false again for not recognized records.
182
183 $local_sql = "SELECT setting_value FROM db_value
184               WHERE setting = 'gcm_daemon_version'";
185 $dbms->query($local_sql);
186
187 if ($dbms->fetch_row() == "TRUE")
188 {
189    if ($dbms->db_result_row[0] < $gcmd_version)
190    {
191       //Reactive log-records that weren't understood earlier.
192
193       $local_sql = "UPDATE log SET processed = false
194                     WHERE logid NOT IN (SELECT DISTINCT logid FROM log_adv)";
195       $dbms->query($local_sql);
196
197       //Update de gcm_daemon version in the database
198       $local_sql = "UPDATE db_value SET setting_value = '".$gcmd_version;
199       $local_sql .= "' WHERE setting = 'gcm_daemon_version'";
200       $dbms->query($local_sql);
201
202    }
203
204 }
205
206 // Now we loop the tasks that we have to do.
207
208
209 do
210 {
211
212    //At this place we start processing new log-lines
213
214    echo "Processing logs...\n";
215    process_log ();
216    service_check();
217    find_notifications();
218    mail_notifications();
219
220    //  Gather the statistics for each object
221
222    $obj_result = $dbms->query("SELECT objectid FROM object");
223    for ($obj = 0; $obj < $dbms->num_rows($obj_result); $obj++)
224    {
225       $object = $dbms->fetch_object($obj_result, $obj);
226       echo "Gathering statistics for object " . $object->objectid . "\n";
227       GatherStatistics($object->objectid);
228    }
229
230    $keep_running = false;
231
232 } while ($keep_running == true);
233
234 //Tell the log that we're ending our efforts in a nice way
235
236 syslog (LOG_INFO, "gcm_daemon ended nicely");
237
238 function process_log ()
239 {
240
241  /* This function will walk through the log-records that haven't been processed
242   * first a snapshot will be created of a the non-processed records.
243   * sequentially each record will dealt with. By doing that changes will be made
244   * in several log_adv_xxx tables
245   * INPUT  : NONE
246   * OUTPUT : NONE
247   */
248
249   global $dbms;
250   global $dbms_working;
251   global $class_settings;
252
253   $last_log = 0;
254
255   // Find records in log that still have to be processed.
256
257   $local_sql = "SELECT setting_value FROM db_value WHERE setting = 'log_processing'";
258   $dbms->query($local_sql);
259
260   if ($dbms->fetch_row() == "TRUE")
261   {
262      $last_log = $dbms->db_result_row[0];
263   }
264
265   echo "Last processed logid = $last_log \n";
266
267   //Query the log-table
268   $local_sql = "SELECT * FROM log WHERE logid > CAST(".$last_log." AS BIGINT)
269                 ORDER BY logid LIMIT " . BATCHSIZE;
270   $dbms->query($local_sql);
271
272   //Update the log-statistics in the object-table
273   $local_statistics_db = copy_db_class($dbms, $class_settings->database());
274   $local_findobject_db = copy_db_class($dbms, $class_settings->database());
275
276   //Make totals
277   $local_upper_row = $dbms->num_rows() + $last_log + 1;
278   $local_sql = "SELECT COUNT(logid), objectid from log WHERE logid > CAST(". $last_log .
279       " AS BIGINT) AND logid < CAST (" . $local_upper_row . " AS BIGINT) GROUP BY objectid";
280   $local_statistics_db->query ($local_sql);
281
282   // Loop the objects
283   for ($i = 1; $i <= $local_statistics_db->num_rows(); $i++)
284   {
285       $local_object_row = $local_statistics_db->fetch_row();
286
287       $local_sql = "UPDATE object SET log_count = log_count + " .
288           $local_statistics_db->db_result_row[0] . " WHERE objectid = '" .
289           $local_statistics_db->db_result_row[1] . "'";
290
291       $local_findobject_db->query($local_sql);
292   }
293
294   $local_counter = 0;
295
296   if ($dbms->num_rows() > 0)
297   {
298
299     //Create a database connection for changes in the database.
300     $dbms_changes = copy_db_class($dbms, $class_settings->database());
301     if ($dbms_changes->have_db_connection() == 'TRUE')
302     {
303
304        $local_sql               = 0 ;
305        $local_sql_statistics    = "";
306        $local_object_os         = "";
307        $local_object_os_version = "";
308
309        while ($local_counter < $dbms->num_rows())
310        {
311
312          $local_return_row = $dbms->fetch_row();
313          if ($local_return_row == 'TRUE')
314          {
315             // Work on active rows
316             $local_log_id = $dbms->db_result_row[0];
317
318             $local_sql_findobject = "SELECT os, os_version FROM object
319                                 WHERE objectid = '".$dbms->db_result_row[1]."'";
320             $local_findobject_db->query($local_sql_findobject);
321             $local_findobject_result = $local_findobject_db->fetch_row();
322             if ($local_findobject_result == 'TRUE')
323             {
324
325                 // Now work on the OS again
326                 $local_object_os = $local_findobject_db->db_result_row[0];
327                 if  ($local_object_os == "")
328                 {
329                     $local_object_os = "Linux";
330                     $local_object_os_version = "Unknown assuming Linux";
331                 }
332                 else
333                 {
334                   $local_object_os_version = $local_findobject_db->db_result_row[1];
335                 }
336              }
337
338             switch (strtolower($local_object_os))
339             {
340             case "linux":
341                 $local_process_return = linux_log ();
342                 break;
343             default:
344                 syslog (LOG_INFO, "Couldn't find suitable OS for processing the logline");
345                 break;
346             }
347
348             if ($local_process_return != 'TRUE')
349             {
350               $local_process_return = 'FALSE';
351             }
352
353          }
354          else
355          {
356
357            break;
358
359          }
360          $local_counter++;
361        }
362
363        //  Check for spam and other abuses.
364
365        // abuse_check($last_log);
366
367        match_log_patterns($last_log);
368
369        // Register that the logrecords have been processed.
370        $local_upper_row--;
371        $local_sql = "UPDATE db_value SET setting_value = '"
372                    . $local_upper_row ."' where setting = 'log_processing'";
373        $dbms->query($local_sql);
374
375
376        // Update the statistics for the object-table
377
378
379      }
380      else
381      {
382        syslog (LOG_INFO, "Couldn't clone database connection.");
383        die ("Couldn't reconnect to the database.\n");
384      }
385   }
386
387 }
388
389 /*
390  *   Update a single statistic for some object.
391  *   If it does not yet exist, it will be created.
392  */
393
394 function UpdateStatistic($objectid, $name, $value)
395 {
396    global $dbms;
397
398    $result = $dbms->query("SELECT objectid FROM object_statistics WHERE
399              objectid='$objectid' AND statname='$name'");
400    if ($dbms->num_rows() == 0)
401    {
402       $dbms->query("INSERT INTO object_statistics VALUES
403                     ('$objectid', '$name', '$value')");
404    }
405    else
406    {
407       $dbms->query("UPDATE object_statistics SET statvalue='$value' WHERE
408            statname='$name' AND objectid='$objectid'");
409    }
410 }
411
412 /*
413  *   Gather the statistics for a single object ($objectid).
414  *   We count the number of parameters, removed parameters, notifications
415  *   closed notifications and log entries. The totals of these are
416  *   maintained in a separate table: object_statistics.
417  */
418
419 function GatherStatistics($objectid)
420 {
421    global $dbms;
422
423    //  Gather statistics on parameters
424
425    $r = $dbms->query("SELECT paramid FROM parameter WHERE objectid=CAST('"
426                         . $objectid . "' AS BIGINT)");
427    $nr_parameters = $dbms->num_rows($r);
428
429    $removed_parameters = 0;
430    for ($p = 0; $p < $nr_parameters; $p++)
431    {
432       $param = pg_fetch_object($r, $p);
433       $qry ="select change_nature from history where paramid= CAST('";
434       $qry .= $param->paramid . "' AS BIGINT) order by modified desc";
435       $rhist = $dbms->query($qry);
436       if ($dbms->num_rows($rhist) == 0)
437       {
438          echo "ERROR: No history for parameter id " . $param->paramid . "\n";
439       }
440       else
441       {
442          $hist = $dbms->fetch_object($rhist, 0);
443          if ($hist->change_nature == "REMOVED")
444          {
445             $removed_parameters++;
446          }
447       }
448    }
449
450    UpdateStatistic($objectid, 'parameters', $nr_parameters);
451    UpdateStatistic($objectid, 'removed_parameters', $removed_parameters);
452
453    //  Gather statistics on notifications
454
455    $r = $dbms->query("SELECT count(notificationid) FROM notification WHERE
456                        objectid = CAST('" . $objectid . "' AS BIGINT)");
457    $cnt = $dbms->fetch_object($r, 0);
458    UpdateStatistic($objectid, 'notifications', $cnt->count);
459
460    $r = $dbms->query("SELECT count(notificationid) FROM notification WHERE
461                        objectid = CAST('" . $objectid . "' AS BIGINT) AND statuscode ='cls'");
462    $cnt = $dbms->fetch_object($r, 0);
463    UpdateStatistic($objectid, 'closed_notifications', $cnt->count);
464
465    //  Gather statistics on log entries
466
467    $r = $dbms->query("SELECT count(logid) FROM log WHERE
468                        objectid = CAST('" . $objectid . "' AS BIGINT)");
469    $cnt = $dbms->fetch_object($r, 0);
470    UpdateStatistic($objectid, 'logs', $cnt->count);
471 }
472
473 //  Check for spam and other abuses in the log_adv tables.
474
475 function abuse_check($logstart)
476 {
477 return;   //  This function is obsolete
478    global  $dbms;
479
480   // notification: 'abuses exceeded'.
481
482    $noqueue_res = $dbms->query("select logid, source_ip from log_adv_daemon_email
483                                 where event='NOQUEUE' and logid > " . $logstart);
484    echo "NOQUEUE abuses:\n\n";
485    for ($row = 0; $row < $dbms->num_rows($noqueue_res); $row++)
486    {
487       $noqueue = $dbms->fetch_object($noqueue_res, $row);
488       if ($noqueue->source_ip != '')
489       {
490          $obj = $dbms->fetch_object(
491                        $dbms->query("SELECT objectid FROM log WHERE logid = '" . $noqueue->logid . "'"),0);
492          record_abuse(0, $obj->objectid, $noqueue->source_ip, 2);
493
494          // TODO: Create notification
495       }
496    } 
497    $dbms->Free($noqueue_res);
498
499    $noqueue_res = $dbms->query("select logid, source_ip, relay from log_adv_daemon_email
500                                 where event='SPAM' and logid > " . $logstart);
501    echo "SPAM abuses:\n\n";
502    for ($row = 0; $row < $dbms->num_rows($noqueue_res); $row++)
503    {
504       $noqueue = $dbms->fetch_object($noqueue_res, $row);
505       $source = $noqueue->source_ip;
506       if ($source == '')
507       {
508          $source = $noqueue->relay;
509       }
510       if ($source != '')
511       {
512          $obj = $dbms->fetch_object(
513                        $dbms->query("SELECT objectid FROM log WHERE logid = '" . $noqueue->logid . "'"),0);
514          record_abuse(0, $obj->objectid, $source, 1);
515
516          // TODO: Create notification
517       }
518    } 
519    $dbms->Free($noqueue_res);
520
521    echo "HTTP abuses:\n\n";
522    $abuse_res = $dbms->query("select logid, objectid, rawdata from log
523                               where servicecode='httpd' and logid > " . $logstart);
524    for ($row = 0; $row < $dbms->num_rows($abuse_res); $row++)
525    {
526       $source = '';
527       $abuse = $dbms->fetch_object($abuse_res, $row);
528       if (ereg("\[error\] \[client ([0-9.]+)\] request failed: URI too long", $abuse->rawdata, $parts))
529       {
530          echo $abuse->rawdata . "\n";
531          echo "Abuse on object " . $abuse->objectid . " from IP address " . $parts[1] . "\n";
532          $source = $parts[1];
533       }
534       if (ereg("\[error\] \[client ([0-9.]+)\] File does not exist: .+/MSADC",
535                $abuse->rawdata, $parts))
536       {
537          echo $abuse->rawdata . "\n";
538          echo "Abuse on object " . $abuse->objectid . " from IP address " . $parts[1] . "\n";
539          $source = $parts[1];
540       }
541       if ($source != '')
542       {
543          record_abuse(0, $abuse->objectid, $source, 2);
544
545          // TODO: Create notification
546       }
547    }
548    $dbms->Free($abuse_res);
549 }
550
551 function match_log_patterns($logstart)
552 {
553    global  $dbms;
554
555    $notifications = array();
556
557   // notification: 'abuses exceeded'.
558
559    $noqueue_res = $dbms->query("select logid, objectid, servicecode, rawdata from log where logid > " . $logstart
560                                  . " order by logid limit " . BATCHSIZE);
561    for ($row = 0; $row < $dbms->num_rows($noqueue_res); $row++)
562    {
563       $logentry = $dbms->fetch_object($noqueue_res, $row);
564       echo "\n----------\n" . $logentry->rawdata . "\n----------\n";
565       $service = $logentry->servicecode;
566       $pattern_res = $dbms->query("select * from service_pattern where service='$service'
567                                               OR service='ANY' order by rank");
568
569       $match_found = false;
570       for ($patnr = 0; !$match_found && $patnr < $dbms->num_rows($pattern_res); $patnr++)
571       {
572          $srv_pat = $dbms->fetch_object($pattern_res, $patnr);
573          if (ereg($srv_pat->pattern, $logentry->rawdata, $matches))
574          {
575             //  Scan the argument for '$n' expressions and expand
576
577             $srv_pat->argument = expand_arguments($srv_pat->argument, $matches);
578             echo "   " . $srv_pat->pattern . " matches.\n";
579             echo "   Matched string: " . $matches[0] . "\n";
580             echo "   Action = " . $srv_pat->action . "(" . $srv_pat->argument . ")\n\n";
581             $match_found = true;
582
583             switch ($srv_pat->action)
584             {
585             case "ignore":
586                break;
587
588             case "notify":
589                $notif = $srv_pat->argument;
590                if (!isset($notifications[$logentry->objectid][$notif]))
591                {
592                   echo "Creating notification $notif for object " . $logentry->objectid . ".\n";
593                   $remark = "Notification generated from Gnucomo pattern match.";
594                   $notifications[$logentry->objectid][$notif] =
595                          $dbms->new_notification($logentry->objectid, $notif, $remark);
596                }
597                if (isset($notifications[$logentry->objectid][$notif]))
598                {
599                   echo "Notification $notif for object " . $logentry->objectid . " already created.\n";
600                   $insertion = "INSERT INTO log_notification (notificationid, logid) VALUES ('";
601                   $insertion .= $notifications[$logentry->objectid][$notif] . "', '";
602                   $insertion .= $logentry->logid . "')";
603                   $dbms->query($insertion);
604                }
605                break;
606
607             case "abuse":
608                if (record_abuse($logentry->logid, $logentry->objectid, $srv_pat->argument, 1) >= 6)
609                {
610                   $source_ip = $srv_pat->argument;
611                   $notif = 'abuses exceeded';
612                   if (!isset($notifications[$logentry->objectid][$notif][$source_ip]))
613                   {
614                      echo "Creating notification $notif for object " . $logentry->objectid . ".\n";
615                      $remark = "Abuses from IP address $source_ip exceeded the limit.";
616                      $notifications[$logentry->objectid][$notif][$source_ip] =
617                             $dbms->new_notification($logentry->objectid, $notif, $remark);
618                   }
619                   if (isset($notifications[$logentry->objectid][$notif][$source_ip]))
620                   {
621                      echo "Notification $notif for object " . $logentry->objectid . " already created.\n";
622                      $insertion = "INSERT INTO log_notification (notificationid, logid) VALUES ('";
623                      $insertion .= $notifications[$logentry->objectid][$notif][$source_ip] . "', '";
624                      $insertion .= $logentry->logid . "')";
625                      $dbms->query($insertion);
626                   }
627                }
628                break;
629             default:
630                echo "Error: unrecognized action in service pattern: " . $srv_pat->action . "\n";
631                break;
632             }
633          }
634          else
635          {
636             echo "   " . $srv_pat->pattern . " does not match.\n";
637          }
638       }
639
640    }
641 }
642
643 /*
644  *  Some IP address abused us. Record the event.
645  *  Return the number of abuse points recorded so far for the address
646  */
647
648 function record_abuse($logid, $objectid, $sourceip, $points)
649 {
650    global  $dbms;
651
652    $abuse_points = $points;
653
654    $ipaddress = gethostbyname($sourceip);
655    echo " IP address for $sourceip is $ipaddress.\n";
656    $sourceip = $ipaddress;
657
658    $abres = $dbms->query("SELECT * FROM object_abuse WHERE objectid='$objectid' AND source='$sourceip'");
659
660    if (pg_numrows($abres) == 0)
661    {
662       echo "$sourceip is new.\n";
663       $dbms->query("INSERT INTO object_abuse VALUES ('$objectid', '$sourceip', '$points')");
664    }
665    else
666    {
667       $abuse = $dbms->fetch_object($abres, 0);
668       if ($abuse->status == '' || $abuse->status == 'dropped')
669       {
670          $abuse_points = $abuse->nr_abuses + $points;
671          echo $sourceip . " will get " . $abuse_points . " abuse points, ";
672          echo "Status was " . $abuse->status . "\n";
673          $dbms->query("UPDATE object_abuse SET nr_abuses='$abuse_points'" .
674                      " WHERE objectid='$objectid' AND source='$sourceip'");
675
676          $dbms->query("INSERT INTO log_abuse VALUES ('$logid', '$objectid', '$sourceip')");
677          if ($abuse_points >= 6)
678          {
679             echo "      BLOCK IP adrress $sourceip on the firewall.\n";
680             $dbms->query("UPDATE object_abuse SET status='dropped'" .
681                      " WHERE objectid='$objectid' AND source='$sourceip'");
682          }
683       }
684    }
685
686    return $abuse_points;
687 }
688
689
690 /*
691  *   Service_check - Check the log entries if there are any unknown
692  *   services.
693  */
694
695 function service_check()
696 {
697    global  $dbms;
698
699    $unknown_notification = array();
700    $unused_notification  = array();
701    $last_log             = 0;
702
703    //  How far did we get last time ?
704
705    $lastlogres = $dbms->query("SELECT setting_value FROM db_value
706                                WHERE setting = 'log_servicecheck'");
707
708    if ($dbms->num_rows($lastlogres) == 1)
709    {
710      $last_log = $dbms->Field($lastlogres, 0, 'setting_value');
711    }
712    else
713    {
714       $dbms->query("INSERT INTO db_value (setting, setting_value)
715                             VALUES ('log_servicecheck', '0')");
716    }
717
718    // Query the log-table
719
720    $qry = "SELECT logid, objectid, servicecode FROM log
721            WHERE logid > CAST(".$last_log." AS BIGINT) ORDER BY logid LIMIT " . BATCHSIZE;
722    $log_res = $dbms->query($qry);
723    //$log_res = $dbms->query("SELECT logid, objectid, servicecode,rawdata FROM log");
724
725    for ($log_row = 0; $log_row < $dbms->num_rows($log_res); $log_row++)
726    {
727       $log_entry = $dbms->fetch_object($log_res, $log_row);
728       $last_log  = $log_entry->logid;
729
730       //   Check if the service is used on the object.
731
732       $qry = "SELECT * FROM object_service WHERE objectid='";
733       $qry .= $log_entry->objectid . "' AND servicecode='";
734       $qry .= $log_entry->servicecode . "'";
735
736       $os_res = $dbms->query($qry);
737       if ($dbms->num_rows($os_res) == 0)
738       {
739          //   Service is not found for the object, check if the service
740          //   exists at all.
741
742          $qry = "SELECT * FROM service WHERE servicecode='";
743          $qry .= $log_entry->servicecode . "'";
744
745          if ($dbms->num_rows($dbms->query($qry)) == 0)
746          {
747             if (!isset($unknown_notification[$log_entry->objectid]))
748             {
749                $remark = "One or more log entries from a service that is not in the database";
750                $unknown_notification[$log_entry->objectid] =
751                          $dbms->new_notification($log_entry->objectid, 'service unknown', $remark);
752             }
753             if (isset($unknown_notification[$log_entry->objectid]))
754             {
755                $insertion = "INSERT INTO log_notification (notificationid, logid) VALUES ('";
756                $insertion .= $unknown_notification[$log_entry->objectid] . "', '";
757                $insertion .= $log_entry->logid . "')";
758                $dbms->query($insertion);
759             }
760          }
761          else
762          {
763             if (!isset($unused_notification[$log_entry->objectid]))
764             {
765                $remark = "One or more log entries from a service not running on this object";
766                $unused_notification[$log_entry->objectid] =
767                          $dbms->new_notification($log_entry->objectid, 'service not used', $remark);
768             }
769             if (isset($unused_notification[$log_entry->objectid]))
770             {
771                $insertion = "INSERT INTO log_notification (notificationid, logid) VALUES ('";
772                $insertion .= $unused_notification[$log_entry->objectid] . "', '";
773                $insertion .= $log_entry->logid . "')";
774                $dbms->query($insertion);
775             }
776          }
777       }
778    }
779
780    $qry = "UPDATE db_value SET setting_value = '"
781                    . $last_log . "' WHERE setting = 'log_servicecheck'";
782    $dbms->query($qry);
783 }
784
785 function find_notifications ()
786 {
787
788 /*
789  *  Do something with notification checks.
790  *
791  * INPUT  : NONE
792  * OUTPUT : NONE
793  */
794
795    global $dbms;
796
797    // Find checks that have to be executed.
798    $local_sql = "select * from notification_check where
799                     age(last_execution) > time_between_executions";
800    $dbms->query($local_sql);
801
802    for ($i=0; $i<$dbms->num_rows(); $i++)
803    {
804       // A check has been found that has to be executed
805       $dbms->fetch_row();
806    }
807 }
808
809 /*
810  *  find open notifications and send an email to the object's users.
811  */
812
813 function mail_notifications ()
814 {
815    global $dbms;
816
817    $notifres = $dbms->query("SELECT notificationid, objectid, type_of_issueid FROM notification
818                                WHERE statuscode != 'cls'");
819
820    for ($notifrow = 0; $notifrow < pg_numrows($notifres); $notifrow++)
821    {
822       $notification = pg_fetch_object($notifres, $notifrow);
823
824       $issue = pg_fetch_object($dbms->query("SELECT description FROM type_of_issue
825                                              WHERE type_of_issueid='" . $notification->type_of_issueid . "'"), 0);
826       echo "Mailing Notification for object id " . $notification->objectid . "\n";
827       $object = pg_fetch_object($dbms->query("SELECT objectname FROM object
828                                               WHERE objectid='" . $notification->objectid ."'"), 0);
829
830       $users = $dbms->query("SELECT username FROM object_user WHERE objectid='" . $notification->objectid . "'");
831
832       for ($userrow = 0; $userrow < pg_numrows($users); $userrow++)
833       {
834          $objusr = pg_fetch_object($users, $userrow);
835          $usr = pg_fetch_object($dbms->query("SELECT email FROM usr
836                                               WHERE username='" . $objusr->username . "'"), 0);
837
838          $message = "Notification " . $notification->notificationid . ": " . $issue->description;
839          $message .= "  for object " . $object->objectname . "\n";
840
841          mail($usr->email, "GnuCoMo Notification", $message);
842       }
843    }
844 }
845
846 /*
847  *   The 'command' may contain positional parameters such as '$1' and '$3',
848  *   just like the shell. These parameters are replaced by content from
849  *   the 'args' array.
850  */
851
852 function expand_arguments($command, $args)
853 {
854    while (ereg('\$([0-9]+)', $command, $match))
855    {
856       $index = $match[1];
857       if ($index >= count($args))
858       {
859          echo "Error: Argument $index not found for $command.\n";
860          $command = ereg_replace('\$' . $index, "", $command);
861       }
862       else
863       {
864          $command = ereg_replace('\$' . $index, $args[$index], $command);
865       }
866    }
867    return $command;
868 }
869
870 ?>
871