static function updateHostState($data, $opt, $last) { // map amtc string output to db-usable open_port(int) value $rportmap = array('ssh' => 22, 'rdp' => 3389, 'none' => 0, 'skipped' => 0, 'noscan' => 0); // map hostname -> id (amtc has no clue of those IDs...); improve... $hostnameMap = array(); foreach (Host::find_many() as $host) { $hostnameMap[$host->hostname] = $host->id; } // compare current and last, update laststate where needed foreach ($data as $host => $hostnow) { if (!isset($last[$host])) { isset($opt['v']) && printf("NEW %s: initially set [%d|%d|%d] (%s)\n", $host, $hostnow->amt, $hostnow->http, $rportmap[$hostnow->oport], $hostnow->msg); // Insert into statelog/history table $r = Statelog::create(); $r->state_amt = $hostnow->amt; $r->state_http = $hostnow->http; $r->host_id = $hostnameMap[$host]; $r->open_port = $rportmap[$hostnow->oport]; $r->save(); // Insert into current-state/laststate table $x = Laststate::create(); $x->state_amt = $hostnow->amt; $x->state_http = $hostnow->http; $x->host_id = $hostnameMap[$host]; $x->hostname = $host; $x->state_begin = time(); $x->open_port = $rportmap[$hostnow->oport]; $x->save(); // save $hostnow->msg here! } elseif ($hostnow->amt != $last[$host]['state_amt'] || $hostnow->http != $last[$host]['state_http'] || $rportmap[$hostnow->oport] != $last[$host]['open_port']) { isset($opt['v']) && printf("UPD %s: set [%d|%d|%d] (%s), was [%d|%d|%d]\n", $host, $hostnow->amt, $hostnow->http, $rportmap[$hostnow->oport], $hostnow->msg, $last[$host]['state_amt'], $last[$host]['state_http'], $last[$host]['open_port']); // actually the same as for a new record... to keep record. $r = Statelog::create(); $r->state_amt = $hostnow->amt; $r->state_http = $hostnow->http; $r->host_id = $hostnameMap[$host]; $r->open_port = $rportmap[$hostnow->oport]; $r->save(); $x = Model::factory('Laststate')->where('host_id', $hostnameMap[$host])->find_one(); $x->state_amt = $hostnow->amt; $x->state_http = $hostnow->http; $x->host_id = $hostnameMap[$host]; $x->hostname = $host; $x->state_begin = time(); $x->open_port = $rportmap[$hostnow->oport]; $x->save(); // save $hostnow->msg here! } else { // this should happen most of the time: no change. only tell in -debug mode. isset($opt['d']) && printf("0CH %s: still [%d|%d|%d] (%s)\n", $host, $hostnow->amt, $hostnow->http, $rportmap[$hostnow->oport], $hostnow->msg); } } }