Subversion Repositories computer_asset_manager_v1

Rev

Rev 5 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
3 rodolico 1
<?php
2
 
3
/*
4
 * Requires php-pear and libyaml under Debian Wheezy
5
 * apt-get install php-pear php5-dev libyaml0dev
6
 * I don't know if you also need libyaml-0-2 libyaml-0-2-dbg
7
 * pecl install yaml
8
*/
9
 
10
require 'library.php';
11
 
12
$VERSION='0.8';
13
 
14
class sysinfo {
15
   private $report; // this will hold an entire report
16
   private $messages = array();
17
   private $FATAL = false;
18
   private $parsingArray;   // this is a required array that teaches how to properly parse the input
19
 
20
   // following are used internally to track important information
21
   private $clientID;   // id in database
22
   private $clientName; // name from report
23
   private $machineID;  // id in database
24
   private $machineName;// name in report
25
   private $reportDate; // unix timestamp of report
26
   private $reportDateSQL; // used for inserts and compares in the database
27
   private $serialNumber; // the serial number, which is assumed to be unique
28
   private $fileContents;
29
   private $processDuplicates = false; // used for testing; allows duplicate reports
30
   private $returnCode = 0; // how we returned from this
31
   private $errors = array( 1 => 'Could not process file, not xml, yaml or ini',
32
                            2 => 'Invalid report, does not have one or more of report date, client name or computer name',
33
                            3 => 'Invalid Report, invalid machine name',
34
                            4 => 'Duplicate Report',
35
                            5 => 'New Report, must be added to CAMP',
36
                            6 => 'Report is in queue for addition after updates to CAMP'
37
                          );
38
 
39
   /*
40
    * $parsingArray contains one or more rows, each of which have three rows, starttag, endtag and eval
41
    * starttag and endtag are regex's which match the beginning and end of a document (ie, --- and ... for yaml)
42
    * eval is an anonymous function which will evaluate a particular type of document, returning it as an
43
    * array which we store in $report
44
    */
45
 
46
   function __construct( $parsingArray ) {
47
      $this->parsingArray = $parsingArray;
48
   }
49
 
50
   public function processReport () {
51
      $this->validateReport(); // validate the report appears to be ok
52
      // prepend the name of the report to messages BEFORE any error messages that may have appeared
53
      array_unshift( $this->messages,
54
            "Report on $this->reportDateSQL, client $this->clientName, system $this->machineName ($this->fileType)");
55
      // now, we do every step in turn. If they set the FATAL flag, we exit.
56
      if ( $this->FATAL ) return $this->returnCode;
57
      $this->getMachineID();
58
      if ( empty( $this->machineID ) ) return $this->returnCode;
59
      $this->recordReport();
60
      if ( $this->FATAL) return $this->returnCode;
61
      $this->updateComputerMakeup();
62
      $this->updateOS();
63
      $this->updateBootTime();
64
      $this->doIPAddresses();
65
      $this->processPCI();
66
      $this->processSoftwarePackages();
67
      return $this->returnCode;;
68
   } // function processReport
69
 
70
   /* 
71
    * Name: loadFromFile
72
    * Parameters: filename (path to load file from)
73
    * Returns: true if on success, false if not
74
    * Modifies: 
75
    *    report - added messages on why the report is not valid
76
    *    FATAL    - set to true if any of the required values do not exist
77
    */
78
 
79
   public function loadFromFile ( $filename ) {
80
      // load file into memory. Additionally, remove any \r's from it (leaving \n's for newlines)
81
      $this->fileContents = str_replace("\r","", file_get_contents( $filename ) );
82
      // try to parse the body out
83
      $this->getBody();
84
      if ( isset( $this->report ) ) {
85
         if ( $this->fileType == 'xml' ) $this->fixXML();
86
         if ( $this->fileType == 'ini' ) {
87
            $this->messages[] = 'We do not process ini files, but storing it instead';
88
         }
89
         return $this->fileType;
90
      } else { // we don't know what it is
91
         $this->FATAL = true;
92
         $this->messages[] = "Unable to parse [$filename] using YAML, XML or INI";
93
         return false;
94
      }
95
      //unset( $this->fileContents ); // free up memory
96
   } // function loadFromFile
97
 
98
 
99
   // once the file has been loaded, we need to figure out what kind of file it is
100
   // then use the function embedded in $parsingArray to import it.
101
   private function getBody ( ) {
102
      foreach ( $this->parsingArray as $key => $regexes ) {
103
         $matches;
104
         $pattern = $regexes['startTag'] . '.*' . $regexes['endTag'];
105
         if ( preg_match( "/$pattern/ms", $this->fileContents, $matches ) ) {
106
            $this->fileType = $key;
107
            $this->fileContents = $matches[0];
108
            $this->report = $regexes['eval']($this->fileContents);
109
            return true;
110
         } // if
111
      } // foreach
112
      return false;
113
   }
114
 
115
   /*
116
    * Name: fixXML
117
    * Parameters: None
118
    * Returns: nothing
119
    * Modifies: $this->report
120
    * YAML creates the entries as ['network']['interface name']
121
    * XML  creates the entries as ["network"][x][name]=>
122
    * We will simply copy the XML information into a duplicate
123
    * in YAML style
124
    */
125
   private function fixXML() {
126
       $oldInfo = $this->report['network'];
127
       unset ($this->report['network']);
128
       foreach ( $oldInfo as $entry ) {
129
          #$this->messages[] = "Duplicating network entry for $entry[name]";
130
          foreach ($entry as $key => $value ) {
131
             $this->report['network'][$entry['name']][$key] = $value;
132
             #$this->messages[] = "  Adding  $value as value for network.name.$key";
133
          } // inner foreach
134
       } // outer foreach
135
   } // fixXML
136
 
137
 
138
   private function processINI() {
139
      return false;
140
   }
141
 
142
   public function dumpMessages () {
143
      $return = implode( "\n", $this->messages );
144
      $return .= "\n";
145
      return $return;
146
   }
147
 
148
   /* 
149
    * Name: validateReport
150
    * Parameters: none
151
    * Returns: true if valid, false if not
152
    * Modifies: 
153
    *    messages - added messages on why the report is not valid
154
    *    FATAL    - set to true if any of the required values do not exist
155
    */
156
 
157
      public function validateReport () {
158
      /*
159
       * A report is considered valid if it has a date, client name and hostname
160
       * No check is made at this time for validity of that data
161
       */
162
      if ( empty( $this->report['report']['date']) ) {
163
         $this->messages[] = 'No report date';
164
      } else {
165
         $this->reportDate = strtotime( $this->report['report']['date'] ); // store in Unix timestamp
166
         $this->reportDateSQL = strftime( '%F %T', $this->reportDate ); // save a copy of the date in SQL format
167
         if ( empty( $this->reportDate ) )
168
            $this->messages[] = "Unable to parse report date [$this->report['report']['date']]";
169
      }
170
 
171
      if ( empty( $this->report['report']['client'] ) ) {
172
         $this->messages[] = 'No client name';
173
      } else {
174
         $this->clientName = $this->report['report']['client'];
175
      }
176
 
177
      if ( empty ( $this->report['system']['hostname'] ) ) {
178
         $this->messages[] = 'No Computer Name';
179
      } else {
180
         $this->machineName = $this->report['system']['hostname'];
181
      }
182
      $this->FATAL = ! empty( $this->messages );
183
 
184
      // serial number is fairly new, so it is not a critical error
185
      // it will be set in getMachineID if we have it here, but not there
186
      if ( empty ( $this->report['system']['serial'] ) ) {
187
         $this->messages[] = 'No Serial Number';
188
      } else {
189
         $this->serialNumber = $this->report['system']['serial'];
190
      }
191
 
192
   } // function validateReport
193
 
194
 
195
   /* 
196
    * Name: getMachineID
197
    * Parameters: none
198
    * Returns: true if found, false if not
199
    * Modifies: 
200
    *    clientID - index value of client in database
201
    *    machineID - index value of machine in database
202
    */
203
   private function getMachineID () {
204
      $this->clientID = getClientID( $this->clientName );
205
      if ( $this->clientID ) {
206
         $this->machineID = getMachineID( $this->machineName, $this->clientID, $this->serialNumber );
207
      }
208
      if ( empty( $this->machineID ) ) {
209
         $this->messages[] = $this->makeUnknown( $this->clientName, $this->machineName, $this->reportDateSQL );
210
         return false;
211
      }
212
      if ( $this->machineID == -1 ) {
213
         $this->messages[] = "Duplicate serial number found for serial [$this->serialNumber], aborting";
214
         return false;
215
      }
216
      return true;
217
   } // function getMachineID
218
 
219
   /* 
220
    * checks for a duplicate report, ie one that has already been run.
221
    * if this computer has a report already for this date/time
222
    */ 
223
   private function recordReport() {
224
      $count = getOneDBValue("select count(*) from sysinfo_report where device_id = $this->machineID and report_date = '$this->reportDateSQL'");
225
      if ( $this->processDuplicates ) { $count = 0; } // for testing
226
      if ( $count ) {
227
         $this->messages[] = "Duplicate Report for $this->machineName (id $this->machineID) on $this->reportDateSQL";
228
         $this->returnCode = 4;
229
         $this->FATAL = true;
230
         return false;
231
      }
232
      $version = $this->report['report']['version'];
233
      # if we made it this far, we are ok, so just add the report id
234
      queryDatabaseExtended("insert into sysinfo_report(device_id,version,report_date,added_date) values ($this->machineID ,'$version','$this->reportDateSQL',now())");
235
      $this->reportID = getOneDBValue("select max( sysinfo_report_id ) from sysinfo_report where device_id = $this->machineID and report_date = '$this->reportDateSQL'");
236
      return true;
237
   }
238
 
239
 
240
   function makeUnknown( $clientName, $machineName, $reportDate ) {
241
      $result = getOneDBValue("select report_date from unknown_entry where client_name = '$clientName' and device_name = '$machineName'");
242
      if ( empty( $result ) ) {
243
         queryDatabaseExtended( "insert into unknown_entry(client_name,device_name,report_date) values ('$clientName', '$machineName', '$reportDate')");
244
         $this->returnCode = 5;
245
         return "New entry, client=$clientName, device=$machineName. You must update Camp before this report can be processed";
246
      } else {
247
         $this->returnCode = 6;
248
         return "New entry detected, but entry already made. You must update Camp before this can be processed";
249
      }
250
   }
251
 
252
   # simply used to get an attrib_id. If it does not exit, will create it
253
 
254
   private function getAttributeID ( $attributeName, $reportDate ) {
255
      $attributeName = makeSafeSQLValue( $attributeName );
256
      $result = getOneDBValue( "select attrib_id from attrib where name = $attributeName and removed_date is null" );
257
      if ( !isset( $result) ) {
258
         $result = queryDatabaseExtended( "insert into attrib (name,added_date) values ($attributeName,'$reportDate')");
259
         $this->messages[] = "Added a new attribute type [$attributeName]";
260
         $result = $result['insert_id'];
261
      }
262
      return $result;
263
   }
264
 
265
   /*
266
    * Checks an attribute from the device_attriburtes table. If the value has
267
    * changed, sets the old one's removed_date to this report date, then adds
268
    * new record for new value.
269
    * If the record does not exist, simply creates it
270
    */
271
   public function checkAndUpdateAttribute( $attribute, $value ) {
272
      if ( !isset($attribute) || !isset($value ) ) {
273
         $this->messages[] = "Error: attempt to use null value for [$attribute], value [$value] for ID $this->machineID in checkAndUPdateAttribute";
274
         return false;
275
      }
276
      $value = makeSafeSQLValue($value); # we want to always quote the value on this particular one
277
      //$attribute = makeSafeSQLValue( $attribute );
278
      $attrib_id = $this->getAttributeID( $attribute, $this->reportDateSQL );
279
      $result = getOneDBValue( "select device_attrib.value
280
         from device_attrib join attrib using (attrib_id)
281
         where device_attrib.device_id = $this->machineID
282
               and device_attrib.removed_date is null
283
               and attrib.attrib_id = $attrib_id
284
         ");
285
      $result = makeSafeSQLValue( $result ); # we must do this since we are comparing to $value which has had this done
286
      if ( isset( $result ) ) { # got it, now see if it compares ok
287
         if ( $value != $result ) { # nope, this has changed. Note, must use fixDatabaseValue for escapes already in $value
288
            $this->messages[] = "New value [$value] for $attribute for device $this->machineID, voiding previous";
289
            queryDatabaseExtended( "update device_attrib
290
                                       set removed_date = '$this->reportDateSQL'
291
                                    where device_id = $this->machineID
292
                                          and attrib_id = $attrib_id
293
                                          and removed_date is null");
294
            unset( $result ); # this will force the insert in the next block of code
295
         } # if $result ne $value
296
      } # if ($result)
297
      if ( ! isset( $result ) ) { # we have no valid entry for this attribute
298
         //$this->messages[] = "In checkAndUpdateAttribute, adding new record with insert into device_attrib(device_id,attrib_id,value,added_date) values ($this->machineID,$attrib_id,$value,$this->reportDateSQL)";
299
         queryDatabaseExtended( "insert into device_attrib(device_id,attrib_id,value,added_date)
300
                                 values ($this->machineID,$attrib_id,$value,'$this->reportDateSQL')");
301
         return true;
302
      }
303
      return false;
304
   } // checkAndUpdateAttribute
305
 
306
   # simply verifies some attributes of the computer
307
   private function updateComputerMakeup() {
308
      $this->checkAndUpdateAttribute('Memory',        $this->report['system']['memory']);
309
      $this->checkAndUpdateAttribute('Number of CPUs',$this->report['system']['num_cpu']);
310
      $this->checkAndUpdateAttribute('CPU Type',      $this->report['system']['cpu_type']);
311
      $this->checkAndUpdateAttribute('CPU SubType',   $this->report['system']['cpu_sub']);
312
      $this->checkAndUpdateAttribute('CPU Speed',     $this->report['system']['cpu_speed']);
313
   } // updateComputerMakeup
314
 
315
   // This is kind of funky, because column = null does not work, it must be column is null, so we have to look for it.
316
   function makeSQLEquals ( $field, $value ) {
317
      return "$field " . ( $value == 'null' ? 'is null' : '=' . $value );
318
   }
319
 
320
 
321
   private function updateOS () {
322
      // find os
323
      $osName =         makeSafeSQLValue( isset($this->report['operatingsystem']['os_name'])         ? $this->report['operatingsystem']['os_name'] : '');
324
      $kernel =         makeSafeSQLValue( isset($this->report['operatingsystem']['kernel'])          ? $this->report['operatingsystem']['kernel'] : '');
325
      $distro_name =    makeSafeSQLValue( isset($this->report['operatingsystem']['os_distribution']) ? $this->report['operatingsystem']['distribution'] : '');
326
      $release =        makeSafeSQLValue( isset($this->report['operatingsystem']['os_release'])      ? $this->report['operatingsystem']['release'] : '');
327
      $version =        makeSafeSQLValue( isset($this->report['operatingsystem']['os_version'])      ? $this->report['operatingsystem']['os_version'] : '');
328
      $description =    makeSafeSQLValue( isset($this->report['operatingsystem']['description'])     ? $this->report['operatingsystem']['description'] : '');
329
      $codename =       makeSafeSQLValue( isset($this->report['operatingsystem']['codename'])        ? $this->report['operatingsystem']['codename'] : '');
330
 
331
      $osID = getOneDBValue( "select operating_system_id from operating_system
332
               where " . $this->makeSQLEquals( 'name', $osName ) . "
333
                  and " . $this->makeSQLEquals( 'kernel', $kernel ) . "
334
                  and " . $this->makeSQLEquals( 'distro', $distro_name ) . "
335
                  and " . $this->makeSQLEquals( 'distro_release', $release ) );
336
      if ( !isset( $osID ) ) {
337
         $this->messages[] = "Creating a new OS with name = $osName, kernel = $kernel, distro = $distro_name,  distro_release = $release";
338
         $result = queryDatabaseExtended( "insert into operating_system (name,version,kernel,distro,distro_description,distro_release,distro_codename, added_date) values
339
                                          ($osName,$version,$kernel,$distro_name,$description,$release,$codename, '$this->reportDateSQL')" );
340
         $osID = $result['insert_id'];
341
      }
342
 
343
      # verify the operating system
344
      $registeredOS = getOneDBValue( "select operating_system_id from device_operating_system where device_id = $this->machineID and removed_date is null" );
345
      if ( ! $registeredOS || $registeredOS != $osID ) {
346
         if ( $registeredOS ) { #we have the same computer, but a new OS???
347
            queryDatabaseExtended( "update device_operating_system set removed_date = '$this->reportDateSQL' where device_id = $this->machineID and removed_date is null");
348
            $this->messages[] = "Computer $this->machineName has a new OS";
349
         }
350
         queryDatabaseExtended( "insert into device_operating_system( device_id,operating_system_id,added_date) values ($this->machineID,$osID,'$this->reportDateSQL')");
351
      }
352
   }
353
 
354
   # every time we get a report, we need to see if the computer was rebooted
355
   # if last reboot date is not the same as what our report shows, we will
356
   # remove the existing entry, then add a new one
357
   private function updateBootTime() {
358
      $lastReboot;
359
      if ( isset( $this->report['system']['last_boot'] ) ) {
360
         $lastReboot = strftime( '%F %T',$this->report['system']['last_boot'] ); // convert unix timestamp to sql value
361
         if ( isset( $lastReboot ) ) {
362
            if ( ! getOneDBValue( "select computer_uptime_id from computer_uptime where device_id = $this->machineID and last_reboot = '$lastReboot'" ) ) {
363
               $this->messages[] = "Computer was rebooted at $lastReboot";
364
               queryDatabaseExtended( "update computer_uptime set removed_date = '$this->reportDateSQL' where device_id = $this->machineID and removed_date is null" );
365
               queryDatabaseExtended( "insert into computer_uptime (device_id,added_date,last_reboot) values ($this->machineID,'$this->reportDateSQL','$lastReboot')");
366
            }
367
         } else {
368
            $this->messages[] = 'Invalid reboot time [' . $this->Report['system']['last_boot'] . ']';
369
         }
370
      } else {
371
         $this->messages[] = 'No Boot time given';
372
      }
373
   }
374
 
375
 
376
   // checks if the report and the database values are the same
377
   private function checkInterfaceEquals( $report, $database ) {
378
      //var_dump( $report );
379
      //var_dump( $database );
380
      return ( 
381
         $report['address'] == $database['address'] and
382
         $report['netmask'] == $database['netmask'] and
383
         $report['ip6address'] == $database['ip6'] and
384
         $report['ip6networkbits'] == $database['ip6net'] and
385
         $report['mtu'] == $database['mtu'] and
386
         $report['mac'] == $database['mac'] 
387
         );
388
   } // checkInterfaceEquals
389
 
390
 
391
   /*
392
    * routine will check for all IP addresses reported and check against those recorded in the
393
    * database. It will remove any no longer in the database, and add any new ones
394
    */
395
   private function doIPAddresses () {
396
      /*
397
       * get all interfaces from the database
398
       * remove any interfaces from database which are not in report
399
       * add any interfaces from report which are not in database or which have changed
400
       */
401
      $network = $this->report['network']; // make a copy so we don't modify the original report
402
      // we won't process lo
403
      unset ($network['lo']);
404
      // at this point, we could get rid of tun's also, if we wanted to
405
 
406
      // let's ensure that all rows in report have the minimum required data
407
      foreach ( array_keys( $network ) as $interface ) {
408
         foreach ( array( 'address','netmask','ip6address','ip6networkbits','mtu','mac' ) as $required ) {
409
            if ( ! isset( $network[$interface][$required] ) ) { 
410
               $network[$interface][$required]  = NULL; 
411
            }
412
         } // checking all keys
413
      } // checking all report rows
414
      // var_dump( $network );   
415
 
416
      // get current information on all active interfaces in the database
417
      $dbInterfaces = queryDatabaseExtended( "select network_id,interface,address,netmask,ip6,ip6net,mac,mtu from network where device_id = $this->machineID and removed_date is null" );
418
      //print "select network_id,interface,address,netmask,ip6,ip6net,mac,mtu from network where device_id = $this->machineID and removed_date is null\n";
419
      //var_dump($dbInterfaces);
420
 
421
      // now, get rid of any interfaces which are no longer in the database
422
      // get a list of interfaces being passed in by report as a comma delimited list for processing.
423
      foreach ( array_keys( $network) as $temp ) {
424
         $interfaces[] = "'$temp'";
425
      }
426
      $interfaces = implode( ',', $interfaces );
427
      if ( $interfaces ) { // are there any? Then simply remove anything not in their set.
428
         queryDatabaseExtended( "update network set removed_date = '$this->reportDateSQL' where device_id = $this->machineID and removed_date is null and interface not in ($interfaces)");
429
         // print "update network set removed_date = '$this->reportDateSQL' where device_id = $this->machineID and removed_date is null and interface not in ($interfaces)\n";
430
         // reload the database results to exclude the ones we removed above
431
         $dbInterfaces = queryDatabaseExtended( "select network_id,interface,address,netmask,ip6,ip6net,mac,mtu from network where device_id = $this->machineID and removed_date is null" );
432
         // print "select network_id,interface,address,netmask,ip6,ip6net,mac,mtu from network where device_id = $this->machineID and removed_date is null\n";
433
      } // if
434
      // at this point, the database is a subset of the report, ie there are no entries in the database which are not also in the report.
435
      // let's remove the ones which are the same from both sets.
436
      // we can take a shortcut since the database is a subset of the report, ie we can remove entries from the report as we process
437
      if ( $dbInterfaces ) { // do we have anything in the database?
438
         foreach ( $dbInterfaces['data'] as $row => $value ) {
439
            // print "checking if " . $network[$value['interface']] . " equals $value\n";
440
            if ( $this->checkInterfaceEquals( $network[$value['interface']], $value ) ) { // compare the two entries
441
               // print "\tIt Does, so deleting it from updates\n";
442
               unset( $network[$value['interface']] );
443
            } else { // they are not equal. We will simply void out the existing one and it will treat the report entry as a new entry.
444
               // print "\tit is an update, so setting to removed in database\n";
445
               queryDatabaseExtended( "update network set removed_date = '$this->reportDateSQL' where device_id = $this->machineID and removed_date is null and interface = '" . $value['interface'] . "'");
446
               // print "update network set removed_date = '$this->reportDateSQL' where device_id = $this->machineID and removed_date is null and interface = '" . $value['interface'] . "'\n";
447
            } // if..else
448
         } // foreach
449
      }
450
      // finally, we should have only new entries, or entries which have changed and have been voided
451
      // a new row should be created for anything left.
452
      foreach ( $network as $interface => $values ) {
453
         //var_dump( $values );
454
         $sql = implode ( ',', array( 
455
                              $this->machineID,
456
                              makeSafeSQLValue($this->reportDateSQL),
457
                              makeSafeSQLValue($interface),
458
                              makeSafeSQLValue($values['address']),
459
                              makeSafeSQLValue($values['netmask']),
460
                              makeSafeSQLValue($values['ip6address']),
461
                              makeSafeSQLValue($values['ip6networkbits']),
462
                              makeSafeSQLValue($values['mtu']),
463
                              makeSafeSQLValue($values['mac'])
464
                              )
465
                         );
466
         $sql = "insert into network (device_id,added_date,interface,address,netmask,ip6,ip6net,mtu,mac) values (" . $sql . ")";
467
         //$this->messages[] = $sql;
468
         queryDatabaseExtended( $sql );
469
         $this->messages[] = "Network Device $interface was added/modified";
470
      }
471
   } // doIPAddresses
472
 
473
 
474
   /*
475
    * function looks through every element of $report, for a subkey
476
    * named 'keyfield'. It turns those into a string appropriate for
477
    * inclusion in a query as 
478
    * where fieldname in ( $keylist )
479
    * For example, with values a, b, c, 54, q'
480
    * returns 'a','b','c','54','q\''
481
    * where $keylist is generated by this function
482
    * returns null if no values found
483
    */ 
484
   function getKeyList ( $report ) {
485
      $keys = array();
486
      $keyset = null;
487
      // every row should have a key 'keyfield'.Since we don't know 
488
      // what they are, be sure to make sure they are SQL Safe
489
      foreach ( $report as $key => $value ) {
490
         $keys[] = makeSafeSQLValue( $value['keyfield'] );
491
      }
492
      return $keys ? implode( ",\n", $keys ) : null;
493
   }
494
 
495
   /*
496
    * function checks all keys in $first and $second to see if they
497
    * match. If they do, returns true, else returns false
498
    * ignores any keys passed in as array $ignore
499
    */
500
   function rowMatches ( $first, $second, $ignore = array() ) {
501
      foreach ( $first as $fkey => $fValue ) {
502
         if ( in_array( $fkey, $ignore ) )
503
            continue;
504
         if ( $fValue == $second[$fkey] )
505
            continue;
506
         return false;
507
      }
508
      return true;
509
   } // rowMatches
510
 
511
   /* Generic function that will 
512
    * delete items in database not found in report
513
    * Clean up report to contain only those items which are to be added
514
    * Return a copy of the report.
515
    * 
516
    * NOTE: since we are deleting items not found in the report, we will then
517
    * subsequently add them. This is the update process since we never actually
518
    * "delete" anything from the database.
519
    * 
520
    * Requires the report, and report must have a key for each entry named
521
    * 'keyfield' which the query below may use (as special tag <keys>
522
    * Also uses the following queries. If a query does not exist, that
523
    * process is ignored
524
    * 'remove old' - should have an entry as <device_id> which will have the current
525
    *       machine ID placed in it
526
    * 'delete' - <ids> which will be replaced with a list of keys from the 
527
    *         report.
528
    * 'find' - should return a column named 'id' which is a primary key on the
529
    *          table (used by delete query), and a column named 'keyfield'
530
    *          which matches the same one in the report. Any other fields in
531
    *          the query are checked against the report, and the report and
532
    *          database entry are only considered matching if all query fields
533
    *          match a report entry.
534
    * 
535
    * Before passing in report, you should go through the entries and create
536
    * a new one called 'keyfield' for each entry which will be a unique key
537
    * for an entry. For example, software packages may be the package name
538
    * and the version.
539
    */
540
   private function AddDeleteUpdate ( $report, $queries, $reportLabel, $testing=false ) {
541
 
542
      if ( $testing ) {
543
         print "*****************Starting\n"; 
544
         print_r( $report ); 
545
         print "*****************Starting\n";
546
      }
547
      $database = null;
548
      $keySet = $this->getKeyList( $report );
549
      if ( is_null( $keySet ) ) // bail if we don't have any data
550
         return null;
551
 
552
      // find values which are in database but not in report and delete them from database
553
      if ( $queries['remove old'] ) {
554
         $queries['remove old'] = str_replace( '<keys>', $keySet, $queries['remove old'] );
555
         $queries['remove old'] = str_replace( '<device_id>', $this->machineID, $queries['remove old'] );
556
         if ( $testing )
557
            print "Remove Query***************************\n" . $queries['remove old'] . "\n***********************************\n";
558
         else {
559
            $database = queryDatabaseExtended( $queries['remove old'] );
560
            if ( $database and $database['affected_rows'] ) 
561
               $this->messages[] = $database['affected_rows'] . " $reportLabel removed from database because they were removed for superceded";
562
         } // else
563
      } // if
564
 
565
      // now, let's get all the values left in the database
566
      if ( $queries['find'] ) {
567
         $queries['find'] = str_replace( '<keys>', $keySet, $queries['find'] );
568
         $queries['find'] = str_replace( '<device_id>', $this->machineID, $queries['find'] );
569
         if ( $testing )
570
            print "Find Query***************************\n" . $queries['find'] . "\n***********************************\n";
571
         else
572
            $database = queryDatabaseExtended( $queries['find'] );
573
      }
574
      if ( $database ) { // there were entries in the database still
575
         $database = $database['data']; // get to the data
576
         $keysToDelete = array();
577
         // find values which are different in report, and delete the database entry
578
         foreach ( $database as $row => $entries ) {
579
            foreach ( $report as $key => $values ) {
580
               if ( $report[$key]['keyfield'] != $entries['keyfield'] )
581
                  continue;
582
               // if we made it here, our keyfields match, so we check
583
               // the contents of the other fields
584
               if ( $this->rowMatches( $entries, $values, array( 'keyfield', 'id' ) ) ) {
585
                  // they match, so remove it from the report
586
                  unset( $report[$key] );
587
               } else { // they are different in the report, so remove from database
588
                  $keysToDelete[] = $entries['id'];
589
               }
590
            } // inner foreach
591
         } // outer foreach
592
         if ( $keysToDelete and $queries['delete'] ) {
593
            $queries['delete'] = str_replace( '<ids>', implode( ',', $keysToDelete ), $queries['delete'] );
594
            if ( $testing )
595
               print "Delete Query***************************\n" . $queries['delete'] . "\n***********************************\n";
596
            else {
597
               $updates = queryDatabaseExtended( $queries['delete'] );
598
               $this->messages[] = $updates['affected_rows'] . " $reportLabel modified";
599
            }
600
         }
601
      } // if $database
602
      // return items to be added
603
      if ( $testing ) {
604
         print "*****************Ending\n"; 
605
         print_r( $report ); 
606
         print "*****************Ending\n";
607
      }
608
      return $report;
609
   } // function AddDeleteUpdate
610
 
611
 
612
   /*
613
    * routine to ensure the hardware returned as PCI hardware is in the attributes area
614
    */ 
615
   private function processPCI ( ) {
616
      // following are some of the synonyms we will use from the PCI
617
      // tables for the "name" of the device. They are listed in the
618
      // order of priority (ie, first one found is chosen).
619
      $nameSynomyms = array('name','device','sdevice','device0');
620
 
621
      // query which removes devices from database that are not in report
622
      // we assume if the report doesn't have it, it has been removed
623
      $queries['remove old'] = 
624
                    "update device
625
                        set removed_date = '$this->reportDateSQL'
626
                        where device_id in (
627
                           select device_id from (
628
                              select
629
                                    device_id
630
                                 from
631
                                    device join device_type using (device_type_id)
632
                                 where
633
                                    device.part_of = <device_id>
634
                                    and device.removed_date is null
635
                                    and device.name not in ( <keys> )
636
                              ) as b
637
                              )";
638
 
639
 
640
      $queries['find'] = 
641
                    "select
642
                        device_id id,
643
                        device.name  'keyfield',
644
                        device.notes 'info'
645
                     from device join device_type using (device_type_id) 
646
                     where
647
                        device_type.name = 'PCI Card' 
648
                        and device.removed_date is null
649
                        and device.part_of = <device_id>";
650
 
651
      $queries['delete'] =
652
                    "update device
653
                        set removed_date = '$this->reportDateSQL'
654
                        where device_id in ( <ids> )";
655
 
656
 
657
      if ( ! isset( $this->report['pci'] ) ) return;
658
      // make a local copy so we can modify as needed
659
      $pciHash = $this->report['pci'];
660
      # normalize the data
661
      foreach ( array_keys( $pciHash ) as $key ) {
662
         if ( ! is_array( $pciHash[$key] ) ) {
663
            $this->messages[] = 'Invalid PCI format, not recording';
664
            return false;
665
         }
666
         if ( ! isset( $pciHash[$key]['slot'] ) ) { // doesn't have a slot field
667
            $slotField = '';
668
            foreach ( array_keys( $pciHash[$key] ) as $subkey ) { // scan through all keys and see if there is something with a "slot looking" value in it
669
               if ( preg_match ( '/^[0-9a-f:.]+$/' , $pciHash[$key][$subkey] ) )
670
                  $slotField = $subkey;
671
            }
672
            if ( $slotField ) {
673
               $pciHash[$key]['slot'] = $pciHash[$key][$slotField];
674
            } else {
675
               $pciHash[$key]['slot'] = 'Unknown';
676
            }
677
         }
678
         // Each entry must have a name. Use 'device' if it doesn't exist
679
         // Basically, we try each option in turn, with the first test having
680
         // priority.
681
 
682
         if ( ! isset( $pciHash[$key]['name'] ) ) {
683
            // if there is no name, try to use one of the synonyms
684
            foreach ( $nameSynomyms as $testName ) {
685
               if ( isset ( $pciHash[$key][$testName] ) ) {
686
                  $pciHash[$key]['name'] = $pciHash[$key][$testName];
687
                  break;
688
               } // if
689
            } // foreach
690
            if ( empty( $pciHash[$key]['name'] ) ) {
691
               $this->messages[] = "No name given for one or more PCI devices at normalize, Computer ID: [$this->machineID], Report Date: [$this->reportDate]";
692
               //print_r( $pciHash ); 
693
               //die;
694
               return;
695
            }
696
         } elseif ( $pciHash[$key]['name'] == $pciHash[$key]['slot'] ) {
697
            $pciHash[$key]['name'] = $pciHash[$key]['device'];
698
         } // if..else
699
         // Following is what will actually be put in the device table, ie device.name
700
         $pciHash[$key]['keyfield'] = $pciHash[$key]['slot'] . ' - ' . $pciHash[$key]['name'];
701
         ksort( $pciHash[$key] );
702
         $ignore = array( 'keyfield' );
703
         $info = '';
704
         foreach ( $pciHash[$key] as $subkey => $value ) {
705
            if ( in_array( $subkey, $ignore ) )
706
               continue;
707
            $info .= "[$subkey]=$value\n";
708
         }
709
         $pciHash[$key]['info'] = $info;
710
      } // foreach
711
      // at this point, we should have a slot and a name field in all pci devices
712
      $toAdd = $this->AddDeleteUpdate( $pciHash, $queries, 'PCI Devices' );
713
      if ( $toAdd ) {
714
         $pciCardID = getOneDBValue( "select device_type_id from device_type where name = 'PCI Card'");
715
         $count = 0;
716
         foreach ( $toAdd as $entry => $values ) {
717
            $keyfield = makeSafeSQLValue( $values['keyfield'] );
718
            $info = makeSafeSQLValue( $values['info'] );
719
            $query = "insert into device 
720
                        select 
721
                           null,
722
                           site_id,
723
                           $pciCardID,
724
                           $keyfield,
725
                           $info,
726
                           device_id,
727
                           '$this->reportDateSQL',
728
                           null,
729
                           null 
730
                        from device 
731
                        where device_id = $this->machineID";
732
            queryDatabaseExtended( $query );
733
            $count++;
734
         } // foreach
735
         $this->messages[] = "$count PCI devices added/modified";
736
      } // if
737
   } // processPCI
738
 
739
   function getSoftwareID ( $packageName,$versionInfo,$description ) {
740
      $packageName = makeSafeSQLValue( $packageName );
741
      $versionInfo = makeSafeSQLValue( $versionInfo );
742
      $description = makeSafeSQLValue( $description );
743
      // does the package exist?
744
      $packageID = getOneDBValue("select software_id from software where package_name = $packageName and removed_date is null");
745
      if ( !$packageID ) { # NO, package doesn't exist, so add it to the database
746
         $packageID = queryDatabaseExtended( "insert into software (package_name,description, added_date) values ($packageName,$description, '$this->reportDateSQL')");
747
         if ( $packageID['insert_id'] )
748
            $packageID = $packageID['insert_id'];
749
         else {
750
            $this->messages[] = "ERROR: Software Packages - Could not find version $packageName and could not add to database";
751
            $packageID = null;
752
         }
753
      }
754
      // does this version number exist?
755
      $versionID = getOneDBValue( "select software_version_id from software_version where version = $versionInfo and removed_date is null" );
756
      if ( ! $versionID ) { # nope, so add it
757
         $versionID = queryDatabaseExtended( "insert into software_version ( version,added_date ) values ($versionInfo,'$this->reportDateSQL')");
758
         if ( $versionID['insert_id'] )
759
            $versionID = $versionID['insert_id'];
760
         else {
761
            $this->messages[] = "ERROR: Software Packages - Could not find version $versionInfo and could not add to database";
762
            $versionID = null;
763
         }
764
      }
765
      return array( 'package id' => $packageID,'version id' => $versionID);
766
   } // getSoftwareID
767
 
768
 
769
   function processSoftwarePackages (  ) {
770
      // query which removes devices from database that are not in report
771
      // we assume if the report doesn't have it, it has been removed
772
      $queries['remove old'] = 
773
                    "update installed_packages
774
                        set removed_date = '$this->reportDateSQL'
775
                        where installed_packages_id in (
776
                           select installed_packages_id from (
777
                              select
778
                                    installed_packages_id
779
                              from 
780
                                 installed_packages 
781
                                 join software using ( software_id )
782
                                 join software_version using (software_version_id)
783
                              where
784
                                    installed_packages.device_id = <device_id>
785
                                    and installed_packages.removed_date is null
786
                                    and concat(software.package_name,software_version.version) not in ( <keys> )
787
                              ) as b
788
                              )";
789
      $queries['find'] = 
790
           "select 
791
               installed_packages.installed_packages_id 'id',
792
               concat(software.package_name,software_version.version) 'keyfield'
793
            from 
794
               installed_packages 
795
               join software using ( software_id )
796
               join software_version using (software_version_id)
797
            where 
798
               device_id = <device_id>
799
               and installed_packages.removed_date is null";
800
      $queries['delete'] =
801
                    "update installed_packages
802
                        set removed_date = '$this->reportDateSQL'
803
                        where installed_packages_id in ( <ids> )";
804
 
805
      if ( ! isset( $this->report['software'] ) ) return;
806
      // make a local copy so we can modify as needed
807
      $softwareHash = $this->report['software'];
808
      foreach ( array_keys( $softwareHash ) as $key ) {
809
         if ( ! isset( $softwareHash[$key]['name'] ) )
810
            $softwareHash[$key]['name'] = $key;
811
         if ( ! isset( $softwareHash[$key]['description'] ) )
812
            $softwareHash[$key]['description'] = '';
813
         // This is needed for matching
814
         $softwareHash[$key]['keyfield'] = $softwareHash[$key]['name'] . $softwareHash[$key]['version'];
815
      } // foreach
816
      // at this point, we should have a slot and a name field in all pci devices
817
      $toAdd = $this->AddDeleteUpdate( $softwareHash, $queries, 'Software Packages' );
818
      if ( $toAdd ) {
819
         $count = 0;
820
         foreach ( $toAdd as $key => $value ) {
821
            $ids = $this->getSoftwareID ( $value['name'],$value['version'],$value['description'] );
822
            if ( is_null( $ids['package id'] ) or is_null( $ids['version id'] ) ) {
823
               $this->messages[] = "Could not create entry for package " . $value['name'] . ", version " . $value['version'];
824
            } else {
825
               $insertValues = implode( ',', array( $this->machineID, $ids['package id'], $ids['version id'], "'$this->reportDateSQL'" ) );
826
               $query = "insert into installed_packages
827
                           (device_id,software_id,software_version_id,added_date) 
828
                           values 
829
                           ( $insertValues )";
830
               $database = queryDatabaseExtended( $query );
831
               if ( $database )
832
                  $count++;
833
            } // if..else
834
         } // foreach
835
         if ( $count )
836
            $this->messages[] = "$count software packages added/updated";
837
      }
838
   } // processSoftwarePackages
839
 
840
} // class sysinfo
841
 
842
 
843
require "sysinfoRead.php.conf";
844
global $bodyContents;
845
 
846
mysql_connect( $databaseServer, $databaseUsername, $databasePassword ) or die(mysql_error());
847
mysql_select_db( $database ) or die(mysql_error());
848
 
849
 
850
$thisReport = new sysinfo( $bodyContents );
851
$result; 
852
 
853
$result = $thisReport->loadFromFile( $argc > 1 ? $argv[1] : "php://stdin" );
854
if ( $result == 'ini' ) {
855
   print $thisReport->dumpMessages();
856
   exit(0);
857
}
858
if ( ! $result )
859
   exit ( 1 );
860
$result = $thisReport->processReport();
861
print $thisReport->dumpMessages();
862
//var_dump( $thisReport );
863
exit ( $result );
864
 
865
?>