Beispiel #1
0
 public function __construct()
 {
     parent::__construct();
     $log_details = new stdClass();
     stdlog($log_details);
     unset($log_details);
 }
Beispiel #2
0
 public function __construct()
 {
     parent::__construct();
     // log the attempt
     $log_details = new stdClass();
     $log_details->severity = 6;
     stdlog($log_details);
     unset($log_details);
 }
Beispiel #3
0
 public function __construct()
 {
     parent::__construct();
     // must be an admin to access this page
     if ($this->user->admin != 'y') {
         if (isset($_SERVER['HTTP_REFERER']) and $_SERVER['HTTP_REFERER'] > "") {
             redirect($_SERVER['HTTP_REFERER']);
         } else {
             redirect('main/list_groups');
         }
     }
     $this->load->helper(array('form', 'url'));
     // log the attempt
     $log_details = new stdClass();
     stdlog($log_details);
     unset($log_details);
 }
Beispiel #4
0
 public function __construct()
 {
     parent::__construct();
     // log the attempt
     stdlog();
     # ensure our URL doesn't have a trailing / as this may break image (and other) relative paths
     $this->load->helper('url');
     if (strrpos($_SERVER['REQUEST_URI'], '/') === strlen($_SERVER['REQUEST_URI']) - 1) {
         redirect(uri_string());
     }
     $this->load->helper('input');
     $this->load->helper('output');
     $this->load->helper('error');
     $this->load->model('m_networks');
     inputRead();
     $this->output->url = $this->config->item('oa_web_index');
 }
Beispiel #5
0
 public function activate_group()
 {
     $log_details = new stdClass();
     if ($handle = opendir(BASEPATH . '../application/controllers/groups')) {
         $i = 0;
         $this->load->model("m_oa_group");
         while (false !== ($file = readdir($handle))) {
             if (mb_strpos($file, ".xml") !== false) {
                 $group_name = '';
                 $file_handle = fopen(BASEPATH . '../application/controllers/groups/' . $file, "rb");
                 $contents = fread($file_handle, filesize(BASEPATH . '../application/controllers/groups/' . $file));
                 try {
                     $xml = @new SimpleXMLElement($contents);
                 } catch (Exception $error) {
                     // $errors = libxml_get_errors();
                     // print_r($errors);
                     $log_details->message = "Invalid XML for group in file " . BASEPATH . '../application/controllers/groups/' . $file;
                     $log_details->file = 'system';
                     stdlog($log_details);
                     continue;
                 }
                 $group_name = $xml->details->group_name;
                 $group_icon = $xml->details->group_icon;
                 $group_description = $xml->details->group_description;
                 unset($xml);
                 fclose($file_handle);
                 $this->data['query'][$i]['file'] = $file;
                 $this->data['query'][$i]['group_name'] = $group_name;
                 $this->data['query'][$i]['group_icon'] = $group_icon;
                 $this->data['query'][$i]['group_description'] = $group_description;
                 $this->data['query'][$i]['activated'] = $this->m_oa_group->get_group_id($group_name);
                 $i++;
                 // echo "$file<br />\n";
             }
         }
         closedir($handle);
     }
     $this->data['heading'] = 'Activate Groups';
     $this->data['include'] = 'v_add_groups';
     $this->data['sortcolumn'] = '1';
     $this->load->view('v_template', $this->data);
 }
Beispiel #6
0
 public function __construct()
 {
     parent::__construct();
     $this->load->library('session');
     $this->load->helper('url');
     $this->load->helper('form');
     $this->load->helper('log');
     $this->load->model('m_oa_config');
     $this->m_oa_config->load_config();
     $this->load->helper('report_helper');
     check_default_reports();
     $this->load->helper('group_helper');
     if ($this->config->config['internal_version'] >= '20160620') {
         check_default_groups();
     }
     // log the attempt
     $log_details = new stdClass();
     $log_details->severity = 6;
     stdlog($log_details);
     unset($log_details);
 }
Beispiel #7
0
 function log_error($error_code, $model = '')
 {
     $CI =& get_instance();
     # ensure we have an array in the $response object to hold our error
     if (!empty($CI->response)) {
         if (!isset($CI->response->errors) or is_null($CI->response->errors)) {
             $CI->response->errors = array();
         }
     }
     # this object will hold this specific error data and be added to the above array at the end
     $error = new stdClass();
     $error->code = $error_code;
     $error->file = 'system';
     $error->model = $model;
     if (function_exists('getError')) {
         $error = getError($error->code);
         $error->message = $error->title;
     }
     // log the details of the error to the log file
     stdlog($error);
     if (!empty($error->controller) and !empty($eror->function)) {
         $error->controller = $error->controller . '::' . $error->function;
     } else {
         $error->controller = '';
     }
     unset($error->function);
     // if the error is severe enough, set the error in the response object
     if (isset($error->severity) and $error->severity <= 3) {
         error_reporting(E_ALL);
         unset($error->file);
         # we don't care about where this was logged (into which file)
         unset($error->message);
         # this is for logging only and is already contained in the $error->title
         $error->link = $CI->config->config['oa_web_folder'] . '/index.php/errors/' . $error->code;
         if (!empty($CI->response)) {
             $CI->response->errors[] = $error;
             $CI->response->meta->header = $error->status;
         }
     }
 }
Beispiel #8
0
 public function __construct()
 {
     parent::__construct();
     // log the attempt
     stdlog();
     # ensure our URL doesn't have a trailing / as this may break image (and other) relative paths
     $this->load->helper('url');
     if (strrpos($_SERVER['REQUEST_URI'], '/') === strlen($_SERVER['REQUEST_URI']) - 1) {
         redirect(uri_string());
     }
     $this->load->helper('network');
     $this->load->helper('output');
     $this->load->helper('error');
     $this->load->helper('input');
     $this->load->model('m_devices');
     $this->load->model('m_orgs');
     inputRead();
     $this->output->url = $this->config->item('oa_web_index');
     if ($this->response->meta->id != '') {
         $access_level = $this->m_devices->get_user_device_org_access();
         if ($access_level < 1) {
             // we should determine if the device does actually exist or not
             // then we can throw the correct status code of 404 or 403
             $sql = "SELECT system.id FROM system WHERE system.id = ?";
             $data = array($this->response->meta->id);
             $query = $this->db->query($sql, $data);
             $result = $query->result();
             if (count($result) == 0) {
                 $this->response->errors[] = getError('ERR-0007');
             } else {
                 $this->response->errors[] = getError('ERR-0008');
             }
             $this->response->meta->header = $this->response->errors[0]->status;
             output($this->response);
             exit;
         }
     }
 }
Beispiel #9
0
 function snmp_audit($ip, $credentials, $display)
 {
     error_reporting(E_ALL);
     $CI =& get_instance();
     $log = new stdClass();
     $log->file = 'system';
     $log->severity = 7;
     if ($display == 'y') {
         $log->display = 'y';
     } else {
         $log->display = 'n';
     }
     if (!extension_loaded('snmp')) {
         $log->message = 'SNMP PHP function not loaded hence not attempting to run snmp_helper::snmp_audit function';
         $log->severity = 5;
         stdlog($log);
         unset($log);
         return false;
     } else {
         $log->message = 'SNMP PHP function loaded and attempting to run snmp_helper::snmp_audit function';
         stdlog($log);
     }
     # we need an ip address
     if (empty($ip)) {
         $log->message = 'SNMP command received no ip address';
         $log->severity = 5;
         stdlog($log);
         unset($log);
         return false;
     } elseif (!filter_var($ip, FILTER_VALIDATE_IP)) {
         $log->message = 'SNMP command received invalid ip address';
         $log->severity = 5;
         stdlog($log);
         unset($log);
         return false;
     } else {
         $log->message = 'snmp_helper::snmp_audit function received ip ' . $ip;
         stdlog($log);
     }
     if (empty($credentials) or !is_object($credentials)) {
         $log->message = 'SNMP snmp_helper::snmp_audit received no credentials for ' . $ip;
         $log->severity = 5;
         stdlog($log);
         unset($log);
         return false;
     } else {
         $log->message = 'snmp_helper::snmp_audit function received credentials for ip ' . $ip;
         stdlog($log);
     }
     # new in 1.5 - remove the type from the returned SNMP query.
     # this affects the snmp_clean function in this file
     snmp_set_valueretrieval(SNMP_VALUE_PLAIN);
     snmp_set_oid_output_format(SNMP_OID_OUTPUT_NUMERIC);
     $details = new stdClass();
     $module = new stdclass();
     $return_ips = new stdClass();
     $return_ips->item = array();
     $details->ip = (string) $ip;
     $details->manufacturer = '';
     $details->serial = '';
     $details->model = '';
     $details->type = '';
     $details->sysDescr = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.1.1.0");
     $details->description = $details->sysDescr;
     $details->sysContact = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.1.4.0");
     $details->contact = $details->sysContact;
     $details->sysName = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.1.5.0");
     $details->hostname = $details->sysName;
     $details->name = $details->sysName;
     $details->sysLocation = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.1.6.0");
     $details->location = $details->sysLocation;
     // uptime
     $details->sysUpTime = intval(my_snmp_get($ip, $credentials, "1.3.6.1.6.3.10.2.1.3.0")) * 100;
     if (empty($details->sysUpTime)) {
         $details->sysUpTime = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.1.3.0");
     }
     if (empty($details->sysUpTime)) {
         $i = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.1.3.0");
         if ($i > '' and strpos($i, ")") !== false) {
             $j = explode(")", $i);
             $details->uptime = intval(trim($j[1]) * 24 * 60 * 60);
         } else {
             $details->uptime = '';
         }
     }
     // OID
     $details->sysObjectID = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.1.2.0");
     $details->snmp_oid = $details->sysObjectID;
     if ($details->snmp_oid > '') {
         $details->manufacturer = get_oid($details->snmp_oid);
         if ($details->manufacturer == 'net-snmp') {
             $details->manufacturer = (string) '';
         }
     }
     # sometimes we get an OID, but not enough to specify a manufacturer
     $explode = explode(".", $details->snmp_oid);
     if (!isset($explode[6])) {
         $vendor_oid = 0;
         if (strpos($details->sysDescr, "ZyXEL") !== false) {
             # we have a Zyxel device
             $vendor_oid = 890;
         }
     } else {
         $vendor_oid = intval($explode[6]);
     }
     if (file_exists(BASEPATH . '../application/helpers/snmp_' . $vendor_oid . '_helper.php')) {
         $log->message = 'snmp_helper::snmp_audit is loading the snmp helper for ' . $vendor_oid . ' when scanning ' . $ip;
         stdlog($log);
         unset($get_oid_details);
         include 'snmp_' . $vendor_oid . "_helper.php";
         $new_details = $get_oid_details($ip, $credentials, $details->snmp_oid);
         foreach ($new_details as $key => $value) {
             $details->{$key} = $value;
         }
         unset($new_details);
     } else {
         $log->message = 'snmp_helper::snmp_audit could not load the snmp helper for ' . $vendor_oid . ' when scanning ' . $ip;
         $log->severity = 6;
         stdlog($log);
         $log->severity = 7;
     }
     if (!empty($details->sysDescr) and stripos($details->sysDescr, 'dd-wrt') !== false) {
         $details->os_group = 'Linux';
         $details->os_name = 'DD-WRT';
         $details->type = 'router';
     }
     if (!empty($details->sysDescr) and stripos($details->sysDescr, "Darwin Kernel Version 12") !== false) {
         $details->manufacturer = "Apple Inc";
         $details->os_family = 'Apple OSX';
     }
     if (!empty($details->manufacturer) and (stripos($details->manufacturer, 'tplink') !== false or stripos($details->manufacturer, 'tp-link') !== false)) {
         $details->manufacturer = 'TP-Link Technology Co.,Ltd';
     }
     if (!empty($details->sysDescr) and stripos($details->sysDescr, 'buffalo terastation') !== false) {
         $details->manufacturer = 'Buffalo';
         $details->model = 'TeraStation';
         $details->type = 'nas';
     }
     if (!empty($details->sysDescr) and (stripos($details->sysDescr, 'synology') !== false or stripos($details->sysDescr, 'diskstation') !== false)) {
         $details->manufacturer = 'Synology';
         $temp = my_snmp_get($ip, $credentials, "1.3.6.1.4.1.6574.1.5.1.0");
         $details->model = trim('DiskStation ' . $temp);
         $details->serial = my_snmp_get($ip, $credentials, "1.3.6.1.4.1.6574.1.5.2.0");
         $details->type = 'nas';
         $details->os_group = 'Linux';
         $details->os_family = 'Synology DSM';
         $details->os_name = 'Synology ' . my_snmp_get($ip, $credentials, "1.3.6.1.4.1.6574.1.5.3.0");
     }
     // guess at manufacturer using entity mib
     if (empty($details->manufacturer)) {
         $details->manufacturer = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.47.1.1.1.1.12.1");
     }
     // guess at model using entity mib
     if (empty($details->model)) {
         $details->model = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.47.1.1.1.1.13");
     }
     // guess at model using host resources mib
     if (empty($details->model)) {
         $details->model = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.25.3.2.1.3.1");
     }
     // serial
     if (empty($details->serial)) {
         $details->serial = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.47.1.1.1.1.11");
     }
     if (empty($details->serial)) {
         $details->serial = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.47.1.1.1.1.11.1");
     }
     if (empty($details->serial)) {
         $details->serial = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.47.1.1.1.1.11.1.0");
     }
     # generic snmp
     if (empty($details->serial)) {
         $details->serial = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.43.5.1.1.17.1");
     }
     # below is another generic attempt - works for my NetGear Cable Modem
     if (empty($details->serial)) {
         $details->serial = my_snmp_get($ip, $credentials, "1.3.6.1.4.1.4491.2.4.1.1.1.3.0");
     }
     $log->message = 'snmp_helper::snmp_audit thinks ' . $ip . ' is a type:' . $details->type . ' model:' . $details->model . ' serial:' . $details->serial;
     stdlog($log);
     // subnet
     if (empty($details->subnet)) {
         $details->subnet = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.4.20.1.3." . $details->ip);
     }
     // mac address
     if (empty($details->mac_address)) {
         $interface_number = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.4.20.1.2." . $ip);
         snmp_set_valueretrieval(SNMP_VALUE_LIBRARY);
         $details->mac_address = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.2.2.1.6." . $interface_number);
         snmp_set_valueretrieval(SNMP_VALUE_PLAIN);
         $details->mac_address = format_mac($details->mac_address);
     }
     // last attempt at a MAC - just use whatever's in the first interface MAC
     if (empty($details->mac_address)) {
         snmp_set_valueretrieval(SNMP_VALUE_LIBRARY);
         $details->mac_address = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.2.2.1.6.1");
         snmp_set_valueretrieval(SNMP_VALUE_PLAIN);
         $details->mac_address = format_mac($details->mac_address);
     }
     $log->message = 'snmp_helper::snmp_audit MAC Address for ' . $ip . ' is ' . $details->mac_address;
     stdlog($log);
     // type
     if (empty($details->type) or $details->type == 'network printer') {
         $h = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.25.3.2.1.2.1");
         if ($h == '1.3.6.1.2.1.25.3.1.5') {
             # we have a printer
             $details->type = 'network printer';
             $i = my_snmp_walk($ip, $credentials, "1.3.6.1.2.1.43.13.4.1.10.1");
             if (count($i) > 0) {
                 $details->printer_duplex = 'n';
                 for ($k = 0; $k < count($i); $k++) {
                     if (mb_strpos($i[$k], "Duplex") !== false) {
                         $details->printer_duplex = 'y';
                     }
                 }
             }
             if (empty($details->manufacturer)) {
                 $hex = my_snmp_walk($ip, $credentials, "1.3.6.1.2.1.43.8.2.1.14.1");
                 if (count($hex) > 0) {
                     if (isset($hex[1])) {
                         if (mb_strpos($hex[1], "Hex-STRING: ") !== false) {
                             $hex[1] = str_replace("Hex-STRING: ", "", $hex[1]);
                             for ($i = 0; $i < strlen($hex[1]); $i++) {
                                 $details->manufacturer .= chr(hexdec(substr($hex[1], $i, 2)));
                             }
                         } else {
                             $details->manufacturer = str_replace("STRING: ", "", $hex[1]);
                             $details->manufacturer = str_replace('"', '', $details->manufacturer);
                         }
                     }
                 }
             }
             $details->printer_color = 'n';
             $i = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.43.11.1.1.6.1.2");
             if (strpos(strtolower($i), "cartridge") !== false) {
                 # it's likely this is a colour printer
                 $details->printer_color = 'y';
             }
         } else {
             # If the device is a Switch, the OID 1.3.6.1.2.1.17.1.2.0 is an integer and
             #                                OID 1.3.6.1.2.1.4.1.0    should have a value of 2
             $i = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.17.1.2.0");
             $j = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.4.1.0");
             if ($i == intval($i) and $j == '2') {
                 $details->type = 'switch';
             }
             # If the device is a Router, the OID 1.3.6.1.2.1.4.1.0 should have a value of 1 (already read above)
             if (empty($details->type)) {
                 if ($i == '1') {
                     $details->type = 'router';
                 }
             }
             # If the device is a Printer, the OID 1.3.6.1.2.1.43.5.1.1.1.1 should have a value
             #if (!isset($details->type) or $details->type == '') {
             $i = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.43.5.1.1.1.1");
             if (strpos(strtolower($i), "counter32") !== false) {
                 $details->type = 'network printer';
                 // printer duplex
                 $details->printer_duplex = '';
                 $i = my_snmp_walk($ip, $credentials, "1.3.6.1.2.1.43.13.4.1.10.1");
                 if (count($i) > 0) {
                     $details->printer_duplex = 'n';
                     for ($k = 0; $k < count($i); $k++) {
                         if (mb_strpos($i[$k], "Duplex") !== false) {
                             $details->printer_duplex = 'y';
                         }
                     }
                 }
                 if (empty($details->manufacturer)) {
                     $hex = my_snmp_walk($ip, $credentials, "1.3.6.1.2.1.43.8.2.1.14.1");
                     if (count($hex) > 0) {
                         if (isset($hex[1])) {
                             if (mb_strpos($hex[1], "Hex-STRING: ") !== false) {
                                 $hex[1] = str_replace("Hex-STRING: ", "", $hex[1]);
                                 for ($i = 0; $i < strlen($hex[1]); $i++) {
                                     $details->manufacturer .= chr(hexdec(substr($hex[1], $i, 2)));
                                 }
                             } else {
                                 $details->manufacturer = str_replace("STRING: ", "", $hex[1]);
                                 $details->manufacturer = str_replace('"', '', $details->manufacturer);
                             }
                         }
                     }
                 }
                 $details->printer_color = 'n';
                 $i = my_snmp_get($ip, $credentials, "1.3.6.1.2.1.43.11.1.1.6.1.2");
                 if (strpos(strtolower($i), "cartridge") !== false) {
                     # it's likely this is a colour printer
                     $details->printer_color = 'y';
                 }
             }
         }
     }
     // modules - NOTE, we call these 'entities' in the web interface
     $log->message = 'snmp_helper::snmp_audit module retrieval for ' . $ip . ' starting';
     stdlog($log);
     $modules = array();
     $modules_list = my_snmp_real_walk($ip, $credentials, "1.3.6.1.2.1.47.1.1.1.1.2");
     if (isset($modules_list) and is_array($modules_list) and count($modules_list) > 0) {
         $log->message = 'snmp_helper::snmp_audit module count for ' . $ip . ' is ' . count($modules_list);
         stdlog($log);
         $log->message = 'snmp_helper::snmp_audit object_id retrieval for ' . $ip . ' starting';
         stdlog($log);
         $temp_object_id = my_snmp_real_walk($ip, $credentials, '1.3.6.1.2.1.47.1.1.1.1.3');
         $log->message = 'snmp_helper::snmp_audit contained_in retrieval for ' . $ip . ' starting';
         stdlog($log);
         $temp_contained_in = my_snmp_real_walk($ip, $credentials, '1.3.6.1.2.1.47.1.1.1.1.4');
         $log->message = 'snmp_helper::snmp_audit class retrieval for ' . $ip . ' starting';
         stdlog($log);
         $temp_class = my_snmp_real_walk($ip, $credentials, '1.3.6.1.2.1.47.1.1.1.1.5');
         $log->message = 'snmp_helper::snmp_audit hardware_revision retrieval for ' . $ip . ' starting';
         stdlog($log);
         $temp_hardware_revision = my_snmp_real_walk($ip, $credentials, '1.3.6.1.2.1.47.1.1.1.1.8');
         $log->message = 'snmp_helper::snmp_audit firmware_revision retrieval for ' . $ip . ' starting';
         stdlog($log);
         $temp_firmware_revision = my_snmp_real_walk($ip, $credentials, '1.3.6.1.2.1.47.1.1.1.1.9');
         $log->message = 'snmp_helper::snmp_audit software_revision retrieval for ' . $ip . ' starting';
         stdlog($log);
         $temp_software_revision = my_snmp_real_walk($ip, $credentials, '1.3.6.1.2.1.47.1.1.1.1.10');
         $log->message = 'snmp_helper::snmp_audit serial_number retrieval for ' . $ip . ' starting';
         stdlog($log);
         $temp_serial_number = my_snmp_real_walk($ip, $credentials, '1.3.6.1.2.1.47.1.1.1.1.11');
         $log->message = 'snmp_helper::snmp_audit asset_id retrieval for ' . $ip . ' starting';
         stdlog($log);
         $temp_asset_id = my_snmp_real_walk($ip, $credentials, '1.3.6.1.2.1.47.1.1.1.1.15');
         $log->message = 'snmp_helper::snmp_audit is_fru retrieval for ' . $ip . ' starting';
         stdlog($log);
         $temp_is_fru = my_snmp_real_walk($ip, $credentials, '1.3.6.1.2.1.47.1.1.1.1.16');
         foreach ($modules_list as $key => $value) {
             $log->message = 'snmp_helper::snmp_audit processing module ' . $value . ' for ' . $ip . ' starting';
             stdlog($log);
             $module = new stdClass();
             $module->description = $value;
             $module->module_index = str_replace('.1.3.6.1.2.1.47.1.1.1.1.2.', '', $key);
             $module->object_ident = $temp_object_id['.1.3.6.1.2.1.47.1.1.1.1.3.' . $module->module_index];
             $module->contained_in = $temp_contained_in['.1.3.6.1.2.1.47.1.1.1.1.4.' . $module->module_index];
             $module->class = $temp_class['.1.3.6.1.2.1.47.1.1.1.1.5.' . $module->module_index];
             $module->hardware_revision = $temp_hardware_revision['.1.3.6.1.2.1.47.1.1.1.1.8.' . $module->module_index];
             $module->firmware_revision = $temp_firmware_revision['.1.3.6.1.2.1.47.1.1.1.1.9.' . $module->module_index];
             $module->software_revision = $temp_software_revision['.1.3.6.1.2.1.47.1.1.1.1.10.' . $module->module_index];
             $module->serial = $temp_serial_number['.1.3.6.1.2.1.47.1.1.1.1.11.' . $module->module_index];
             $module->asset_ident = $temp_asset_id['.1.3.6.1.2.1.47.1.1.1.1.15.' . $module->module_index];
             $module->is_fru = $temp_is_fru['.1.3.6.1.2.1.47.1.1.1.1.16.' . $module->module_index];
             if ((string) $module->is_fru == '1') {
                 $module->is_fru = 'y';
             } else {
                 $module->is_fru = 'n';
             }
             $module->class_text = 'unknown';
             if ($module->class == '1') {
                 $module->class_text = 'other';
             }
             if ($module->class == '2') {
                 $module->class_text = 'unknown';
             }
             if ($module->class == '3') {
                 $module->class_text = 'chassis';
             }
             if ($module->class == '4') {
                 $module->class_text = 'backplane';
             }
             if ($module->class == '5') {
                 $module->class_text = 'container';
             }
             if ($module->class == '6') {
                 $module->class_text = 'powerSupply';
             }
             if ($module->class == '7') {
                 $module->class_text = 'fan';
             }
             if ($module->class == '8') {
                 $module->class_text = 'sensor';
             }
             if ($module->class == '9') {
                 $module->class_text = 'module';
             }
             if ($module->class == '10') {
                 $module->class_text = 'port';
             }
             if ($module->class == '11') {
                 $module->class_text = 'stack';
             }
             if ($module->class == '12') {
                 $module->class_text = 'cpu';
             }
             $modules[] = $module;
         }
     }
     $log->message = 'snmp_helper::snmp_audit module retrieval for ' . $ip . ' complete';
     stdlog($log);
     // network intereface details
     $interfaces = array();
     $interfaces_filtered = array();
     $interfaces = my_snmp_walk($ip, $credentials, "1.3.6.1.2.1.2.2.1.1");
     $log->message = 'snmp_helper::snmp_audit interface count for ' . $ip . ' is ' . count($interfaces);
     stdlog($log);
     if (is_array($interfaces) and count($interfaces) > 0) {
         $log->message = 'snmp_helper::snmp_audit models retrieval for ' . $ip . ' starting';
         stdlog($log);
         $models = my_snmp_real_walk($ip, $credentials, "1.3.6.1.2.1.2.2.1.2");
         $log->message = 'snmp_helper::snmp_audit types retrieval for ' . $ip . ' starting';
         stdlog($log);
         $types = my_snmp_real_walk($ip, $credentials, "1.3.6.1.2.1.2.2.1.3");
         $log->message = 'snmp_helper::snmp_audit speeds retrieval for ' . $ip . ' starting';
         stdlog($log);
         $speeds = my_snmp_real_walk($ip, $credentials, "1.3.6.1.2.1.2.2.1.5");
         $log->message = 'snmp_helper::snmp_audit mac_addresses retrieval for ' . $ip . ' starting';
         stdlog($log);
         $mac_addresses = my_snmp_real_walk($ip, $credentials, "1.3.6.1.2.1.2.2.1.6");
         $log->message = 'snmp_helper::snmp_audit ip_enableds retrieval for ' . $ip . ' starting';
         stdlog($log);
         $ip_enableds = my_snmp_real_walk($ip, $credentials, "1.3.6.1.2.1.2.2.1.8");
         $log->message = 'snmp_helper::snmp_audit ip_addresses retrieval for ' . $ip . ' starting';
         stdlog($log);
         $ip_addresses = my_snmp_real_walk($ip, $credentials, "1.3.6.1.2.1.4.20.1.2");
         $log->message = 'snmp_helper::snmp_audit ifAdminStatus retrieval for ' . $ip . ' starting';
         stdlog($log);
         $ifAdminStatus = my_snmp_real_walk($ip, $credentials, "1.3.6.1.2.1.2.2.1.7");
         $log->message = 'snmp_helper::snmp_audit ifLastChange retrieval for ' . $ip . ' starting';
         stdlog($log);
         $ifLastChange = my_snmp_real_walk($ip, $credentials, "1.3.6.1.2.1.2.2.1.9");
         if (isset($details->os_group) and $details->os_group == "VMware") {
             $log->message = 'snmp_helper::snmp_audit ip_addresses_2 retrieval for ' . $ip . ' starting';
             stdlog($log);
             $ip_addresses_2 = my_snmp_real_walk($ip, $credentials, "1.3.6.1.2.1.4.34.1.3.1.4");
         }
         $log->message = 'snmp_helper::snmp_audit subnets retrieval for ' . $ip . ' starting';
         stdlog($log);
         $subnets = my_snmp_real_walk($ip, $credentials, "1.3.6.1.2.1.4.20.1.3");
         $log->message = 'snmp_helper::snmp_audit connection_ids retrieval for ' . $ip . ' starting';
         stdlog($log);
         $connection_ids = my_snmp_real_walk($ip, $credentials, "1.3.6.1.2.1.31.1.1.1.1");
         $log->message = 'snmp_helper::snmp_audit aliases retrieval for ' . $ip . ' starting';
         stdlog($log);
         $aliases = my_snmp_real_walk($ip, $credentials, "1.3.6.1.2.1.31.1.1.1.18");
         foreach ($interfaces as $key => $value) {
             $log->message = 'snmp_helper::snmp_audit processing interface ' . $value . ' for ' . $ip . ' starting';
             stdlog($log);
             $interface = new stdclass();
             $interface->net_index = $value;
             snmp_set_valueretrieval(SNMP_VALUE_LIBRARY);
             $interface->mac = format_mac(my_snmp_get($ip, $credentials, "1.3.6.1.2.1.2.2.1.6." . $interface->net_index));
             snmp_set_valueretrieval(SNMP_VALUE_PLAIN);
             if (!isset($interface->mac)) {
                 $interface->mac = (string) '';
             }
             $interface->model = @$models[".1.3.6.1.2.1.2.2.1.2." . $interface->net_index];
             $interface->description = $interface->model;
             $interface->connection = @$connection_ids[".1.3.6.1.2.1.31.1.1.1.1." . $interface->net_index];
             $interface->alias = @$aliases[".1.3.6.1.2.1.31.1.1.1.18." . $interface->net_index];
             $interface->type = @interface_type(@$types[".1.3.6.1.2.1.2.2.1.3." . $interface->net_index]);
             $interface->ip_enabled = @ip_enabled($ip_enableds[".1.3.6.1.2.1.2.2.1.8." . $interface->net_index]);
             $interface->ifadminstatus = @if_admin_status($ifAdminStatus[".1.3.6.1.2.1.2.2.1.7." . $interface->net_index]);
             $interface->iflastchange = @$ifLastChange[".1.3.6.1.2.1.2.2.1.9." . $interface->net_index];
             $interface->speed = @$speeds[".1.3.6.1.2.1.2.2.1.5." . $interface->net_index];
             $interface->manufacturer = '';
             $interface->connection_status = '';
             $interface->dhcp_enabled = '';
             $interface->dhcp_server = '';
             $interface->dhcp_lease_obtained = '';
             $interface->dhcp_lease_expires = '';
             $interface->dns_host_name = '';
             $interface->dns_domain = '';
             $interface->dns_domain_reg_enabled = '';
             $interface->dns_server = '';
             if (is_array($ip_addresses) and count($ip_addresses > 0)) {
                 foreach ($ip_addresses as $each_key => $each_value) {
                     if ($each_value == $interface->net_index) {
                         $new_ip = new stdclass();
                         $new_ip->net_index = $interface->net_index;
                         $new_ip->ip = str_replace(".1.3.6.1.2.1.4.20.1.2.", "", $each_key);
                         $new_ip->mac = $interface->mac;
                         $new_ip->netmask = @$subnets[".1.3.6.1.2.1.4.20.1.3." . $new_ip->ip];
                         $new_ip->version = '4';
                         if ($new_ip->ip != '127.0.0.1' and $new_ip->ip != '127.0.1.1') {
                             $return_ips->item[] = $new_ip;
                         }
                         $new_ip = null;
                     }
                 }
             }
             if (isset($ip_addresses_2) and is_array($ip_addresses_2) and isset($details->os_group) and $details->os_group == "VMware") {
                 // likely we have a VMware ESX box - get what we can
                 foreach ($ip_addresses_2 as $each_key => $each_value) {
                     $new_ip = new stdClass();
                     $new_ip->net_index = $each_value;
                     $new_ip->ip = str_replace(".1.3.6.1.2.1.4.34.1.3.1.4.", "", $each_key);
                     $new_ip->netmask = '';
                     $new_ip->version = '4';
                     if ($new_ip->net_index == $interface->net_index) {
                         $new_ip->mac = $interface->mac;
                         if ($new_ip->ip != '127.0.0.1' and $new_ip->ip != '127.0.1.1') {
                             $return_ips->item[] = $new_ip;
                         }
                     }
                     $new_ip = null;
                 }
             }
             if (isset($details->os_group) and $details->os_group == 'Windows') {
                 if (isset($interface->ip_addresses) and count($interface->ip_addresses) > 0) {
                     if (strpos(strtolower($interface->type), 'loopback') === false) {
                         $interfaces_filtered[] = $interface;
                     }
                 }
             } else {
                 if (strtolower($interface->type != 'software loopback')) {
                     $interfaces_filtered[] = $interface;
                 }
             }
         }
     }
     // end of network interfaces
     // Virtual Guests
     $guests = array();
     if ($vendor_oid == 6876) {
         if (file_exists(BASEPATH . '../application/helpers/snmp_6876_2_helper.php')) {
             $log->message = 'snmp_helper::snmp_audit is loading the model helper for VMware virtual guests';
             stdlog($log);
             include 'snmp_6876_2_helper.php';
         }
     }
     $return_array = array('details' => $details, 'interfaces' => $interfaces_filtered, 'guests' => $guests, 'modules' => $modules, 'ip' => $return_ips);
     return $return_array;
 }
Beispiel #10
0
 public function edit_user()
 {
     $this->load->model("m_oa_user");
     $this->load->model("m_oa_group");
     $this->load->helper('url');
     $this->data['url'] = current_url();
     if (!isset($_POST['submit'])) {
         # load the initial form
         $this->data['user'] = $this->m_oa_user->get_user_details($this->data['id']);
         $this->data['user_group'] = $this->m_oa_group->get_all_user_groups($this->data['id']);
         $this->data['heading'] = 'Edit User';
         $this->data['include'] = 'v_edit_user';
         $this->data['sortcolumn'] = '1';
         $this->load->view('v_template', $this->data);
     } else {
         # process the form
         $error = '0';
         $details = new stdClass();
         foreach ($_POST as $key => $value) {
             $details->{$key} = $value;
         }
         if ($details->user_password != $details->user_password_confirm) {
             $error = '1';
             $this->data['error_message'] = "Passwords must match.";
             $this->data['user'] = $this->m_oa_user->get_user_details($details->user_id);
             $this->data['user_group'] = $this->m_oa_group->get_all_user_groups($details->user_id);
             $this->data['heading'] = 'Edit User';
             $this->data['include'] = 'v_edit_user';
             $this->load->view('v_template', $this->data);
         }
         if ($this->m_oa_user->check_user_name($details->user_name, $details->user_id) == false) {
             $error = '1';
             $this->data['error_message'] = "Username already exists.";
             $this->data['user'] = $this->m_oa_user->get_user_details($details->user_id);
             $this->data['user_group'] = $this->m_oa_group->get_all_user_groups($details->user_id);
             $this->data['heading'] = 'Edit User';
             $this->data['include'] = 'v_edit_user';
             $this->load->view('v_template', $this->data);
         }
         if ($error == '0') {
             $this->m_oa_user->edit_user($details);
             $this->m_oa_group->edit_user_groups($details);
             // Reset the admin user password in OAE
             if ($details->user_name == 'admin') {
                 $server_os = php_uname('s');
                 if ($server_os == 'Windows NT') {
                     if (file_exists('c:\\xampplite\\apache\\bin\\htpasswd.exe')) {
                         $command_string = 'c:\\xampplite\\apache\\bin\\htpasswd.exe -mb c:\\omk\\conf\\users.dat admin ' . $details->user_password . ' 2>&1';
                     }
                 }
                 if (php_uname('s') == 'Linux' or php_uname('s') == "Darwin") {
                     if (file_exists('/usr/local/opmojo/conf/users.dat')) {
                         $command_string = 'htpasswd -mb /usr/local/opmojo/conf/users.dat admin ' . $details->user_password . ' 2>&1';
                     }
                     if (file_exists('/usr/local/omk/conf/users.dat')) {
                         $command_string = 'htpasswd -mb /usr/local/omk/conf/users.dat admin ' . $details->user_password . ' 2>&1';
                     }
                 }
                 exec($command_string, $output, $return_var);
                 if ($return_var != '0') {
                     $log_details = new stdClass();
                     $log_details->log_file = 'system';
                     $log_details->message = 'Admin user password reset attempt for Open-AudIT and Open-AudIT Enterprise has failed';
                     stdlog($log_details);
                     unset($log_details);
                 } else {
                     $log_details = new stdClass();
                     $log_details->log_file = 'system';
                     $log_details->message = 'Admin user password reset attempt for Open-AudIT and Open-AudIT Enterprise has succeeded';
                     stdlog($log_details);
                     unset($log_details);
                 }
                 $command_string = null;
                 $output = null;
                 $return_var = null;
             }
             redirect('admin_user/list_users');
         }
     }
 }
Beispiel #11
0
    /**
    * Insert a new device into the system table using whatever values we have and insert corresponding rows into the sys_edit_log table
    *
    * @param array $details the array of attributes from the system table
    * @access  public
    *
    * @return string $id which is the id of the device in the system table
    */
    public function create(&$details)
    {
        # nasty hack because when a simplexmlobject is sent (ie, from audit_windows.vbs)
        # the foreach iterators below don't work.
        # if we cast it to an "object", it stays as a SimpleXMLObject and doesn't work
        # because our XML is quite simple, we can cast it to an array and back to a 'normal'
        # object and the foreach below works.
        $details = (object) $details;
        $details = (array) $details;
        $details = (object) $details;
        # this is an insert - we do NOT want a system.id
        unset($details->id);

        // get a name we can use
        if (!empty($details->name)) {
            $name = $details->name;
        } elseif (!empty($details->hostname)) {
            $name = $details->hostname;
            $details->name = $details->hostname;
        } elseif (!empty($details->sysName)) {
            $name = $details->sysName;
            $details->name = $details->sysName;
        } elseif (!empty($details->dns_hostname)) {
            $name = $details->dns_hostname;
            $details->name = $details->dns_hostname;
        }

        if (!isset($details->ip)) {
            $details->ip = '';
        }

        $log_details = new stdClass();
        $log_details->message = 'System insert start for '.ip_address_from_db($details->ip).' ('.$name.')';
        $log_details->severity = 7;
        $log_details->file = 'system';
        stdlog($log_details);

        # remove some characters from the OS string
        if ( ! empty($details->os_name)) {
            $details->os_name = str_ireplace("(r)", "", $details->os_name);
            $details->os_name = str_ireplace("(tm)", "", $details->os_name);
        }


        if (empty($details->status)) {
            $details->status = 'production';
        }
        if (empty($details->type)) {
            $details->type = 'unknown';
        } else {
            $details->type = strtolower($details->type);
        }
        if (empty($details->environment)) {
            $details->environment = 'production';
        }

        # we now set a default location - 0 the location_id
        if (!isset($details->location_id)) {
            $details->location_id = '0';
        }

        # Set the form factor to virtual if required
        if ( ! empty($details->manufacturer)) {
            if ((strripos($details->manufacturer, "vmware") !== false) or
                (strripos($details->manufacturer, "parallels") !== false) or
                (strripos($details->manufacturer, "virtual") !== false)) {
                if (!isset($details->class) or $details->class != 'hypervisor') {
                    $details->form_factor = 'Virtual';
                }
            }
        }
        if ( ! empty($details->model)) {
            if (strripos($details->model, "bhyve") !== false) {
                if (!isset($details->class) or $details->class != 'hypervisor') {
                    $details->form_factor = 'Virtual';
                }
            }
        }

        # Pad the IP address
        if ( ! empty($details->ip)) {
            $details->ip = ip_address_to_db($details->ip);
        }

        if ( ! empty($details->hostname) and  ! empty($details->domain) and empty($details->fqdn)) {
            $details->fqdn = $details->hostname.".".$details->domain;
        }

        $sql = "SHOW COLUMNS FROM system";
        $query = $this->db->query($sql);
        $columns = $query->result();

        $sql = "INSERT INTO system ( ";
        foreach ($details as $key => $value) {
            if ($key > '') {
                # need to iterate through available columns and only insert where $key == valid column name
                foreach ($columns as $column) {
                    if ($key == $column->Field) {
                        $sql .= $key.", ";
                    }
                }
            }
        }
        $sql = mb_substr($sql, 0, mb_strlen($sql)-2);
        $sql .= " ) VALUES ( ";
        foreach ($details as $key => $value) {
            if ($key > '') {
                foreach ($columns as $column) {
                    if ($key == $column->Field) {
                        $sql .= "'".mysqli_real_escape_string($this->db->conn_id, str_replace('"', '', $value))."', ";
                    }
                }
            }
        }
        $sql = mb_substr($sql, 0, mb_strlen($sql)-2);
        $sql .= ")";

        $query = $this->db->query($sql);
        $details->id = $this->db->insert_id();

        // set the weight for these $details
        $weight = $this->weight($details->last_seen_by);

        // insert entries into the edit_log table for these $details columns
        foreach ($details as $key => $value) {
            if ($key > '') {
                foreach ($columns as $column) {
                    if ($key == $column->Field) {
                        $sql = "INSERT INTO edit_log VALUES (NULL, 0, ?, '', ?, ?, 'system', ?, ?, ?, ?)";
                        $data = array("$details->id", "$details->last_seen_by", "$weight", "$key", "$details->last_seen", "$value", "");
                        $query = $this->db->query($sql, $data);
                    }
                }
            }
        }

        # update the device icon
        $this->reset_icons($details->id);

        # insert a subnet so we have a default
        if (!isset($details->subnet) or $details->subnet == '') {
            $details->subnet = '0.0.0.0';
        }

        $log_details->message = 'System insert end for '.ip_address_from_db($details->ip).' ('.$name.') (System ID '.$details->id.')';
        stdlog($log_details);
        unset($log_details);
        return $details->id;
    }
Beispiel #12
0
    function wmi_audit($ip = '', $credentials, $display = 'n')
    {
        if (strtolower($display) != 'y') {
            $display = 'n';
        } else {
            $display = 'y';
        }

        $log = new stdClass();
        $log->severity = 7;
        $log->file = 'system';
        $log->display = $display;

        if (empty($ip)) {
            $log->message = 'No IP supplied to wmi_helper::wmi_audiy.';
            stdlog($log);
            return false;
        }

        if (!filter_var($ip, FILTER_VALIDATE_IP)) {
            $log->message = 'No valid IP supplied to wmi_helper::wmi_audit.';
            stdlog($log);
            return false;
        }
        if (!is_object($credentials)) {
            $log->message = 'No credentials supplied to wmi_helper::wmi_audit.';
            stdlog($log);
            return false;
        }

        $details = new stdClass();

        # UUID
        $command = 'csproduct get uuid';
        $wmi_result = wmi_command($ip, $credentials, $command, $display);
        if ($wmi_result['status'] == 0) {
            $details->uuid = $wmi_result['output'][1];
        }

        # Serial
        $command = 'csproduct get IdentifyingNumber';
        $wmi_result = wmi_command($ip, $credentials, $command, $display);
        if ($wmi_result['status'] == 0) {
            $details->serial = $wmi_result['output'][1];
        }

        # Manufacturer
        $command = 'csproduct get vendor';
        $wmi_result = wmi_command($ip, $credentials, $command, $display);
        if ($wmi_result['status'] == 0) {
            $details->manufacturer = $wmi_result['output'][1];
        }

        # Description
        $command = 'os get description';
        $wmi_result = wmi_command($ip, $credentials, $command, $display);
        if ($wmi_result['status'] == 0) {
            $details->description = $wmi_result['output'][1];
        }

        # Hostname / name
        $command = 'computersystem get name';
        $wmi_result = wmi_command($ip, $credentials, $command, $display);
        if ($wmi_result['status'] == 0) {
            $details->hostname = strtolower($wmi_result['output'][1]);
            $details->name = $details->hostname;
        }

        # Domain / fqdn
        $command = 'computersystem get domain';
        $wmi_result = wmi_command($ip, $credentials, $command, $display);
        if ($wmi_result['status'] == 0) {
            $details->domain = strtolower($wmi_result['output'][1]);
            $details->fqdn = $details->hostname . '.' . $details->domain;
        }

        # OS Name
        $command = 'os get name';
        $wmi_result = wmi_command($ip, $credentials, $command, $display);
        if ($wmi_result['status'] == 0) {
            $details->os_name = $wmi_result['output'][1];
            $details->os_name = trim(substr($details->os_name, 0, stripos($details->os_name, '|')));
            if (stripos($details->os_name, " 95") !== false) {
                $details->os_family = "Windows 95";
            }
            if (stripos($details->os_name, " 98") !== false) {
                $details->os_family = "Windows 98";
            }
            if (stripos($details->os_name, " NT") !== false) {
                $details->os_family = "Windows NT";
            }
            if (stripos($details->os_name, " 2000") !== false) {
                $details->os_family = "Windows 2000";
            }
            if (stripos($details->os_name, " XP") !== false) {
                $details->os_family = "Windows XP";
            }
            if (stripos($details->os_name, "2003") !== false) {
                $details->os_family = "Windows 2003";
            }
            if (stripos($details->os_name, "Vista") !== false) {
                $details->os_family = "Windows Vista";
            }
            if (stripos($details->os_name, "2008") !== false) {
                $details->os_family = "Windows 2008";
            }
            if (stripos($details->os_name, "Windows 7") !== false) {
                $details->os_family = "Windows 7";
            }
            if (stripos($details->os_name, "Windows 8") !== false) {
                $details->os_family = "Windows 8";
            }
            if (stripos($details->os_name, "2012") !== false) {
                $details->os_family = "Windows 2012";
            }
            if (stripos($details->os_name, "Windows 10") !== false) {
                $details->os_family = "Windows 10";
            }
        }

        return($details);
    }
Beispiel #13
0
 public function process_subnet()
 {
     // accept or process the output of the discover subnet script - nmap details
     if (!isset($_POST['form_details'])) {
         $this->load->view('v_process_subnet', $this->data);
     } else {
         $display = '';
         if ($this->input->post('debug') and strpos($_SERVER['HTTP_ACCEPT'], 'html')) {
             $display = 'y';
             echo "<pre>\n";
             echo "DEBUG - Starting process_subnet.\n";
             echo "***********************************************************************************\n";
             echo "* NOTE - THIS PAGE WILL CONTINUOUSLY RENDER UNTIL THE DISCOVERY HAS FINISHED      *\n";
             echo "* WATCH YOUR BROSWER TO SEE WHEN THE PAGE FINISHES RENDERING                      *\n";
             echo "* DO NOT REFRESH THIS PAGE OR ATTEMPT TO GO 'back' UNTIL THE PAGE HAS COMPLETED   *\n";
             echo "***********************************************************************************\n";
         }
         $this->load->model('m_oa_user');
         $this->load->model('m_scripts');
         if (isset($this->session->userdata['user_id']) and is_numeric($this->session->userdata['user_id'])) {
             $this->user = $this->m_oa_user->get_user_details($this->session->userdata['user_id']);
         }
         // all logging will be as below, only the message will change
         $log_details = new stdClass();
         $log_details->severity = 7;
         $log_details->file = 'system';
         $log_details->display = $display;
         if (!$this->m_oa_config->check_blessed($_SERVER['REMOTE_ADDR'], '')) {
             if ($display == 'y') {
                 $log_details->message = "Audit submission from an IP (" . $_SERVER['REMOTE_ADDR'] . ") not in the list of blessed subnets, exiting.";
                 echo "\n" . $log_details->message . "\n";
                 stdlog($log_details);
             }
             exit;
         }
         $this->load->helper('url');
         $this->load->model('m_credentials');
         if ($display == 'y') {
             echo 'DEBUG - <a href=\'' . base_url() . "index.php/discovery/discover_subnet'>Back to input page</a>\n";
             echo 'DEBUG - <a href=\'' . base_url() . "index.php'>Front Page</a>\n";
         }
         if (php_uname('s') != 'Windows NT') {
             $filepath = $this->config->config['base_path'] . '/other';
         } else {
             $filepath = $this->config->config['base_path'] . '\\other';
         }
         $this->load->helper('xml');
         $xml_input = $_POST['form_details'];
         try {
             $xml = new SimpleXMLElement($xml_input);
         } catch (Exception $error) {
             // not a valid XML string
             $log_details->message = 'Invalid XML input for discovery from ' . $_SERVER['REMOTE_ADDR'];
             stdlog($log_details);
             exit;
         }
         $this->load->helper('url');
         $this->load->library('encrypt');
         $this->load->helper('ipmi');
         if (extension_loaded('snmp')) {
             $this->load->helper('snmp');
             $this->load->helper('snmp_oid');
         }
         $this->load->model('m_system');
         $this->load->model('m_oa_group');
         $this->load->model('m_audit_log');
         $this->load->model('m_change_log');
         $this->load->model('m_devices_components');
         $this->load->model('m_devices');
         $timestamp = $this->config->config['timestamp'];
         $count = 0;
         foreach ($xml->children() as $details) {
             $details = (object) $details;
             if (isset($details->complete) and $details->complete == 'y') {
                 // delete the credential set
                 if ($display == 'y') {
                     echo "DEBUG - ----------------------------------------------------\n";
                 }
                 $this->echo_details($details);
                 sleep(5);
                 $log_details->message = 'Deleting credential set for ' . $details->subnet_range . ' submitted on ' . $details->subnet_timestamp;
                 stdlog($log_details);
                 $sql = '/* discovery::process_subnet */ DELETE FROM oa_temp WHERE temp_name = \'Subnet Credentials - ' . $details->subnet_range . '\' and temp_timestamp = \'' . $details->subnet_timestamp . '\' ';
                 $query = $this->db->query($sql);
             } else {
                 $skip = false;
                 if (stripos(' ' . $this->config->config['discovery_ip_exclude'] . ' ', ' ' . $details->ip . ' ') !== false) {
                     # Our ip address matched an ip in the discovery_ip_exclude list - exit
                     $log_details->message = $details->ip . ' is in the list of excluded ip addresses - skipping.';
                     stdlog($log_details);
                     $skip = true;
                 }
                 if (!$skip) {
                     $log_details->message = 'Start processing ' . $details->ip;
                     stdlog($log_details);
                     $count++;
                     $details->last_seen = $timestamp;
                     $details->last_user = '';
                     $details->last_seen_by = 'nmap';
                     $details->domain = '';
                     $details->audits_ip = ip_address_to_db($_SERVER['REMOTE_ADDR']);
                     $details->hostname = '';
                     if ($this->config->item('discovery_use_dns') == 'y') {
                         $details = dns_validate($details, $display);
                     }
                     $details->id = '';
                     $details->id = $this->m_system->find_system($details);
                     $details->last_seen_user = '';
                     $details->network_address = '';
                     $details->limit = 1000000;
                     $details->count = 0;
                     $details->use_https = '';
                     // # 1.12.6
                     $credentials = array();
                     // If we find a device and we're in DEBUG, output a result line.
                     if ($display == 'y') {
                         if (!empty($details->id)) {
                             echo 'DEBUG - Device found with ID: <a href=\'' . base_url() . 'index.php/main/system_display/' . $details->id . '\'>' . $details->id . "</a>.\n";
                         }
                     }
                     // Device specific credentials
                     if (!empty($details->id)) {
                         $temp = $this->m_devices_components->read(intval($details->id), 'y', 'credential', '', '*');
                         if (count($temp) > 0) {
                             foreach ($temp as $credential) {
                                 $credentials[] = $credential;
                             }
                         }
                         unset($temp);
                     }
                     // Credential Sets
                     $temp = $this->m_credentials->collection();
                     if (count($temp) > 0) {
                         $credentials = array_merge($credentials, $temp);
                     }
                     unset($temp);
                     // supplied credentials
                     $sql = '/* discovery::process_subnet */ SELECT temp_value FROM oa_temp WHERE temp_name = \'Subnet Credentials - ' . $details->subnet_range . '\' and temp_timestamp = \'' . $details->subnet_timestamp . '\' ORDER BY temp_id DESC LIMIT 1';
                     $query = $this->db->query($sql);
                     $row = $query->row();
                     $supplied_credentials = @$row->temp_value;
                     $supplied = new stdClass();
                     if (isset($supplied_credentials) and $supplied_credentials > '') {
                         $supplied_credentials = $this->encrypt->decode($supplied_credentials);
                         $supplied_credentials = json_decode($supplied_credentials);
                         $details->last_seen_user = @$supplied_credentials->last_user;
                         $details->network_address = @$supplied_credentials->network_address;
                         $details->limit = (int) @$supplied_credentials->limit;
                         $details->count = (int) @$supplied_credentials->count;
                         $details->org_id = (int) @$supplied_credentials->org;
                         $details->location_id = (int) @$supplied_credentials->location;
                         $details->org_id = (int) @$supplied_credentials->org;
                         $details->location_id = (int) @$supplied_credentials->location;
                         $details->use_https = (string) @$supplied_credentials->use_https;
                     }
                     # TODO - replace the ugly code below
                     $creds = array();
                     foreach ($credentials as $credential) {
                         $creds[] = $credential->attributes;
                     }
                     unset($credentials);
                     $credentials = $creds;
                     unset($creds);
                     // default Open-AudIT credentials
                     // $default = $this->m_oa_config->get_credentials();
                     // unset($default);
                     if (intval($details->count) >= intval($details->limit)) {
                         # we have discovered the requested number of devcies
                         $log_details->message = 'Count from DB is higher than requested limit, exiting. Count: ' . $details->count . ' Limit: ' . $details->limit;
                         stdlog($log_details);
                         return;
                     }
                     if (empty($supplied_credentials)) {
                         $supplied_credentials = new stdClass();
                     }
                     if (empty($supplied_credentials->count)) {
                         $supplied_credentials->count = 0;
                     } else {
                         $supplied_credentials->count++;
                     }
                     $sql = '/* discovery::process_subnet */ UPDATE oa_temp SET temp_value = ? WHERE temp_name = \'Subnet Credentials - ' . $details->subnet_range . '\' and temp_timestamp = \'' . $details->subnet_timestamp . '\'';
                     $data_in = json_encode($supplied_credentials);
                     $data_in = $this->encrypt->encode($data_in);
                     $data = array("{$data_in}");
                     $query = $this->db->query($sql, $data);
                     $details->last_user = $details->last_seen_user;
                     $log_details->user = $details->last_seen_user;
                     // create the URL for use by the audit scripts
                     # use $_POST if supplied
                     if (isset($_POST['network_address']) and $_POST['network_address'] > '') {
                         $temp = explode('/', base_url());
                         $url = str_replace($temp[2], $_POST['network_address'], base_url());
                         # use $details->network_address if stored in DB
                     } elseif (isset($details->network_address) and $details->network_address != '') {
                         $temp = explode('/', base_url());
                         $url = str_replace($temp[2], $details->network_address, base_url());
                         # use the open-audit default config value
                     } elseif (isset($this->config->config['default_network_address']) and $this->config->config['default_network_address'] > '') {
                         $temp = explode('/', base_url());
                         $url = str_replace($temp[2], $this->config->config['default_network_address'], base_url());
                         # use the PHP function to guess as a last resort
                     } else {
                         $url = base_url();
                     }
                     unset($details->network_address);
                     if ($details->use_https == 'on') {
                         $url = str_ireplace('http://', 'https://', $url);
                     }
                     if (isset($supplied->snmp_community) and $supplied->snmp_community != '') {
                         $details->snmp_community = $supplied->snmp_community;
                     }
                     // output to log file and DEBUG the status of the three main services
                     $log_details->message = 'WMI Status is ' . $details->wmi_status . ' on ' . $details->ip;
                     stdlog($log_details);
                     // On OSX we cannot run Nmap and get a UDP port result for 161 as 'You requested a scan type which requires root privileges.' So just set the snmp_status to true and attempt to snmp_audit the target device
                     if (php_uname('s') == 'Darwin') {
                         $details->snmp_status = 'true';
                         $details->nmap_ports .= ',161/udp/snmp';
                     }
                     $log_details->message = 'SNMP Status is ' . $details->snmp_status . ' on ' . $details->ip;
                     stdlog($log_details);
                     $log_details->message = 'SSH Status is ' . $details->ssh_status . ' on ' . $details->ip;
                     stdlog($log_details);
                     // get rid of os_* as nmap only guesses
                     unset($details->os_group);
                     unset($details->os_family);
                     unset($details->os_name);
                     # IPMI audit
                     # TODO - make a ipmi_helper::ipmi_credentials function
                     // if (isset($this->config->config['discovery_use_ipmi']) and $this->config->config['discovery_use_ipmi'] == 'y') {
                     //     $credentials_ipmi = new stdClass();
                     //     $credentials_ipmi->type = 'ipmi';
                     //     $credentials_ipmi->credentials = new stdClass();
                     //     $credentials_ipmi->credentials->username = $this->config->config['default_ipmi_username'];
                     //     $credentials_ipmi->credentials->password = $this->config->config['default_ipmi_username'];
                     //     $credentials[] = $credentials_ipmi;
                     //     $ipmi_details = ipmi_audit($details->ip, $credentials_ipmi, $display);
                     //     if (!empty($ipmi_details)) {
                     //         foreach ($ipmi_details as $key => $value) {
                     //             if (!empty($value)) {
                     //                 $details->key = $value;
                     //             }
                     //         }
                     //     }
                     //     if ($details->serial) {
                     //         $details->last_seen_by = 'ipmi';
                     //         $details->audits_ip = '127.0.0.1';
                     //     }
                     // }
                     // SNMP audit
                     if (!extension_loaded('snmp') and $details->snmp_status == 'true') {
                         $log_details->message = 'PHP extension not loaded, skipping SNMP data retrieval for ' . $details->ip;
                         stdlog($log_details);
                     }
                     if (extension_loaded('snmp') and $details->snmp_status == 'true') {
                         $log_details->message = 'Testing SNMP credentials for ' . $details->ip;
                         stdlog($log_details);
                         $credentials_snmp = snmp_credentials($details->ip, $credentials, $display);
                     } else {
                         $credentials_snmp = false;
                     }
                     if ($credentials_snmp) {
                         $temp_array = snmp_audit($details->ip, $credentials_snmp, $display);
                         if (!empty($temp_array['details'])) {
                             foreach ($temp_array['details'] as $key => $value) {
                                 if (!empty($value)) {
                                     $details->{$key} = $value;
                                 }
                             }
                             $details->last_seen_by = 'snmp';
                             $details->audits_ip = '127.0.0.1';
                         }
                         if (!empty($temp_array['interfaces'])) {
                             $network_interfaces = $temp_array['interfaces'];
                         }
                         if (!empty($temp_array['modules'])) {
                             $modules = $temp_array['modules'];
                         }
                         if (!empty($temp_array['ip'])) {
                             $ip = $temp_array['ip'];
                         }
                         if (!empty($temp_array['guests'])) {
                             $guests = $temp_array['guests'];
                         }
                     }
                     // new for 1.8.4 - if we have a non-computer, do not attempt to connect using SSH
                     if ($details->type != 'computer' and $details->type != '' and $details->type != 'unknown' and $details->os_family != 'DD-WRT' and stripos($details->sysDescr, 'dd-wrt') === false) {
                         $log_details->message = 'Not a computer and not a DD-WRT device, setting SSH status to false for ' . $details->ip . ' (System ID ' . $details->id . ')';
                         stdlog($log_details);
                         $details->ssh_status = 'false';
                     }
                     # test for working SSH credentials
                     if ($details->ssh_status == 'true') {
                         $log_details->message = 'Testing SSH credentials for ' . $details->ip;
                         stdlog($log_details);
                         $credentials_ssh = ssh_credentials($details->ip, $credentials, $display);
                     } else {
                         $credentials_ssh = false;
                     }
                     # run SSH audit commands
                     if ($details->ssh_status == 'true' and $credentials_ssh) {
                         $ssh_details = ssh_audit($details->ip, $credentials_ssh, $display);
                         if (!empty($ssh_details)) {
                             $details->last_seen_by = 'ssh';
                             $details->audits_ip = '127.0.0.1';
                             foreach ($ssh_details as $key => $value) {
                                 if (!empty($value)) {
                                     $details->{$key} = $value;
                                 }
                             }
                         }
                     }
                     // test for working Windows credentials
                     if ($details->wmi_status == 'true') {
                         $log_details->message = 'Testing Windows credentials for ' . $details->ip;
                         stdlog($log_details);
                         $credentials_windows = windows_credentials($details->ip, $credentials, $display);
                     } else {
                         $credentials_windows = false;
                     }
                     # run Windows audit commands
                     if ($details->wmi_status == 'true' and $credentials_windows) {
                         $windows_details = wmi_audit($details->ip, $credentials_windows, $display);
                         if (!empty($windows_details)) {
                             $details->last_seen_by = 'windows';
                             $details->audits_ip = '127.0.0.1';
                             foreach ($windows_details as $key => $value) {
                                 if (!empty($value)) {
                                     $details->{$key} = $value;
                                 }
                             }
                         }
                     }
                     # in the case where port 5060 is detected and we have no other information, assign type 'voip phone'
                     if (empty($details->type) and empty($details->snmp_oid) and empty($details->uuid) and stripos($details->nmap_result, '5060/') !== false) {
                         $details->type = 'voip phone';
                     }
                     if ($this->config->item('discovery_use_dns') == 'y') {
                         $details = dns_validate($details, $display);
                     }
                     $details->id = $this->m_system->find_system($details, $display);
                     if ($display == 'y') {
                         $details->show_output = true;
                         echo "=======DETAILS======\n";
                         foreach ($details as $key => $value) {
                             echo "DEBUG - " . $key . ": " . (string) $value . "\n";
                         }
                         echo "====================\n";
                         ob_flush();
                         flush();
                     }
                     // insert or update the device
                     if (isset($details->id) and $details->id != '') {
                         // we have a system id - UPDATE
                         $log_details->message = strtoupper($details->last_seen_by) . " update for {$details->ip} (System ID {$details->id})";
                         stdlog($log_details);
                         $details->original_last_seen = $this->m_devices_components->read($details->id, 'y', 'system', '', 'last_seen');
                         $details->original_last_seen_by = $this->m_devices_components->read($details->id, 'y', 'system', '', 'last_seen_by');
                         $this->m_system->update_system($details, $display);
                     } else {
                         // we have a new system - INSERT
                         $log_details->message = strtoupper($details->last_seen_by) . " insert for {$details->ip}";
                         stdlog($log_details);
                         $details->id = $this->m_system->insert_system($details, $display);
                     }
                     // grab some timestamps
                     $details->last_seen = $this->m_devices_components->read($details->id, 'y', 'system', '', 'last_seen');
                     $details->first_seen = $this->m_devices_components->read($details->id, 'y', 'system', '', 'first_seen');
                     // Insert an audit log
                     if (isset($this->user->full_name)) {
                         $temp_user = $this->user->full_name;
                     } else {
                         $temp_user = '';
                     }
                     $this->m_audit_log->create($details->id, $temp_user, $details->last_seen_by, $details->audits_ip, '', '', $details->last_seen);
                     unset($temp_user);
                     // Update the groups
                     if ($this->config->config['discovery_update_groups'] == 'y') {
                         $this->m_oa_group->update_system_groups($details);
                     }
                     // update any network interfaces and ip addresses retrieved by SNMP
                     if (isset($network_interfaces) and is_array($network_interfaces) and count($network_interfaces) > 0) {
                         $input = new stdClass();
                         $input->item = array();
                         $input->item = $network_interfaces;
                         $this->m_devices_components->process_component('network', $details, $input, $display);
                     }
                     // insert any ip addresses
                     if (isset($ip->item) and count($ip->item) > 0) {
                         $this->m_devices_components->process_component('ip', $details, $ip, $display);
                     }
                     // finish off with updating any network IPs that don't have a matching interface
                     $this->m_devices_components->update_missing_interfaces($details->id);
                     // insert any modules
                     if (isset($modules) and count($modules) > 0) {
                         $input = new stdClass();
                         $input->item = array();
                         $input->item = $modules;
                         $this->m_devices_components->process_component('module', $details, $input, $display);
                     }
                     // insert any found virtual machines
                     if (isset($guests) and is_array($guests) and count($guests) > 0) {
                         $vm = new stdClass();
                         $vm->item = array();
                         $vm->item = $guests;
                         $this->m_devices_components->process_component('vm', $details, $vm, $display);
                     }
                     if (!empty($credentials_snmp) and $details->snmp_status == 'true') {
                         $log_details->message = 'SNMP credential update for ' . $details->ip . ' (System ID ' . $details->id . ')';
                         stdlog($log_details);
                         $this->m_devices->sub_resource_create($details->id, 'credential', $credentials_snmp);
                     }
                     if (!empty($credentials_ssh) and $details->ssh_status == 'true') {
                         $log_details->message = 'SSH credential update for ' . $details->ip . ' (System ID ' . $details->id . ')';
                         stdlog($log_details);
                         $this->m_devices->sub_resource_create($details->id, 'credential', $credentials_ssh);
                     }
                     if (isset($credentials_windows) and $details->wmi_status == 'true') {
                         $log_details->message = "Windows credential update for {$details->ip} (System ID {$details->id})";
                         stdlog($log_details);
                         $this->m_devices->sub_resource_create($details->id, 'credential', $credentials_windows);
                     }
                     // $details->id is now set
                     if ($display == 'y') {
                         echo "DEBUG - System ID <a href='" . base_url() . "index.php/devices/" . $details->id . "'>" . $details->id . "</a>\n";
                     }
                     // process and store the Nmap result
                     $nmap_result = array();
                     foreach (explode(',', $details->nmap_ports) as $port) {
                         $temp = explode('/', $port);
                         $nmap_item = new stdClass();
                         $nmap_item->ip = (string) $details->ip;
                         $nmap_item->port = $temp[0];
                         $nmap_item->protocol = $temp[1];
                         $nmap_item->program = $temp[2];
                         if ($nmap_item->port != '') {
                             $nmap_result[] = $nmap_item;
                         }
                         unset($nmap_item);
                         unset($temp);
                     }
                     if (count($nmap_result) > 0) {
                         $input = new stdClass();
                         $input->item = array();
                         $input->item = $nmap_result;
                         $this->m_devices_components->process_component('nmap', $details, $input, $display);
                     }
                     // insert a blank to indicate we're finished this part of the discovery
                     // if required, the audit scripts will insert their own audit logs
                     $this->m_audit_log->update('debug', '', $details->id, $details->last_seen);
                     # Audit Windows
                     if ($details->wmi_status == "true" and $credentials_windows) {
                         $log_details->message = "Starting windows audit for {$details->ip} (System ID {$details->id})";
                         stdlog($log_details);
                         $share = '\\admin$';
                         $destination = 'audit_windows.vbs';
                         if ($display = 'y') {
                             $debugging = 3;
                         } else {
                             $debugging = 0;
                         }
                         $sql = "/* discovery::process_subnet */ SELECT * FROM `scripts` WHERE `name` = 'audit_windows.vbs' AND `based_on` = 'audit_windows.vbs' ORDER BY `id` LIMIT 1";
                         $query = $this->db->query($sql);
                         $result = $query->result();
                         if (!empty($result[0])) {
                             $script_details = $result[0];
                             # Just ensure we delete any audit scripts that might exist.
                             # Shouldn't be required because we're creating based on the timestamp
                             # Then open the file for writing
                             $ts = date('y_m_d_H_i_s');
                             if (php_uname('s') == 'Windows NT') {
                                 $source_name = 'scripts\\audit_windows_' . $ts . '.vbs';
                                 @unlink($this->config->config['base_path'] . '\\other\\' . $source_name);
                                 try {
                                     $fp = fopen($this->config->config['base_path'] . '\\other\\' . $source_name, 'w');
                                 } catch (Exception $e) {
                                     print_r($e);
                                 }
                             } else {
                                 $source_name = 'scripts/audit_windows_' . $ts . '.vbs';
                                 @unlink($this->config->config['base_path'] . '/other/' . $source_name);
                                 try {
                                     $fp = fopen($this->config->config['base_path'] . '/other/' . $source_name, 'w');
                                 } catch (Exception $e) {
                                     print_r($e);
                                 }
                             }
                             $script = $this->m_scripts->download($script_details->id);
                             fwrite($fp, $script);
                             fclose($fp);
                         } else {
                             $source_name = 'audit_windows.vbs';
                         }
                         if (php_uname('s') != 'Windows NT') {
                             $source = $this->config->config['base_path'] . '/other/' . $source_name;
                             $command = "cscript c:\\windows\\audit_windows.vbs submit_online=y create_file=n strcomputer=. url=" . $url . "index.php/system/add_system debugging=" . $debugging . " system_id=" . $details->id . " last_seen_by=audit_wmi";
                             if (copy_to_windows($details->ip, $credentials_windows, $share, $source, $destination, $display)) {
                                 if (execute_windows($details->ip, $credentials_windows, $command, $display)) {
                                     # All complete!
                                 } else {
                                     # run audit script failed
                                 }
                             } else {
                                 # copy audit script to Windows failed
                             }
                             if ($source_name != 'audit_windows.vbs') {
                                 unlink($this->config->config['base_path'] . '/other/' . $source_name);
                             }
                         } else {
                             #if (strtolower($_SERVER['USERPROFILE']) == 'c:\windows\system32\config\systemprofile') {
                             if (exec('whoami') == 'nt authority\\system') {
                                 # We're running on the LocalSystem account.
                                 # We cannot copy the audit script to the target and then run it,
                                 # We _must_ run the script locally and use $details->ip as the script target
                                 # We will loose the ability to retrieve certain items like files, netstat, tasks, etc
                                 $log_details->message = "Windows audit for {$details->ip} (System ID {$details->id})";
                                 stdlog($log_details);
                                 $username = $credentials_windows->credentials->username;
                                 $temp = explode('@', $username);
                                 $username = $temp[0];
                                 if (count($temp) > 1) {
                                     $domain = $temp[1] . '\\';
                                 } else {
                                     $domain = '';
                                 }
                                 unset($temp);
                                 if ($display == 'y') {
                                     $script_string = "{$filepath}\\" . $source_name . " strcomputer=" . $details->ip . " submit_online=y create_file=n struser="******" strpass="******" url=" . $url . "index.php/system/add_system debugging=3 system_id=" . $details->id . " last_seen_by=audit_wmi";
                                     $command_string = "%comspec% /c start /b cscript //nologo " . $script_string;
                                     exec($command_string, $output, $return_var);
                                     $command_string = str_replace($credentials_windows->credentials->password, '******', $command_string);
                                     echo 'DEBUG - Command Executed: ' . $command_string . "\n";
                                     echo 'DEBUG - Return Value: ' . $return_var . "\n";
                                     echo "DEBUG - Command Output:\n";
                                     print_r($output);
                                     if ($return_var != '0') {
                                         $error = "Attempt to run audit_windows.vbs on {$details->ip} has failed";
                                         $log_details->message = $error;
                                         stdlog($log_details);
                                     } else {
                                         $log_details->message = "Attempt to run audit_windows.vbs on {$details->ip} has succeeded";
                                         stdlog($log_details);
                                     }
                                     $output = null;
                                     $return_var = null;
                                 } else {
                                     $script_string = "{$filepath}\\" . $source_name . " strcomputer=" . $details->ip . " submit_online=y create_file=n struser="******" strpass="******" url=" . $url . "index.php/system/add_system debugging=0  system_id=" . $details->id . " last_seen_by=audit_wmi";
                                     $command_string = "%comspec% /c start /b cscript //nologo " . $script_string . " &";
                                     pclose(popen($command_string, "r"));
                                 }
                                 $command_string = null;
                                 if ($source_name != 'audit_windows.vbs') {
                                     unlink($this->config->config['base_path'] . '/other/' . $source_name);
                                 }
                             } else {
                                 # We are running as something other than the LocalSystem account.
                                 # Therefore we _should_ be able to copy the audit script to tthe target and start it there
                                 # and therefore retrieve ALL information
                                 $source = $this->config->config['base_path'] . '\\other\\' . $source_name;
                                 rename($source, 'c:\\windows\\audit_windows_' . $ts . '.vbs');
                                 $source = 'audit_windows_' . $ts . '.vbs';
                                 $command = "cscript \\\\" . $details->ip . "\\admin\$\\audit_windows_" . $ts . ".vbs submit_online=y create_file=n strcomputer=. url=" . $url . "index.php/system/add_system debugging=" . $debugging . " system_id=" . $details->id . " self_delete=y last_seen_by=audit_wmi";
                                 if (copy_to_windows($details->ip, $credentials_windows, $share, $source, $destination, $display)) {
                                     if (execute_windows($details->ip, $credentials_windows, $command, $display)) {
                                         # All complete!
                                     } else {
                                         # run audit script failed
                                     }
                                 } else {
                                     # copy audit script to Windows failed
                                 }
                                 if ($source_name != 'audit_windows.vbs') {
                                     unlink('c:\\windows\\audit_windows_' . $ts . '.vbs');
                                 }
                             }
                         }
                     }
                     # Audit SSH
                     if ($details->ssh_status == "true" and $details->os_family != 'DD-WRT' and $credentials_ssh) {
                         $log_details->message = "Starting ssh audit for {$details->ip} (System ID {$details->id})";
                         stdlog($log_details);
                         // $command = 'uname';
                         // $ssh_result = ssh_command($details->ip, $credentials_ssh, $command, $display);
                         // if ($ssh_result['status'] == 0) {
                         //     $remote_os = $ssh_result['output'][0];
                         // }
                         // switch (strtolower($remote_os)) {
                         switch (strtolower($details->os_group)) {
                             case 'aix':
                                 $audit_script = 'audit_aix.sh';
                                 break;
                             case 'vmkernel':
                                 $audit_script = 'audit_esxi.sh';
                                 break;
                             case 'linux':
                                 $audit_script = 'audit_linux.sh';
                                 break;
                             case 'darwin':
                                 $audit_script = 'audit_osx.sh';
                                 break;
                             case 'windows':
                                 $audit_script = '';
                                 break;
                             default:
                                 $audit_script = '';
                                 break;
                         }
                         $destination = $audit_script;
                         if ($display = 'y') {
                             $debugging = 3;
                         } else {
                             $debugging = 0;
                         }
                         $sql = "/* discovery::process_subnet */ SELECT * FROM `scripts` WHERE `name` = '{$audit_script}' AND `based_on` = '{$audit_script}' ORDER BY `id` LIMIT 1";
                         $query = $this->db->query($sql);
                         $result = $query->result();
                         if (!empty($result[0])) {
                             $script_details = $result[0];
                             # Just ensure we delete any audit scripts that might exist.
                             # Shouldn't be required because we're creating based on the timestamp
                             # Then open the file for writing
                             $ts = date('y_m_d_H_i_s');
                             if (php_uname('s') == 'Windows NT') {
                                 $source_name = 'scripts\\' . str_replace('.sh', '_' . $ts . '.sh', $audit_script);
                                 $unlink = $this->config->config['base_path'] . '\\other\\' . $source_name;
                                 @unlink($unlink);
                                 $fp = fopen($this->config->config['base_path'] . '\\other\\' . $source_name, 'w');
                             } else {
                                 $source_name = 'scripts/' . str_replace('.sh', '_' . $ts . '.sh', $audit_script);
                                 $unlink = $this->config->config['base_path'] . '/other/' . $source_name;
                                 @unlink($unlink);
                                 try {
                                     $fp = fopen($this->config->config['base_path'] . '/other/' . $source_name, 'w');
                                 } catch (Exception $e) {
                                     print_r($e);
                                 }
                             }
                             $script = $this->m_scripts->download($script_details->id);
                             fwrite($fp, $script);
                             fclose($fp);
                         } else {
                             $unlink = '';
                             $source_name = $audit_script;
                         }
                         unset($temp);
                         if ($audit_script != '') {
                             # copy the audit script to the target ip
                             if (php_uname('s') == 'Windows NT') {
                                 $source = $filepath . '\\' . $source_name;
                             } else {
                                 $source = $filepath . '/' . $source_name;
                             }
                             $destination = $this->config->item('discovery_linux_script_directory');
                             if (substr($destination, -1) != '/') {
                                 $destination .= '/';
                             }
                             $destination .= $audit_script;
                             if ($ssh_result = scp($details->ip, $credentials_ssh, $source, $destination, $display)) {
                                 # Successfully copied the audit script
                                 $command = 'chmod ' . $this->config->item('discovery_linux_script_permissions') . ' ' . $destination;
                                 $temp = ssh_command($details->ip, $credentials_ssh, $command, $display);
                             }
                             if ($display = 'y') {
                                 $debugging = 3;
                             } else {
                                 $debugging = 0;
                             }
                         }
                         # audit anything that's not ESX
                         if ($audit_script != 'audit_esxi.sh' and $audit_script != '') {
                             # successfully copied and chmodded the audit script
                             if (!empty($credentials_ssh->sudo)) {
                                 # run the audit script as a normal user, using sudo
                                 $command = 'echo "' . $credentials_ssh->credentials->password . '" | ' . $credentials_ssh->sudo . ' -S ' . $this->config->item('discovery_linux_script_directory') . $audit_script . ' submit_online=y create_file=n url=' . $url . 'index.php/system/add_system debugging=' . $debugging . ' system_id=' . $details->id . ' display=' . $display . ' last_seen_by=audit_ssh';
                             } else {
                                 # run the script without using sudo
                                 $command = $this->config->item('discovery_linux_script_directory') . $audit_script . ' submit_online=y create_file=n url=' . $url . 'index.php/system/add_system debugging=' . $debugging . ' system_id=' . $details->id . ' display=' . $display . ' last_seen_by=audit_ssh';
                             }
                             $result = ssh_command($details->ip, $credentials_ssh, $command, $display);
                             if ($unlink != '') {
                                 unlink($unlink);
                             }
                         }
                         # audit ESX
                         if ($audit_script == 'audit_esxi.sh') {
                             $command = $this->config->item('discovery_linux_script_directory') . $audit_script . ' submit_online=y last_seen_by=audit_ssh create_file=n debugging=0 echo_output=y system_id=' . $details->id . ' 2>/dev/null';
                             if ($result = ssh_command($details->ip, $credentials_ssh, $command, $display)) {
                                 if ($result['status'] == 0) {
                                     $script_result = '';
                                     foreach ($result['output'] as $line) {
                                         $script_result .= $line . "\n";
                                     }
                                     $script_result = preg_replace('/\\s+/', ' ', $script_result);
                                     $script_result = str_replace("> <", "><", $script_result);
                                     $esx_input = trim($script_result);
                                     try {
                                         $esx_xml = new SimpleXMLElement($esx_input);
                                     } catch (Exception $error) {
                                         // not a valid XML string
                                         $log_details->message = 'Invalid XML input for ESX audit script';
                                         stdlog($log_details);
                                         exit;
                                     }
                                     $count = 0;
                                     foreach ($esx_xml->children() as $child) {
                                         if ($child->getName() === 'sys') {
                                             $esx_details = (object) $esx_xml->sys;
                                             if (!isset($esx_details->ip) or $esx_details->ip == '') {
                                                 $esx_details->ip = $details->ip;
                                             }
                                             $esx_details->system_id = $this->m_system->find_system($esx_details, $display);
                                             $esx_details->last_seen = $details->last_seen;
                                             if (isset($esx_details->system_id) and $esx_details->system_id != '') {
                                                 // we have an existing device
                                                 $esx_details->original_last_seen_by = $this->m_devices_components->read($esx_details->system_id, 'y', 'system', '', 'last_seen_by');
                                                 $esx_details->original_last_seen = $this->m_devices_components->read($esx_details->system_id, 'y', 'system', '', 'last_seen');
                                                 $this->m_system->update_system($esx_details);
                                                 $log_details->message = "ESX update for {$esx_details->ip} (System ID {$esx_details->system_id})";
                                                 stdlog($log_details);
                                             } else {
                                                 // we have a new system
                                                 $esx_details->system_id = $this->m_system->insert_system($esx_details);
                                                 $log_details->message = "ESX insert for {$esx_details->ip} (System ID {$esx_details->system_id})";
                                                 stdlog($log_details);
                                             }
                                             if (!isset($esx_details->audits_ip)) {
                                                 $esx_details->audits_ip = $details->audits_ip;
                                             }
                                             if (isset($this->user->full_name)) {
                                                 $temp_user = $this->user->full_name;
                                             } else {
                                                 $temp_user = '';
                                             }
                                             $this->m_audit_log->create($esx_details->system_id, $temp_user, $esx_details->last_seen_by, $esx_details->audits_ip, '', '', $esx_details->last_seen);
                                             unset($temp_user);
                                         }
                                     }
                                     $this->m_devices_components->process_component('network', $esx_details, $esx_xml->network, $display);
                                     $this->m_devices_components->process_component('software', $esx_details, $esx_xml->software, $display);
                                     $this->m_devices_components->process_component('processor', $esx_details, $esx_xml->processor, $display);
                                     $this->m_devices_components->process_component('bios', $esx_details, $esx_xml->bios, $display);
                                     $this->m_devices_components->process_component('memory', $esx_details, $esx_xml->memory, $display);
                                     $this->m_devices_components->process_component('motherboard', $esx_details, $esx_xml->motherboard, $display);
                                     $this->m_devices_components->process_component('video', $esx_details, $esx_xml->video, $display);
                                     $this->m_devices_components->process_component('vm', $esx_details, $esx_xml->vm, $display);
                                     $this->m_devices_components->process_component('ip', $esx_details, $esx_xml->ip, $display);
                                 }
                             }
                         }
                         $log_details->message = "Completed processing {$details->ip} (System ID {$details->id})";
                         stdlog($log_details);
                     }
                     // close the 'skip'
                 }
                 // close the device / complete switch
                 unset($details);
             }
             // close for each device in XML
         }
         // close for form submission
     }
     // close function
 }
Beispiel #14
0
 /**
  * Process the supplied data and update an existing object
  *
  * @access public
  * @return NULL
  */
 public function create()
 {
     // Only admin's
     if ($this->user->admin !== 'y') {
         log_error('ERR-0008');
         output($this->response);
         exit;
     }
     echo "<pre>\n";
     $file = $_POST['file'];
     $log = new stdClass();
     $log->log_level = 7;
     $log->severity = 6;
     $log->message = 'NMIS import, importing nodes from ' . $file;
     $log->display = 'y';
     stdlog($log);
     $this->load->model('m_system');
     $this->load->model('m_devices');
     $timestamp = $this->config->config['timestamp'];
     $node_array = array();
     $file_handle = fopen($file, 'r');
     $string = fread($file_handle, filesize($file));
     $string = str_replace(PHP_EOL, ' ', $string);
     $string = str_replace("\r\n", ' ', $string);
     $string = str_replace("\n", ' ', $string);
     $string = str_replace(chr(13), ' ', $string);
     $string = str_replace('%hash = (', '{', $string);
     $string = str_replace(');', '}', $string);
     $string = str_replace('=>', ':', $string);
     $string = str_replace("'undef'", "''", $string);
     $string = str_replace('undef', "''", $string);
     $string = str_replace("'", '"', $string);
     $nodes = json_decode($string, true);
     unset($string);
     unset($file_handle);
     unset($file);
     switch (json_last_error()) {
         case JSON_ERROR_NONE:
             // no errors
             break;
         case JSON_ERROR_DEPTH:
             echo "Error importing Nmis.nodes file<br />\n";
             echo 'JSON_ERROR_DEPTH - Maximum stack depth exceeded<br />';
             exit;
             break;
         case JSON_ERROR_STATE_MISMATCH:
             echo "Error importing Nmis.nodes file<br />\n";
             echo 'JSON_ERROR_STATE_MISMATCH - Underflow or the modes mismatch<br />';
             exit;
             break;
         case JSON_ERROR_CTRL_CHAR:
             echo "Error importing Nmis.nodes file<br />\n";
             echo 'JSON_ERROR_CTRL_CHAR - Unexpected control character found<br />';
             exit;
             break;
         case JSON_ERROR_SYNTAX:
             echo "Error importing Nmis.nodes file<br />\n";
             echo 'JSON_ERROR_SYNTAX - Syntax error, malformed JSON<br />';
             print_r($string);
             exit;
             break;
         case JSON_ERROR_UTF8:
             echo "Error importing Nmis.nodes file<br />\n";
             echo 'JSON_ERROR_UTF8 - Malformed UTF-8 characters, possibly incorrectly encoded<br />';
             exit;
             break;
         default:
             echo "Error importing Nmis.nodes file<br />\n";
             echo 'Unknown error<br />';
             exit;
             break;
     }
     $nodes_in_file = 0;
     $nodes_collect = 0;
     $nodes_total = 0;
     foreach ($nodes as $node) {
         $nodes_in_file++;
         if (@$node['collect'] == 'true') {
             $nodes_collect++;
             #echo "=======================\n";
             $device = new stdClass();
             $device->name = strtolower(@$node['name']);
             if (!filter_var($node['host'], FILTER_VALIDATE_IP) === false) {
                 $device->ip = $node['host'];
             } else {
                 if (strpos($node['host'], '.') !== false) {
                     $device->fqdn = $node['host'];
                     $temp = explode('.', $device->fqdn);
                     $device->hostname = $temp[0];
                     unset($temp);
                 } else {
                     $device->hostname = $node['host'];
                 }
             }
             $device = dns_validate($device, 'n');
             $device->omk_uuid = @$node['uuid'];
             $device->id = $this->m_system->find_system($device, 'n');
             $device->status = 'production';
             $device->credentials = new stdClass();
             $device->credentials->description = 'Imported from NMIS';
             $device->credentials->name = 'Device Specific Credentials';
             $device->credentials->type = 'snmp';
             $device->credentials->credentials = new stdClass();
             $temp = @$node['version'];
             switch ($temp) {
                 case 'snmpv1':
                     $device->credentials->credentials->version = 1;
                     break;
                 case 'snmpv2c':
                     $device->credentials->credentials->version = 2;
                     break;
                 case 'snmpv3':
                     $device->credentials->credentials->version = 3;
                     break;
                 default:
                     $device->credentials->credentials->version = 2;
                     break;
             }
             if ($device->credentials->credentials->version == 1) {
                 $device->credentials->credentials->community = @$node['community'];
             }
             if ($device->credentials->credentials->version == 2) {
                 $device->credentials->credentials->community = @$node['community'];
             }
             if ($device->credentials->credentials->version == 3) {
                 $device->credentials->type = 'snmp_v3';
                 $device->credentials->credentials->security_name = @$node['username'];
                 $device->credentials->credentials->authentication_passphrase = @$node['authpassword'];
                 $device->credentials->credentials->authentication_protocol = @$node['authprotocol'];
                 $device->credentials->credentials->privacy_passphrase = @$node['privpassword'];
                 $device->credentials->credentials->privacy_protocol = @$node['privprotocol'];
                 $device->credentials->credentials->security_level = 'noAuthNoPriv';
                 if (!empty(@$node['authpassword']) and !empty(@$node['authprotocol']) and empty($node['privpassword'])) {
                     $device->credentials->credentials->security_level = 'authNoPriv';
                 }
                 if (!empty(@$node['authpassword']) and !empty(@$node['authprotocol']) and !empty($node['privpassword']) and !empty($node['privprotocol'])) {
                     $device->credentials->credentials->security_level = 'authPriv';
                 }
             }
             $nodes_array[$device->ip] = $device;
         }
     }
     // echo "Nodes in file: " . $nodes_in_file . "\n";
     // echo "Nodes with collect: " . $nodes_collect . "\n";
     // echo "Total nodes: " . count($nodes_array) . "\n";
     // print_r($nodes_array);
     $ids = array();
     foreach ($nodes_array as $details) {
         $details->last_seen_by = 'nmis';
         $details->last_seen = $timestamp;
         if (!empty($details->id)) {
             $log->message = "Updating device " . $details->name . " (ID:" . $details->id . ")";
             stdlog($log);
             $this->m_devices->update($details);
         } else {
             $log->message = "Creating device " . $details->name;
             stdlog($log);
             $details->id = $this->m_devices->create($details);
         }
         $this->m_devices->sub_resource_create($details->id, 'credential', $details->credentials);
         $ids[] = $details->id;
         $data = new stdClass();
         $data->id = $details->id;
         $data->type = 'devices';
         $data->attributes = new stdClass();
         $data->attributes->id = $details->id;
         $data->attributes->name = $details->name;
         $data->attributes->hostname = $details->hostname;
         $data->attributes->ip = $details->ip;
         $this->response->data[] = $data;
     }
     $ids = implode(',', $ids);
     if ($this->response->meta->format === 'json') {
         output($this->response);
     } else {
         #exit();
         redirect('devices?action=update&ids=' . $ids);
     }
 }
Beispiel #15
0
    public function validate_user($username, $password)
    {
        $this->load->library('session');
        $this->load->helper('log');
        $log_details = new stdClass();
        $log_details->file = 'system';
        $log_details->severity = 7;


        $sql = "SELECT * FROM oa_user WHERE oa_user.name = ? LIMIT 1";
        $sql = '/* M_userlogin::validate_user */ ' . $sql;
        $data = array("$username");
        $query = $this->db->query($sql, $data);
        if ($query->num_rows() > 0) {
            $row = $query->row();
            $user_id = $row->id;
            $hash_password = $row->password;
            $user_data = array(    'username' => $row->name, 'logged_in' => true, 'user_id' => $row->id,
                            'user_full_name' => $row->full_name, 'user_lang' => $row->lang,
                            'user_theme' => $row->theme, 'user_admin' => $row->admin,
                            'user_debug' => 'n', 'user_sam' => $row->sam, );

            # make sure to validate if we have any older style MD5 passwords
            if ($hash_password == md5($password)) {
                # change the password to a salted SHA256
                # get 256 random bits in hex
                $salt = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
                # prepend the salt, then hash
                $hash = hash("sha256", $salt.$password);
                # store the salt and hash in the same string, so only 1 DB column is needed
                $encrypted_password = $salt.$hash;
                $sql = "/* m_userlogin::validate_user */ UPDATE oa_user SET password = ? WHERE id = ?";
                $data = array("$encrypted_password", "$user_id");
                $query = $this->db->query($sql, $data);

                return $user_data;
            }

            # compare the supplied and salted sha256 passwords
            # get the salt from the front of the hash
            $salt = substr($hash_password, 0, 64);
            # the SHA256 form the end of the hash
            $valid_hash = substr($hash_password, 64, 64);
            # hash the password being tested
            $test_hash = hash("sha256", $salt.$password);
            # if the hashes are exactly the same, the password is valid
            if ($test_hash == $valid_hash) {
                # correct password
                # NOTE - we must test if user is active when DB version > 20130512 release.
                # this releave (v1.0) added a flag to the users table for user_active.
                $sql = "/* m_userlogin::validate_user */ SELECT config_value FROM oa_config WHERE config_name = 'internal_version'";
                $query = $this->db->query($sql);
                $row = $query->row();
                $db_version = $row->config_value;
                if ($db_version < '20130512') {
                    # we have not updgraded the DB yet, so need to not attempt to check if user is active
                } else {
                    # this is a 1.0 (or above) version of the database
                    # only log user on to system if user is 'active'
                    $sql = "/* m_userlogin::validate_user */ SELECT active FROM oa_user WHERE id = ?";
                    $data = array($user_id);
                    $query = $this->db->query($sql, $data);
                    $row = $query->row();
                    if ($row->active == 'y') {
                        # we have an active user
                    } else {
                        $log_details->message = "User $username not set to active in DB.";
                        stdlog($log_details);
                        # remove the $data array
                        unset($user_data);
                        $user_data = 'fail';
                    }
                }
            } else {
                $log_details->message = "Password does not match hash for $username.";
                stdlog($log_details);
                unset($user_data);
                $user_data = 'fail';
            }
        } else {
            $log_details->message = "Cound not find username $username in DB.";
            stdlog($log_details);
            unset($user_data);
            $user_data = 'fail';
        }

        return $user_data;
    }
Beispiel #16
0
 public function add_nmap()
 {
     if (!isset($_POST['form_nmap'])) {
         $this->load->view('v_system_add_nmap', $this->data);
     } else {
         // check if the submitting IP is in the list of allowable subnets
         if (!$this->m_oa_config->check_blessed($_SERVER['REMOTE_ADDR'], '')) {
             exit;
         }
         $log_details = new stdClass();
         $log_details->severity = 7;
         $log_details->file = 'system';
         $log_details->message = 'Start processing nmap submitted data';
         stdlog($log_details);
         $log_details->message = 'ATTENTION - audit_subnet script being used. This is deprecated. Please use discovery scripts instead.';
         $log_details->severity = 5;
         stdlog($log_details);
         unset($log_details);
         $this->load->helper('url');
         $this->load->helper('xml');
         $this->load->helper('network');
         $this->load->library('encrypt');
         if (extension_loaded('snmp')) {
             $this->load->helper('snmp');
             $this->load->helper('snmp_oid');
         }
         $this->load->model('m_system');
         $this->load->model('m_oa_group');
         $this->load->model('m_audit_log');
         $timestamp = $this->config->config['timestamp'];
         $xml_input = $_POST['form_nmap'];
         try {
             $xml_post = new SimpleXMLElement($xml_input);
         } catch (Exception $error) {
             // not a valid XML string
             $log_details = new stdClass();
             $log_details->severity = 5;
             $log_details->file = 'system';
             $log_details->message = 'Invalid XML input for NMap import';
             stdlog($log_details);
             unset($log_details);
             exit;
         }
         $count = 0;
         foreach ($xml_post->children() as $details) {
             $details = (object) $details;
             if (isset($this->session->userdata['user_id']) and is_numeric($this->session->userdata['user_id'])) {
                 echo 'Device IP: ' . $details->ip . "\n";
             }
             $count++;
             $details->last_seen = $timestamp;
             $details->last_user = '';
             $details->hostname = '';
             if ($this->config->item('discovery_use_dns') == 'y') {
                 $details = dns_validate($details);
             }
             $details->audits_ip = ip_address_to_db($_SERVER['REMOTE_ADDR']);
             $log_details = new stdClass();
             $log_details->severity = 7;
             $log_details->file = 'system';
             $log_details->message = 'Processing nmap audit result for ' . $details->ip . ' (' . $details->hostname . ')';
             stdlog($log_details);
             unset($log_details);
             if (!isset($details->type) or $details->type === '') {
                 $details->type = 'unknown';
             }
             if (extension_loaded('snmp')) {
                 // try to get more information using SNMP
                 if (!isset($details->access_details)) {
                     $details->access_details = $this->m_system->get_access_details($details->id);
                 }
                 $decoded_access = $this->encrypt->decode($details->access_details);
                 $decoded_access = json_decode($decoded_access);
                 $details->snmp_community = @$decoded_access->snmp_community;
                 $details->snmp_version = @$decoded_access->snmp_version;
                 $details->snmp_port = @$decoded_access->snmp_port;
                 $temp_array = get_snmp($details);
                 $details = $temp_array['details'];
                 $network_interfaces = $temp_array['interfaces'];
                 $ip = $temp_array['ip'];
             }
             $details->id = '';
             $details->id = $this->m_system->find_system($details);
             if (isset($details->snmp_oid) and $details->snmp_oid > '') {
                 // we received a result from SNMP, use this data to update OR insert
                 $details->last_seen_by = 'snmp';
                 $details->audits_ip = '127.0.0.1';
                 if ($this->config->item('discovery_use_dns') == 'y') {
                     $details = dns_validate($details);
                 }
                 if (isset($details->id) and !empty($details->id)) {
                     // we have a system.id and snmp details to update
                     $log_details = new stdClass();
                     $log_details->severity = 7;
                     $log_details->file = 'system';
                     $log_details->message = 'SNMP update for ' . $details->ip . ' (system id ' . $details->id . ')';
                     stdlog($log_details);
                     unset($log_details);
                     $this->m_system->update_system($details);
                 } else {
                     // we have a new system
                     $details->id = $this->m_system->insert_system($details);
                     $log_details = new stdClass();
                     $log_details->severity = 7;
                     $log_details->message = 'SNMP insert for ' . $details->ip . ' (system id ' . $details->id . ')';
                     stdlog($log_details);
                     unset($log_details);
                 }
                 # update any network interfaces and ip addresses retrieved by SNMP
                 if (isset($network_interfaces) and is_array($network_interfaces) and count($network_interfaces) > 0) {
                     $input = new stdClass();
                     $input->item = array();
                     $input->item = $network_interfaces;
                     $this->m_devices_components->process_component('network', $details, $input);
                 }
                 if (isset($ip->item) and count($ip->item) > 0) {
                     $this->m_devices_components->process_component('ip', $details, $ip);
                 }
             } else {
                 // we received a result from nmap only, use this data to update OR insert
                 $details->last_seen_by = 'nmap';
                 if (isset($details->id) and $details->id !== '') {
                     // we have a system id and nmap details to update
                     $log_details = new stdClass();
                     $log_details->severity = 7;
                     $log_details->message = 'Nmap update for ' . $details->ip . ' (system id ' . $details->id . ')';
                     stdlog($log_details);
                     unset($log_details);
                     $this->m_system->update_system($details);
                 } else {
                     // we have a new system
                     $details->id = $this->m_system->insert_system($details);
                     $log_details = new stdClass();
                     $log_details->severity = 7;
                     $log_details->message = 'Nmap insert for ' . $details->ip . ' (system id ' . $details->id . ')';
                     stdlog($log_details);
                     unset($log_details);
                 }
             }
             if (isset($this->user->full_name)) {
                 $temp_user = $this->user->full_name;
             } else {
                 $temp_user = '';
             }
             $this->m_audit_log->create($details->id, $temp_user, $details->last_seen_by, $details->audits_ip, '', '', $details->last_seen);
             unset($temp_user);
             $this->m_oa_group->update_system_groups($details);
         }
         if (isset($this->session->userdata['user_id']) and is_numeric($this->session->userdata['user_id'])) {
             echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">";
             echo "<head>\n<title>Open-AudIT</title>\n</head>\n<body>\n<pre>\n";
             echo $count . ' systems processed.<br />';
             echo "<a href='" . base_url() . "index.php/system/add_nmap'>Back to input page</a><br />\n";
             echo "<a href='" . base_url() . "index.php'>Front Page</a><br />\n";
             echo "<pre>\n";
             print_r($details);
             echo "</pre>\n";
         }
     }
 }
Beispiel #17
0
    public function update()
    {
        $log = new stdClass();
        $log->severity = 7;
        $log->file = 'system';
        $CI = & get_instance();

        $sql = 'UPDATE `scripts` SET ';
        $data = array();
        $log->message = json_encode($CI->response->meta->received_data);
        stdlog($log);
        if ( !empty($CI->response->meta->received_data->attributes->options)) {
            $received_options = new stdClass();
            foreach ($CI->response->meta->received_data->attributes->options as $key => $value) {
                    $received_options->$key = $value;
            }
            $select = "SELECT * FROM scripts WHERE id = ?";
            $existing_options = $this->run_sql($select, array($CI->response->meta->id));
            $existing_options = json_decode($existing_options[0]->options);
            $new_options = new stdClass();
            foreach ($existing_options as $existing_key => $existing_value) {
                if (!empty($received_options->$existing_key)) {
                    $new_options->$existing_key = $received_options->$existing_key;
                } else {
                    $new_options->$existing_key = $existing_options->$existing_key;
                }
            }
            $sql .= "`options` = ?, ";
            $data[] = (string)json_encode($new_options);
        }
        
        if (!empty($CI->response->meta->received_data->attributes->name)) {
            $sql .= "`name` = ?, ";
            $data[] = $CI->response->meta->received_data->attributes->name;
        }

        if (!empty($CI->response->meta->received_data->attributes->description)) {
            $sql .= "`description` = ?, ";
            $data[] = $CI->response->meta->received_data->attributes->description;
        }

        if ($sql == 'UPDATE `scripts` SET ') {
            # TODO - THROW AN ERROR, no credentials or name or description supplied for updating
        }
        $sql .= " `edited_by` = ?, `edited_date` = NOW() WHERE id = ?";
        $data[] = (string)$CI->user->full_name;
        $data[] = intval($CI->response->meta->id);
        $this->run_sql($sql, $data);
        return;
    }
Beispiel #18
0
 public function system_tags($id = 0)
 {
     // log the attempt
     $log_details = new stdClass();
     $log_details->severity = 7;
     stdlog($log_details);
     unset($log_details);
     $this->load->model("m_system");
     if ($this->m_system->get_system_access_level($this->data['system_id'], $this->user->id) < '1') {
         // not even VIEW permission - output "Not Authorised"
         echo "<div class=\"TagPopupResult\">\n";
         echo "<table border=\"0\" style=\"font-size: 8pt; color:#3D3D3D; font-family: 'Verdana','Lucida Sans Unicode','Lucida Sans',sans-serif;\">\n";
         echo "<tr>\n";
         echo "  <td>Not Authorised. {$auth}</td>\n";
         echo "</tr>\n";
         echo "</table>\n";
         echo "</div>";
     } else {
         // authorised - now get the data
         $query = $this->m_system->get_system_groups($this->data['system_id'], $this->user->id);
         echo "<div class=\"TagPopupResult\">\n";
         echo "<table border=\"0\" style=\"font-size: 8pt; color:#3D3D3D; font-family: 'Verdana','Lucida Sans Unicode','Lucida Sans',sans-serif;\">\n";
         foreach ($query as $group) {
             echo "<tr>\n";
             echo "  <td><a href=\"" . site_url() . "/main/list_devices/" . intval($group->group_id) . "\">" . htmlentities($group->group_name) . "</a></td>\n";
             echo "</tr>\n";
         }
         echo "</table>\n";
         echo "</div>";
     }
 }
Beispiel #19
0
    /**
     * The SSH connection attempt using specific, supplied and default credentials
     *
     * @access    public
     *
     * @category  Function
     *
     * @author    Mark Unwin <*****@*****.**>
     *
     * @param     ip
     *
     * @param     credentials
     *
     * @param     source
     *
     * @param     destination
     *
     * @param     display
     *
     * @return    TRUE || FALSE [depending on if the file could be copied]
     */
    function scp($ip = '', $credentials, $source = '', $destination = '', $display = 'n')
    {
        if (strtolower($display) != 'y') {
            $display = 'n';
        } else {
            $display = 'y';
        }

        $log = new stdClass();
        $log->severity = 7;
        $log->file = 'system';
        $log->display = $display;

        if (empty($ip)) {
            $log->message = 'No IP supplied to ssh_helper::scp function.';
            stdlog($log);
            return false;
        }

        if (!filter_var($ip, FILTER_VALIDATE_IP)) {
            $log->message = 'No valid IP supplied to ssh_helper::scp function.';
            stdlog($log);
            return false;
        }
        if (!is_object($credentials)) {
            $log->message = 'No credentials supplied to ssh_helper::scp function.';
            stdlog($log);
            return false;
        } else {
            if ($credentials->type == 'ssh') {
                $username = $credentials->credentials->username;
                $password = $credentials->credentials->password;
            } elseif ($credentials->type == 'ssh_key') {
                $username = $credentials->credentials->username;
                $keyfile = ssh_create_keyfile($credentials->credentials->ssh_key);
            }
        }

        if (empty($source)) {
            $log->message = 'No source supplied to ssh_helper::scp function.';
            stdlog($log);
            return false;
        }

        if (empty($destination)) {
            $log->message = 'No destination supplied to ssh_helper::scp function.';
            stdlog($log);
            return false;
        }

        $return = array('output' => '', 'status' => '');

        if (php_uname('s') == 'Linux') {
            if ($credentials->type == 'ssh') {
                $descriptorspec = array(
                    0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
                    1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
                    2 => array("file", "/dev/null", "a"), // stderr is a file to write to
                );
                $cwd = '/tmp';
                $env = array();
                $command = 'timeout 5m sshpass scp -oStrictHostKeyChecking=no -oConnectTimeout=10 -oUserKnownHostsFile=/dev/null ' . $source . ' ' . escapeshellarg($username) . '@' . escapeshellarg($ip) . ':' . $destination;
                $echo = $command;
                $process = proc_open($command, $descriptorspec, $pipes, $cwd, $env);
                if (is_resource($process)) {
                    fwrite($pipes[0], $password);
                    fclose($pipes[0]);
                    // stdOut
                    $temp = stream_get_contents($pipes[1]);
                    $return['output'] = explode("\n", $temp);
                    if (end($return['output']) == '') {
                        unset($return['output'][count($return['output'])-1]);
                    }
                    fclose($pipes[1]);
                    $return['status'] = proc_close($process);
                }
            } elseif ($credentials->type == 'ssh_key') {
                $command = 'scp -oStrictHostKeyChecking=no -oConnectTimeout=10 -oUserKnownHostsFile=/dev/null -i ' . $keyfile . ' ' . $source . ' ' . escapeshellarg($username) . '@' . escapeshellarg($ip) . ':' . $destination;
                $echo = $command;
                exec($command, $return['output'], $return['status']);
                unlink($keyfile);
            }
        }

        if (php_uname('s') == 'Darwin') {
            if ($credentials->type == 'ssh') {
                $descriptorspec = array(
                    0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
                    1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
                    2 => array("file", "/dev/null", "a"), // stderr is a file to write to
                );
                $cwd = '/tmp';
                $env = array();
                $command = 'sshpass scp -oStrictHostKeyChecking=no -oConnectTimeout=10 -oUserKnownHostsFile=/dev/null ' . $source . ' ' . escapeshellarg($username) . '@' . $ip . ':' . $destination;
                $echo = $command;
                $process = proc_open($command, $descriptorspec, $pipes, $cwd, $env);
                if (is_resource($process)) {
                    fwrite($pipes[0], $password);
                    fclose($pipes[0]);
                    // stdOut
                    $temp = stream_get_contents($pipes[1]);
                    $return['output'] = explode("\n", $temp);
                    if (end($return['output']) == '') {
                        unset($return['output'][count($return['output'])-1]);
                    }
                    fclose($pipes[1]);
                    $return['status'] = proc_close($process);
                }
            } elseif ($credentials->type == 'ssh_key') {
                $command = 'scp -oStrictHostKeyChecking=no -oConnectTimeout=10 -oUserKnownHostsFile=/dev/null -i ' . $keyfile . ' ' . $source . ' ' . escapeshellarg($username) . '@' . escapeshellarg($ip) . ':' . $destination;
                $echo = $command;
                exec($command, $return['output'], $return['status']);
                unlink($keyfile);
            }
        }

        if (php_uname('s') == 'Windows NT') {
            $filepath = dirname(dirname(dirname(dirname(dirname(__FILE__)))))."\open-audit\other";
            if ($credentials->type == 'ssh') {
                $password = str_replace('"', '\"', $password);
                $command = $filepath . '\pscp.exe -pw "' . $password . '" ' . $source . ' ' . $user . '@' . $host . ':' . $destination;
                $echo = str_replace($password, '******', $command);
                exec($command, $return['output'], $return['status']);
            } elseif ($credentials->type == 'ssh_key') {
                $command = $filepath . '\pscp.exe -i "' . $keyfile . '" ' . $source . ' ' . $user . '@' . $host . ':' . $destination;
                $echo = $command;
                exec($command, $return['output'], $return['status']);
            }
        }

        if ($display == 'y') {
            echo 'DEBUG - Command Executed: '.$echo."\n";
            echo 'DEBUG - Return Value: '.$return['status']."\n";
            echo "DEBUG - Command Output:\n";
            $formatted_output = implode("\n", $return['output']);
            $formatted_output = htmlentities($formatted_output);
            $formatted_output = explode("\n", $formatted_output);
            if (end($formatted_output) == '') {
                unset($formatted_output[count($formatted_output)-1]);
            }
            print_r($formatted_output);
            echo "\nDEBUG ---------------\n";
        }

        if ($return['status'] != '0') {
            $log->message = 'SCP copy \'' . $source . '\' to ' . $ip . ' failed';
            stdlog($log);
            return false;
        } else {
            $log->message = 'SCP copy \'' . $source . '\' to ' . $ip . ' succeeded';
            stdlog($log);
            return true;
        }
    }
    public function process_component($table = '', $details, $input, $display = 'n', $match_columns = array())
    {
        $create_alerts = $this->m_oa_config->get_config_item('discovery_create_alerts');
        $delete_noncurrent = @$this->m_oa_config->get_config_item('delete_noncurrent');

        $log_details = new stdClass();
        $log_details->message = '';
        $log_details->severity = 7;
        $log_details->file = 'system';
        if ($display != 'y') {
            $display = 'n';
        }
        $log_details->display = $display;
        unset($display);

        if (empty($details->name) and !empty($details->hostname)) {
            $name = $details->hostname;
        } else {
            $name = $details->name;
        }

        // ensure we have a valid table name
        if (!$this->db->table_exists($table)) {
            $log_details->message = 'Table supplied does not exist (' . $table . ') for '.@ip_address_from_db($details->ip).' ('.$name.')';
            $log_details->severity = 5;
            stdlog($log_details);
            return;
        }

        if (!$input) {
            $log_details->message = 'No input supplied (' . $table . ') for '.@ip_address_from_db($details->ip).' ('.$name.')';
            $log_details->severity = 5;
            stdlog($log_details);
            return;
        }

        if (!isset($match_columns) or count($match_columns) == 0) {
            $match_columns = $this->match_columns($table);
        }

        if ($table == '' or count($match_columns) == 0 or !isset($details->id)) {
            if ($table == '') {
                $log_details->message = 'No table supplied for '.@ip_address_from_db($details->ip).' ('.$name.')';
                $message = "No table name supplied - failed";
            }
            if (count($match_columns) == 0) {
                $log_details->message = 'No columns to match supplied for '.@ip_address_from_db($details->ip).' ('.$name.')';
                $message = "$table - No columns to match supplied - failed";
            }
            # if (!isset($details->id)) { # this will be changed when we convert the system table
            if (!isset($details->id)) {
                $log_details->message = 'No id supplied for '.@ip_address_from_db($details->ip).' ('.$name.')';
                $message = "$table - No id supplied - failed";
            }
            $this->m_audit_log->update('debug', $message, $details->id, $details->last_seen);
            unset($message);
            $log_details->severity = 5;
            stdlog($log_details);
            return;
        } else {
            $this->m_audit_log->update('debug', "$table - start", $details->id, $details->last_seen);
            $log_details->message = 'Processing component (' . $table . ') start for '.@ip_address_from_db($details->ip).' ('.$name.')';
            $log_details->severity = 7;
            stdlog($log_details);
        }

        // make sure we have an entry for each match column, even if it's empty
        foreach ($match_columns as $match_column) {
            for ($i=0; $i<count($input->item); $i++) {
                if (isset($input->item[$i]) and !isset($input->item[$i]->$match_column)) {
                    $input->item[$i]->$match_column = '';
                }
            }
        }

        ### IP ADDRESS ###
        if ((string)$table == 'ip') {
            for ($i=0; $i<count($input->item); $i++) {
                # some devices may provide upper case MAC addresses - ensure all stored in the DB are lower
                $input->item[$i]->mac = strtolower($input->item[$i]->mac);
                # As at 1.5.6 we pass an additional attribute called 'type' for bonded adapters
                # We use this to test and not pad the MAC address if set
                if (!isset($input->item[$i]->type)) {
                    $input->item[$i]->type = '';
                }
                # calculate the network this address is on (assuming we have an ip AND subnet)
                if (isset($input->item[$i]->ip) and $input->item[$i]->ip != '' and isset($input->item[$i]->netmask) and $input->item[$i]->netmask != '' and $input->item[$i]->netmask != '0.0.0.0') {
                    $temp_long = ip2long($input->item[$i]->netmask);
                    $temp_base = ip2long('255.255.255.255');
                    $temp_subnet = 32-log(($temp_long ^ $temp_base)+1,2);
                    $net = network_details($input->item[$i]->ip.'/'.$temp_subnet);
                    if (isset($net->network) and $net->network != '') {
                        #$input->item[$i]->network = $net->network.' / '.$temp_subnet;
                        $input->item[$i]->network = $net->network.'/'.$temp_subnet;
                    } else {
                        $input->item[$i]->network = '';
                    }
                    if (isset($net->network_slash) and $net->network_slash != '') {
                        $input->item[$i]->cidr = $net->network_slash;
                    } else {
                        $input->item[$i]->cidr = '';
                    }
                    unset($temp_long);
                    unset($temp_base);
                    unset($temp_subnet);
                    unset($net);
                }
                if ($input->item[$i]->type != 'bonded') {
                    if (isset($input->item[$i]->mac) and $input->item[$i]->mac != '') {
                        $mymac = explode(":", $input->item[$i]->mac);
                        for ($j = 0; $j<count($mymac); $j++) {
                            $mymac[$j] = mb_substr("00".$mymac[$j], -2);
                        }
                        if (count($mymac) > 0) {
                            $input->item[$i]->mac = implode(":", $mymac);
                        }
                    }
                }
                if (!isset($input->item[$i]->version) or $input->item[$i]->version != '6') {
                    $input->item[$i]->version = 4;
                }
                # ensure we have the correctly padded ip v4 address
                if ($input->item[$i]->version == 4) {
                    $input->item[$i]->ip = ip_address_to_db($input->item[$i]->ip);
                }
                if (!isset($input->item[$i]->ip) or $input->item[$i]->ip == '') {
                    unset($input->item[$i]);
                }
                # ensure we add the network to the networks list
                if (!empty($input->item[$i]->network)) {
                    $this->m_oa_config->update_blessed($input->item[$i]->network);
                }
            }
            if ($details->type == 'computer' and $details->os_group == 'VMware') {
                # TODO - fix the below somewhow ?!??
                # the issue is that ESXi provides different values for network cards from the command line and from SNMP
                $sql = "DELETE FROM `ip` WHERE `ip`.`system_id` = ?";
                $sql = $this->clean_sql($sql);
                $data = array($details->id);
                $query = $this->db->query($sql, $data);
                # set the below so we don't generate alerts for this
                $create_alerts = 'n';
            }
        }

        ### NETSTAT ###
        if ((string)$table == 'netstat') {
            $input = $this->format_netstat_data($input, $details);
        }

        ### NETWORK ###
        # depending on the device type we need to alter our matching columns for the network card
        if ((string)$table == 'network') {
            if ($details->type == 'computer' and $details->os_group != 'VMware') {
                # we already match only on MAC Address
            } elseif ($details->type == 'computer' and $details->os_group == 'VMware') {
                # add index and connection id to the list to be matched
                $match_columns[] = 'net_index';
                $match_columns[] = 'connection';
                # TODO - fix the below somewhow ?!??
                # the issue is that ESXi provides different values for network cards from the command line and from SNMP
                $sql = "DELETE FROM `network` WHERE `network`.`system_id` = ?";
                $sql = $this->clean_sql($sql);
                $data = array($details->id);
                $query = $this->db->query($sql, $data);
                # set the below so we don't generate alerts for this
                $create_alerts = 'n';
            } else {
                # just match the index
                $match_columns[] = 'net_index';
            }

            # some devices may provide upper case MAC addresses - ensure all stored in the DB are lower
            for ($i=0; $i<count($input->item); $i++) {
                if (isset($input->item[$i]->mac)) {
                    $input->item[$i]->mac = strtolower($input->item[$i]->mac);
                } else {
                    $input->item[$i]->mac = '';
                }
            }
        }

        ### PARTITION ###
        # AIX needs to also match on partition.name
        if ((string)$table == 'partition' and strtolower($details->os_family) == 'ibm aix') {
            $match_columns[] = 'name';
        }

        ### PROCESSOR ###
        if ((string)$table == 'processor') {
            $input->item[0]->description = str_ireplace('(R)', '', $input->item[0]->description);
            $input->item[0]->description = str_ireplace('(TM)', '', $input->item[0]->description);
            $input->item[0]->description = str_ireplace('  ', ' ', $input->item[0]->description);
            $input->item[0]->manufacturer = str_ireplace('AuthenticAMD', 'AMD', $input->item[0]->manufacturer);
            $input->item[0]->manufacturer = str_ireplace('GenuineIntel', 'Intel', $input->item[0]->manufacturer);
        }

        ### SERVER ###
        if ((string)$table == 'server') {
            for ($i=0; $i<count($input->item); $i++) {
                if (isset($input->item[$i]->version) and $input->item[$i]->version != '' and $input->item[$i]->type == 'database') {
                    $input->item[$i]->full_name = (string)$this->get_sql_server_version_string($input->item[$i]->version);
                }
            }
        }

        ### SOFTWARE ###
        # need to pad the version
        if ((string)$table == 'software') {
            for ($i=0; $i<count($input->item); $i++) {
                if (isset($input->item[$i]->version) and $input->item[$i]->version != '') {
                    $pieces = array();
                    $pieces = preg_split("/[\s,\+\-\_\.\\\+\~]+/", $input->item[$i]->version);
                    $input->item[$i]->version_padded = (string)'';
                    foreach ($pieces as $piece) {
                        if (strlen($piece) > 10 ) {
                            $input->item[$i]->version_padded .= $piece;
                        } else {
                            $input->item[$i]->version_padded .= mb_substr("00000000000000000000".$piece, -10);
                        }
                    }
                } else {
                    $input->item[$i]->version_padded = '';
                }
            }
        }

        ### VIRTUAL MACHINE ###
        if ((string)$table == 'vm') {
            foreach ($input->item as $vm) {
                if (!isset($vm->group)) {
                    $vm->group = '';
                }
                if (!isset($vm->guest_system_id)) {
                    $vm->guest_system_id = '';
                }
                if (!isset($vm->icon)) {
                    $vm->icon = '';
                }
                if (!isset($vm->uuid) or $vm->uuid == '') {
                    $vm->uuid = '';
                } else {
                    $sql = "SELECT `system`.`id`, `system`.`icon` FROM `system` WHERE LOWER(`uuid`) = LOWER(?) and `system`.`status` = 'production'";
                    $sql = $this->clean_sql($sql);
                    $data = array("$vm->uuid");
                    $query = $this->db->query($sql, $data);
                    if ($query->num_rows() > 0) {
                        $row = $query->row();
                        $vm->guest_system_id = $row->system_id;
                        $vm->icon = $row->icon;
                        $sql = "UPDATE `system` SET `system`.`vm_server_name` = ?, `system`.`vm_system_id` = ? WHERE `system`.`id` = ?";
                        $sql = $this->clean_sql($sql);
                        $data = array("$details->name", "$details->id", $vm->guest_system_id);
                        $query = $this->db->query($sql, $data);
                    }
                }
            }
        }

        # make sure we have a populated org_id for adding items to the charts table
        if (empty($details->org_id)) {
            $sql = "SELECT `system`.`org_id` FROM `system` WHERE `system`.`id` = ?";
            $sql = $this->clean_sql($sql);
            $data = array($details->id);
            $query = $this->db->query($sql, $data);
            $row = $query->row();
            $details->org_id = $row->org_id;
        }

        // get any existing current rows from the database
        $sql = "SELECT *, '' AS updated FROM `$table` WHERE current = 'y' AND `$table`.`system_id` = ?";
        $sql = $this->clean_sql($sql);
        #$data = array($details->id); # this will be changed when we convert the system table
        $data = array($details->id);
        $query = $this->db->query($sql, $data);
        $db_result = $query->result();
        $alert = false;
        if (count($db_result) != 0) {
            // we have existing items in the database
            // we should raise an alert where required
            $alert = true;
        }

        // get the field list from the table
        $fields = $this->db->list_fields($table);

        // ensure we have a filtered array with only single copies of each $item
        $items = array();
        // for every input item
        foreach ($input->item as $input_key => $input_item) {
            $matched = 'n';
            // loop through the building up item array
            foreach ($items as $output_key => $output_item) {
                // the matched count is the number of columns in the match_columns array
                // that have equal values in our input items
                $match_count = 0;
                // loop through our match_columns array
                for ($i = 0; $i < count($match_columns); $i++) {
                    // and test if the variables match
                    if ((string)$input_item->$match_columns[$i] == (string)$output_item->$match_columns[$i]) {
                        // they match so increment the count
                        $match_count ++;
                    }
                }
                if ($match_count == (count($match_columns))) {
                    // we have two matching items - combine them
                    foreach ($fields as $field) {
                        if ((!isset($output_item->$field) or $output_item->$field == '') and isset($input_item->$field) and $input_item->$field != '') {
                            $output_item->$field = (string) $input_item->$field;
                        }
                    }
                    $items[$output_key] = $output_item;
                    $matched = 'y';
                }
            }
            if ($matched != 'y') {
                // no match, add the input item to the item array
                $items[] = $input_item;
            }
        }

        // for each item from the audit
        foreach ($items as $input_item) {
            // set these flags on a per audit item basis
            $flag = 'insert';
            // compare the audit data against the rows from the DB
            foreach ($db_result as $key => $db_item) {
                // check for a match against the columns in $match_columns
                $match_count = 0;
                for ($i = 0; $i < count($match_columns); $i++) {
                    if ((string)$input_item->$match_columns[$i] == (string)$db_item->$match_columns[$i] and $db_item->updated != 'y') {
                        $match_count ++;
                    }
                }
                if ($match_count == (count($match_columns))) {
                    // UPDATE because all supplied columns match
                    $flag = 'update';
                    $sql = '';
                    // if we have an audit value, replace the DB value
                    foreach ($fields as $field) {
                        if (isset($input_item->$field) and $input_item->$field != '') {
                            $db_item->$field = (string) $input_item->$field;
                        }
                        $sql .= " `" . $table . "`.`" . $field . "` = ? , ";
                    }
                    // remove the trailing characters
                    $sql = substr($sql, 0, -2);
                    // set the last_seen column to the same as in $details (system table)
                    $db_item->last_seen = (string)$details->last_seen;
                    // update all values in the table
                    $sql = "UPDATE `$table` SET $sql WHERE `" . $table . "`.`id` = '" . $db_item->id . "'";
                    // make sure no data is in $data
                    unset ($data);
                    // populate $data with the values from the database, combined with those of the audit
                    // this is stored in $fields
                    $data = array();
                    foreach ($fields as $field) {
                        $data[] = (string)$db_item->$field;
                    }
                    $sql = $this->clean_sql($sql);
                    $query = $this->db->query($sql, $data);
                    // remove this item from the database array
                    // we will later update the remaining items with current = n
                    // don't deletre it yet as we need to account for multiple items that are the same
                    //    typically in the Windows software listing
                    // unset($db_result[$key]);
                    $db_item->updated = 'y';
                    // set the $id so we can link to this row from graph, etc tables
                    $id = $db_item->id;
                    // stop the loop
                    break;
                } else {
                    // no match - $flag = 'insert' stays unchanged
                }
            }
            // we have looped through the database items
            // INSERT because the $flag is set to insert
            if ($flag == 'insert') {
                # $input_item->system_id  = $details->id; # this will be changed when we convert the system table
                $input_item->system_id  = $details->id;
                $input_item->current  = 'y';
                $input_item->first_seen = (string)$details->last_seen;
                $input_item->last_seen  = (string)$details->last_seen;
                $data = array();
                $set_fields = '';
                $set_values = '';
                foreach ($input_item as $key => $value) {
                    foreach($fields as $field) {
                        if ($key == $field) {
                            $set_fields .= " `$key`, ";
                            $set_values .= " ?, ";
                            $data[] = "$value";
                        }
                    }
                }
                $set_fields = substr($set_fields, 0, -2);
                $set_values = substr($set_values, 0, -2);
                $sql = "INSERT INTO `$table` ( $set_fields ) VALUES ( $set_values ) ";
                $sql = $this->clean_sql($sql);
                $query = $this->db->query($sql, $data);
                $id = $this->db->insert_id();

                if ($alert and strtolower($create_alerts) == 'y') {
                    // We have existing items and this is a new item - raise an alert
                    $alert_details = '';
                    foreach ($match_columns as $key => $value) {
                        $alert_details .= $value . ' is ' . $input_item->$value . ', ';
                    }
                    $alert_details = substr($alert_details, 0, -2);
                    $alert_details = "Item added to $table - " . $alert_details;
                    if (!isset($details->last_seen) or $details->last_seen == '0000-00-00 00:00:00' or $details->last_seen =='') {
                        $sql = "SELECT last_seen FROM `system` WHERE id = ?";
                        $sql = $this->clean_sql($sql);
                        $data = array($details->id);
                        $query = $this->db->query($sql, $data);
                        $result = $query->result();
                        $details->last_seen = $result[0]->last_seen;
                    }
                    $sql = "INSERT INTO change_log (system_id, db_table, db_row, db_action, details, `timestamp`) VALUES (?, ?, ?, ?, ?, ?)";
                    $sql = $this->clean_sql($sql);
                    $data = array("$details->id", "$table", "$id", "create", "$alert_details", "$details->last_seen");
                    $query = $this->db->query($sql, $data);
                    # add a count to our chart table
                    $sql = "INSERT INTO chart (`when`, `what`, `org_id`, `count`) VALUES (DATE(NOW()), '" . $table . "_create', " . intval($details->org_id) . ", 1) ON DUPLICATE KEY UPDATE `count` = `count` + 1";
                    $sql = $this->clean_sql($sql);
                    $query = $this->db->query($sql);
                }
            }
            if ((string)$table == 'partition') {
                // insert an entry into the graph table
                $used_percent = @intval(($input_item->used / $input_item->size) * 100);
                $free_percent = @intval(100 - $used_percent);
                $sql = "INSERT INTO graph VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                $sql = $this->clean_sql($sql);
                $data = array(intval($details->id), "$table", intval($id), "$table", intval($used_percent),
                        intval($free_percent), intval($input_item->used), intval($input_item->free), intval($input_item->size), "$details->last_seen");
                $query = $this->db->query($sql, $data);
            }
        }

        // remove the duplicated DB_items
        foreach ($db_result as $key => $db_item) {
            if ($db_item->updated) {
                unset($db_result[$key]);
            }
        }

        // we have now inserted or updated all items in the audit set
        // we have also unset any items that were inserted (from the audit set above) from the db set
        // any remaining rows in the db set should have their current flag set to n as they were not found in the audit set
        if (count($db_result) > 0) {
            $log_details->message = 'Inserting change logs (' . $table . ') for '.@ip_address_from_db($details->ip).' ('.$name.')';
            $log_details->severity = 7;
            stdlog($log_details);
        }
        foreach ($db_result as $db_item) {
            if (strtolower($delete_noncurrent) == 'y') {
                $sql = "DELETE FROM `$table` WHERE `id` = ?";
                $sql = $this->clean_sql($sql);
                $data = array($db_item->id);
                $query = $this->db->query($sql, $data);

            } else {
                $sql = "UPDATE `$table` SET current = 'n' WHERE id = ?";
                $sql = $this->clean_sql($sql);
                $data = array($db_item->id);
                $query = $this->db->query($sql, $data);
                if (strtolower($create_alerts) == 'y') {
                    $alert_details = '';
                    foreach ($match_columns as $key => $value) {
                        $alert_details .= $value . ' is ' . $db_item->$value . ', ';
                    }
                    $alert_details = substr($alert_details, 0, -2);
                    $alert_details = "Item removed from $table - " . $alert_details;
                    if (!isset($details->last_seen) or $details->last_seen == '0000-00-00 00:00:00' or $details->last_seen =='') {
                        $sql = "SELECT last_seen FROM `system` WHERE id = ?";
                        $sql = $this->clean_sql($sql);
                        $data = array($details->id);
                        $query = $this->db->query($sql, $data);
                        $result = $query->result();
                        $details->last_seen = $result[0]->last_seen;
                    }
                    $sql = "INSERT INTO change_log (system_id, db_table, db_row, db_action, details, `timestamp`) VALUES (?, ?, ?, ?, ?, ?)";
                    $sql = $this->clean_sql($sql);
                    $data = array("$details->id", "$table", "$db_item->id", "delete", "$alert_details", "$details->last_seen");
                    $query = $this->db->query($sql, $data);
                    # add a count to our chart table
                    $sql = "INSERT INTO chart (`when`, `what`, `org_id`, `count`) VALUES (DATE(NOW()), '" . $table . "_delete', " . intval($details->org_id) . ", 1) ON DUPLICATE KEY UPDATE `count` = `count` + 1";
                    $sql = $this->clean_sql($sql);
                    $query = $this->db->query($sql);
                }
            }
        }
        // update the audit log
        $this->m_audit_log->update('debug', "$table - end", $details->id, $details->last_seen);
        $log_details->message = 'Processing component (' . $table . ') end for '.@ip_address_from_db($details->ip).' ('.$name.')';
        $log_details->severity = 7;
        stdlog($log_details);
        return;
    }
Beispiel #21
0
//   e.g. $resource_module_classes['memory'] = 'vmtResourceMemory';
$namespace_stage = array();
// array of vmtManagedObjects parsed from the object/namespace files
$composite_stage = array();
// array of vmtManagedObjects where "namespace" attributes and "object" attributes are merged
$substitution_stage = array();
// array of vmtManagedObjects where static substitution variables have been replaced
$resource_stage = array();
// array of vmtManagedObjects where vmtResource dynamic substitution variables have been replaced
// Parse command line arguments which will override any default values specified
// in the rulebook options file.
ParseCommandline();
ReadRulebookOptions();
LogCommandline();
// Discover and load into memory all code modules, by reading them from disk.
DiscoverAndLoadModules();
// Read the namespace-object files from disk instantiating the namespaces object and base objects,
// then merge the namespace and base objects together
ReadNamespaces();
MergeIntoCompositeObjects();
// Copy all composite-stage object to the resource-stage collection,
// and evaluate all vmtResource-derived objects in dependency order.
CopyToResourceStage();
EvaluateResourceObjects();
// Substitute variables with their values
ApplyStaticSubstitutions();
// Loop through all non-vmtResource objects, in dependency order, and validate
// using the keyword-specified rules.
ValidateRuleObjects();
stdlog("End");
exit;
Beispiel #22
0
 /**
  * The standard input function for Open-AudIT.
  *
  * @access    public
  *
  * @category  Function
  *
  * @author    Mark Unwin <*****@*****.**>
  *
  * @return NULL [creates and updates the $this->response object]
  */
 function inputRead()
 {
     // Our default values are below
     // resource is the controller name (devices, groups, et al)
     // id is the integer value (if any) following the controller name in the URL
     // sub_resource = blank
     // sub_resource_id = blank
     // action = read if id is set or list if id is not set (create, read, update, delete, list, execute, download)
     // sort = blank
     // current = y
     // groupby = blank
     // limit = 1000
     // offset = 0
     // format = json
     // properties = *
     // filter = blank
     // version = 1 if JSON requested (the original), 0 if not JSON requested (the latest available)
     // Can set individual items using parameters /devices/1 == /devices?id=1 ???
     // set up our logging object
     $log = new stdClass();
     $log->severity = 7;
     $log->file = 'system';
     $log->message = '';
     error_reporting(E_ALL);
     $CI =& get_instance();
     if (empty($CI->response)) {
         $CI->response = new stdClass();
     }
     # enable the $_GET global
     parse_str(substr(strrchr($_SERVER['REQUEST_URI'], "?"), 1), $_GET);
     # /collection/{id}/{sub_resource}
     # initialise our properties
     $CI->response->meta = new stdClass();
     $CI->response->meta->action = '';
     $CI->response->meta->baseurl = $CI->config->config['base_url'];
     $CI->response->meta->collection = '';
     $CI->response->meta->current = 'y';
     $CI->response->meta->debug = false;
     $CI->response->meta->filtered = '';
     $CI->response->meta->format = '';
     $CI->response->meta->groupby = '';
     $CI->response->meta->header = 'HTTP/1.1 200 OK';
     $CI->response->meta->id = NULL;
     $CI->response->meta->ids = 0;
     $CI->response->meta->include = '';
     $CI->response->meta->limit = '';
     $CI->response->meta->offset = 0;
     $CI->response->meta->properties = '';
     $CI->response->meta->query_string = '';
     $REQUEST_METHOD = strtoupper($CI->input->server('REQUEST_METHOD'));
     $CI->response->meta->request_method = $REQUEST_METHOD;
     $CI->response->meta->sort = '';
     $CI->response->meta->sub_resource = '';
     $CI->response->meta->sub_resource_id = 0;
     $CI->response->meta->total = 0;
     $CI->response->meta->version = 1;
     $CI->response->meta->filter = array();
     $CI->response->meta->internal = new stdClass();
     $CI->response->meta->received_data = array();
     $CI->response->links = array();
     $CI->response->included = array();
     $actions = ' bulk_update_form collection create create_form debug delete download import import_form read sub_resource_create sub_resource_create_form sub_resource_delete update update_form ';
     $action = '';
     $collections = ' charts connections credentials devices fields files locations networks nmis orgs scripts ';
     $collection = '';
     # Allow for URLs thus:
     # /api/{version}/
     # /v1/
     # /v2/
     # as well as /devices or
     # version={version} in the accept header
     # get the version
     if ($CI->uri->segments[1] == 'api' or $CI->uri->segments[1] == 'v1' or $CI->uri->segments[1] == 'v2') {
         if ($CI->uri->segments[1] == 'api') {
             $CI->response->meta->version = intval($CI->uri->segment(2));
             unset($CI->uri->segments[1]);
             unset($CI->uri->segments[2]);
             $log->message = 'Set version to ' . intval($CI->uri->segment(2)) . ', according to URI segment.';
             stdlog($log);
         } else {
             if ($CI->uri->segments[1] == 'v1') {
                 $CI->response->meta->version = 1;
                 $log->message = 'Set version to v1, according to URI segment.';
                 stdlog($log);
                 unset($CI->uri->segments[1]);
             } else {
                 if ($CI->uri->segments[1] == 'v2') {
                     $CI->response->meta->version = 2;
                     $log->message = 'Set version to v2, according to URI segment.';
                     stdlog($log);
                     unset($CI->uri->segments[1]);
                 }
             }
         }
         array_unshift($CI->uri->segments, '');
         $CI->uri->segments = array_values($CI->uri->segments);
     } else {
         if (strpos($_SERVER['HTTP_ACCEPT'], 'application/json;version=') !== false) {
             $CI->response->meta->version = intval(str_replace('application/json;version=', '', $_SERVER['HTTP_ACCEPT']));
             $log->message = 'Set version to ' . $CI->response->meta->version . ', according to headers.';
             stdlog($log);
         }
     }
     # get our collection - usually devices, groups, reports, etc
     $temp = $CI->uri->segment(1);
     if (isset($temp) and $temp != '' and stripos($collections, ' ' . $temp . ' ') !== false) {
         $CI->response->meta->collection = (string) $temp;
         $CI->response->meta->heading = ucfirst($CI->response->meta->collection);
         $log->message = 'Set collection to ' . $CI->response->meta->collection . ', according to URI.';
         stdlog($log);
     }
     unset($temp);
     # get debug
     if ($CI->input->get('debug')) {
         $CI->response->meta->debug = $CI->input->get('debug');
         $log->message = 'Set debug to ' . $CI->response->meta->debug . ', according to URI.';
         stdlog($log);
     }
     if ($CI->input->post('debug')) {
         $CI->response->meta->debug = $CI->input->post('debug');
         $log->message = 'Set debug to ' . $CI->response->meta->debug . ', according to POST.';
         stdlog($log);
     }
     if (strtolower($CI->response->meta->debug) == 'true') {
         $CI->response->meta->debug = true;
     } else {
         $CI->response->meta->debug = false;
     }
     # get the id of the collection item in question
     # if we have an integer
     if ($CI->uri->segment(2) != '' and is_numeric($CI->uri->segment(2))) {
         $CI->response->meta->id = intval($CI->uri->segment(2));
         $log->message = 'Set ID to ' . $CI->response->meta->id . ', according to URI.';
         stdlog($log);
     }
     # if we have a reserved word
     if ($CI->uri->segment(2) and stripos($actions, ' ' . $CI->uri->segment(2) . ' ') !== false) {
         $CI->response->meta->action = $CI->uri->segment(2);
         $action = $CI->uri->segment(2);
         $log->message = 'Set action to ' . $CI->response->meta->action . ', according to URI.';
         stdlog($log);
     }
     if ($CI->uri->segment(3) and stripos($actions, ' ' . $CI->uri->segment(3) . ' ') !== false) {
         $CI->response->meta->action = $CI->uri->segment(3);
         $action = $CI->uri->segment(3);
         $log->message = 'Set action to ' . $CI->response->meta->action . ', according to URI.';
         stdlog($log);
     }
     # if we have an item name (ie, not it's ID)
     if (is_null($CI->response->meta->id) and $CI->uri->segment(2) != '' and stripos($actions, ' ' . $CI->uri->segment(2) . ' ') === false) {
         $log->message = 'Searching for ID, using ' . $CI->uri->segment(2) . ' on the ' . $CI->response->meta->collection . ' collection.';
         stdlog($log);
         $sql = '';
         switch ($CI->response->meta->collection) {
             case 'devices':
                 $sql = "SELECT system.id AS id FROM system WHERE name LIKE ? ORDER BY system.id DESC LIMIT 1";
                 $table = 'system';
                 break;
             case 'groups':
                 $sql = "SELECT group_id AS id FROM oa_group WHERE group_name LIKE ? LIMIT 1";
                 $table = 'oa_group';
                 break;
             case 'orgs':
                 $sql = "SELECT id FROM oa_org WHERE name LIKE ? LIMIT 1";
                 $table = 'oa_org';
                 break;
             case 'users':
                 $sql = "SELECT id AS id FROM oa_user WHERE name LIKE ? LIMIT 1";
                 $table = 'oa_user';
                 break;
             case 'reports':
                 $sql = "SELECT report_id AS id FROM oa_report WHERE report_name LIKE ? LIMIT 1";
                 $table = 'oa_report';
                 break;
             case 'scripts':
                 $sql = "SELECT id AS id FROM scripts WHERE name LIKE ? LIMIT 1";
                 $table = 'scripts';
                 break;
             case 'charts':
                 $sql = '';
                 $CI->response->meta->id = 1;
                 $CI->response->meta->sub_resource = $CI->uri->segment(2);
                 break;
         }
         if ($sql != '') {
             $data = array($CI->uri->segment(2));
             $query = $CI->db->query($sql, $data);
             $result = $query->result();
             if (count($result) > 0) {
                 $CI->response->meta->id = intval($result[0]->id);
                 $log->message = 'Set id to ' . $CI->response->meta->id . ', after searching.';
                 stdlog($log);
             } else {
                 // should throw an error as we were given a name, but nothing matched
                 $CI->response->meta->id = 888888888888.0;
                 $log->message = 'Set id to NULL, after searching - no match found.';
                 stdlog($log);
             }
         }
     }
     # get the include
     if ($CI->input->get('include')) {
         $CI->response->meta->include = $CI->input->get('include');
         $log->message = 'Set include to ' . $CI->response->meta->include . ', according to GET.';
         stdlog($log);
     }
     if ($CI->input->post('include')) {
         $CI->response->meta->include = $CI->input->post('include');
         $log->message = 'Set include to ' . $CI->response->meta->include . ', according to POST.';
         stdlog($log);
     }
     # get the sub_resource
     if (empty($CI->response->meta->sub_resource)) {
         $temp = @(string) $CI->uri->segment(3, '');
         if (stripos($actions, ' ' . $temp . ' ') === false and $temp != '') {
             $CI->response->meta->sub_resource = $temp;
             $log->message = 'Set sub_resource to ' . $CI->response->meta->sub_resource . ', according to URI.';
             stdlog($log);
         }
     }
     if ($CI->input->get('sub_resource')) {
         $CI->response->meta->sub_resource = $CI->input->get('sub_resource');
         $log->message = 'Set sub_resource to ' . $CI->response->meta->sub_resource . ', according to GET.';
         stdlog($log);
     }
     if ($CI->input->post('sub_resource')) {
         $CI->response->meta->sub_resource = $CI->input->post('sub_resource');
         $log->message = 'Set sub_resource to ' . $CI->response->meta->sub_resource . ', according to POST.';
         stdlog($log);
     }
     $CI->response->meta->sub_resource = str_replace(array(',', '.', '\'', '"', '(', ')'), '', $CI->response->meta->sub_resource);
     # get the sub_resource id
     #$CI->response->meta->sub_resource_id = $CI->uri->segment(4, '');
     if (empty($CI->response->meta->sub_resource_id)) {
         if (!empty($CI->response->meta->sub_resource)) {
             $CI->response->meta->sub_resource_id = (string) $CI->uri->segment(4, '');
             $log->message = 'Set sub_resource_id to ' . $CI->response->meta->sub_resource_id . ', according to URI.';
             stdlog($log);
         }
     }
     if ($CI->input->get('sub_resource_id')) {
         $CI->response->meta->sub_resource_id = $CI->input->get('sub_resource_id');
         $log->message = 'Set sub_resource_id to ' . $CI->response->meta->sub_resource_id . ', according to GET.';
         stdlog($log);
     }
     if ($CI->input->post('sub_resource_id')) {
         $CI->response->meta->sub_resource_id = $CI->input->post('sub_resource_id');
         $log->message = 'Set sub_resource_id to ' . $CI->response->meta->sub_resource_id . ', according to POST.';
         stdlog($log);
     }
     $CI->response->meta->sub_resource_id = intval($CI->response->meta->sub_resource_id);
     # TODO - fit this somewhere nicer. Need to account for multiple id's being sent
     if (!empty($_GET['ids'])) {
         $CI->response->meta->ids = $_GET['ids'];
         unset($_GET['ids']);
     }
     # put any POST data into the object
     if ($REQUEST_METHOD == 'POST') {
         if (is_array($CI->input->post('data'))) {
             $CI->response->meta->received_data = $CI->input->post('data');
             $CI->response->meta->received_data = json_encode($CI->response->meta->received_data);
             $CI->response->meta->received_data = json_decode($CI->response->meta->received_data);
         } else {
             $CI->response->meta->received_data = json_decode($CI->input->post('data'));
         }
     }
     if ($REQUEST_METHOD == 'PATCH') {
         $data = json_decode(urldecode(str_replace('data=', '', file_get_contents('php://input'))));
         $CI->response->meta->received_data = $data->data;
         unset($data);
     }
     if (isset($CI->response->meta->received_data->id)) {
         $CI->response->meta->id = intval($CI->response->meta->received_data->id);
     }
     # get the action
     # valid values are typically - create, read, update, delete, list, execute
     # TODO - request_method == post and body contains system.id, then update, not create
     if ($CI->input->get('action')) {
         $action = $CI->input->get('action');
         $log->message = 'Set action to ' . $action . ', according to GET.';
         stdlog($log);
     }
     if ($CI->input->post('action')) {
         $action = $CI->input->post('action');
         $log->message = 'Set action to ' . $action . ', according to POST.';
         stdlog($log);
     }
     if ($REQUEST_METHOD == 'GET' and is_null($CI->response->meta->id) and $action == '') {
         // return a list of items
         $CI->response->meta->action = 'collection';
         $log->message = 'Set action to ' . $CI->response->meta->action . ', because GET, no id, no action.';
         stdlog($log);
     }
     if ($REQUEST_METHOD == 'GET' and is_null($CI->response->meta->id) and $action == 'create') {
         // show a HTML form for entering a new item
         $CI->response->meta->action = 'create_form';
         $log->message = 'Set action to ' . $CI->response->meta->action . ', because GET, no id and action = create.';
         stdlog($log);
     }
     if ($REQUEST_METHOD == 'GET' and $action == 'create' and $CI->response->meta->sub_resource != '') {
         // show a HTML form for entering a new item
         $CI->response->meta->action = 'sub_resource_create_form';
         $log->message = 'Set action to ' . $CI->response->meta->action . ', because GET, sub_resource and action = create.';
         stdlog($log);
     }
     if ($REQUEST_METHOD == 'GET' and is_null($CI->response->meta->id) and $action == 'import') {
         // show a HTML form for entering a new item
         $CI->response->meta->action = 'import_form';
         $log->message = 'Set action to ' . $CI->response->meta->action . ', because GET, no id and action = import.';
         stdlog($log);
     }
     if ($REQUEST_METHOD == 'GET' and !is_null($CI->response->meta->id) and $action == '') {
         // return a single item
         $CI->response->meta->action = 'read';
         $CI->response->meta->id = intval($CI->response->meta->id);
         $log->message = 'Set action to ' . $CI->response->meta->action . ', because GET, id and no action.';
         stdlog($log);
     }
     if ($REQUEST_METHOD == 'GET' and !is_null($CI->response->meta->id) and $action == 'update' and empty($CI->response->meta->ids)) {
         // show a HTML form for updating an existing item
         $CI->response->meta->action = 'update_form';
         $log->message = 'Set action to ' . $CI->response->meta->action . ', because GET, id and action = ' . $action . '.';
         stdlog($log);
     }
     if ($REQUEST_METHOD == 'GET' and is_null($CI->response->meta->id) and $action == 'update' and !empty($CI->response->meta->ids)) {
         // show a HTML form for entering a new item
         $CI->response->meta->action = 'bulk_update_form';
         $log->message = 'Set action to ' . $CI->response->meta->action . ', because GET, ids, no id and action = update.';
         stdlog($log);
     }
     if ($REQUEST_METHOD == 'GET' and !is_null($CI->response->meta->id) and $action == 'download') {
         // mainly used for running a report and displaying the output
         $CI->response->meta->action = 'download';
         $log->message = 'Set action to ' . $CI->response->meta->action . ', because GET, id and action = download.';
         stdlog($log);
     }
     if ($REQUEST_METHOD == 'POST' and is_null($CI->response->meta->id) and $action == '' and $CI->response->meta->received_data != '') {
         // insert an item
         $CI->response->meta->action = 'create';
         $CI->response->meta->header = 'HTTP/1.1 201 Created';
         $log->message = 'Set action to ' . $CI->response->meta->action . ', because POST, data, no id and no action.';
         stdlog($log);
     }
     if ($REQUEST_METHOD == 'POST' and is_null($CI->response->meta->id) and $action == '' and $CI->response->meta->received_data == '') {
         // insert an item
         $CI->response->meta->action = 'collection';
         $log->message = 'Set action to ' . $CI->response->meta->action . ', because POST, no id, no data and no action.';
         stdlog($log);
     }
     if ($REQUEST_METHOD == 'POST' and is_null($CI->response->meta->id) and $action == 'import') {
         // insert an item
         $CI->response->meta->action = 'import';
         $CI->response->meta->header = 'HTTP/1.1 201 Created';
         $log->message = 'Set action to ' . $CI->response->meta->action . ', because POST, no id and action = import.';
         stdlog($log);
     }
     if ($REQUEST_METHOD == 'POST' and is_null($CI->response->meta->id) and $action == 'update' and !empty($CI->response->meta->ids)) {
         $CI->response->meta->action = 'update';
         $log->message = 'Set action to ' . $CI->response->meta->action . ', because POST, ids, no id and action = update.';
         stdlog($log);
     }
     if (($REQUEST_METHOD == 'POST' or $REQUEST_METHOD == 'PUT' or $REQUEST_METHOD == 'PATCH') and !is_null($CI->response->meta->id) and $action == '') {
         // update an item
         $CI->response->meta->action = 'update';
         $CI->response->meta->header = 'HTTP/1.1 200 OK';
         $CI->response->meta->id = intval($CI->response->meta->id);
         $log->message = 'Set action to ' . $CI->response->meta->action . ', because POST/PATCH/PUT, id and no action.';
         stdlog($log);
     }
     if ($REQUEST_METHOD == 'PATCH' and !empty($CI->response->meta->ids)) {
         // update several items
         $CI->response->meta->action = 'update';
         $CI->response->meta->header = 'HTTP/1.1 200 OK';
         $CI->response->meta->id = intval($CI->response->meta->id);
         $log->message = 'Set action to ' . $CI->response->meta->action . ', because PATCH, ids and no id.';
         stdlog($log);
     }
     if ($REQUEST_METHOD == 'POST' and (!is_null($CI->response->meta->id) or $CI->response->meta->ids != '') and $CI->response->meta->sub_resource != '') {
         // show a HTML form for entering a new item
         $CI->response->meta->action = 'sub_resource_create';
         $log->message = 'Set action to ' . $CI->response->meta->action . ', because POST, id, sub_resource.';
         stdlog($log);
     }
     if ($REQUEST_METHOD == 'DELETE' and !is_null($CI->response->meta->id) and $CI->response->meta->sub_resource == '') {
         // delete an item
         $CI->response->meta->action = 'delete';
         $CI->response->meta->header = 'HTTP/1.1 200 OK';
         $CI->response->meta->id = intval($CI->response->meta->id);
         $log->message = 'Set action to ' . $CI->response->meta->action . ', because DELETE, id.';
         stdlog($log);
     }
     if ($REQUEST_METHOD == 'DELETE' and !is_null($CI->response->meta->id) and $CI->response->meta->sub_resource != '' and $CI->response->meta->sub_resource_id != '') {
         // delete an item
         $CI->response->meta->action = 'sub_resource_delete';
         $CI->response->meta->header = 'HTTP/1.1 200 OK';
         $CI->response->meta->id = intval($CI->response->meta->id);
         $log->message = 'Set action to ' . $CI->response->meta->action . ', because DELETE, id, sub_resource, sub_resource_id.';
         stdlog($log);
     }
     if ($CI->response->meta->action == '') {
         $CI->response->meta->action = 'collection';
         $log->message = 'Set action to ' . $CI->response->meta->action . ', no action.';
         stdlog($log);
     }
     if (stripos($actions, ' ' . $CI->response->meta->action . ' ') === false) {
         $CI->response->meta->action = 'collection';
         $log->message = 'Set action to ' . $CI->response->meta->action . ', because not in reserved words.';
         stdlog($log);
     }
     # get the sort
     $CI->response->meta->sort = $CI->input->get('sort');
     if ($CI->input->post('sort')) {
         $CI->response->meta->sort = $CI->input->post('sort');
         $log->message = 'Set sort to ' . $CI->response->meta->sort . ', according to POST.';
         stdlog($log);
     }
     $CI->response->meta->sort = str_replace('+', '', $CI->response->meta->sort);
     if ($CI->response->meta->sort != '') {
         $temp = explode(',', $CI->response->meta->sort);
         foreach ($temp as &$item) {
             if (substr($item, 0, 1) == '-') {
                 $item = substr($item, 1) . ' DESC';
             }
         }
         $CI->response->meta->sort = implode(',', $temp);
     }
     if ($CI->response->meta->sort != '') {
         $CI->response->meta->internal->sort = 'ORDER BY ' . implode(',', $temp);
     } else {
         $CI->response->meta->internal->sort = '';
     }
     # get current
     $CI->response->meta->current = $CI->input->get('current');
     if ($CI->input->post('current')) {
         $CI->response->meta->current = $CI->input->post('current');
         $log->message = 'Set current to ' . $CI->response->meta->current . ', according to POST.';
         stdlog($log);
     }
     $current_words = ' y n all delta ';
     if (stripos($current_words, ' ' . $CI->response->meta->current . ' ') === false) {
         $CI->response->meta->current = 'y';
         $log->message = 'Set current to ' . $CI->response->meta->current . ', because in reserved words.';
         stdlog($log);
     }
     unset($current_words);
     # get the group by
     if ($CI->input->get('groupby')) {
         $CI->response->meta->groupby = $_GET['groupby'];
         $log->message = 'Set groupby to ' . $CI->response->meta->groupby . ', according to GET.';
         stdlog($log);
     }
     if ($CI->input->post('groupby')) {
         $CI->response->meta->groupby = $_POST['groupby'];
         $log->message = 'Set groupby to ' . $CI->response->meta->groupby . ', according to POST.';
         stdlog($log);
     }
     if ($CI->response->meta->groupby) {
         $CI->response->meta->internal->groupby = 'GROUP BY ' . $CI->response->meta->groupby;
     } else {
         $CI->response->meta->internal->groupby = '';
     }
     # get the output format
     $CI->response->meta->format = '';
     if (strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false) {
         $CI->response->meta->format = 'json';
         $log->message = 'Set format to ' . $CI->response->meta->format . ', according to HEADERS.';
         stdlog($log);
     }
     if (strpos($_SERVER['HTTP_ACCEPT'], 'html') !== false) {
         $CI->response->meta->format = 'screen';
         $log->message = 'Set format to ' . $CI->response->meta->format . ', according to HEADERS.';
         stdlog($log);
     }
     if (isset($_GET['format'])) {
         $CI->response->meta->format = $_GET['format'];
         $log->message = 'Set format to ' . $CI->response->meta->format . ', according to GET.';
         stdlog($log);
     }
     if (isset($_POST['format'])) {
         $CI->response->meta->format = $_POST['format'];
         $log->message = 'Set format to ' . $CI->response->meta->format . ', according to POST.';
         stdlog($log);
     }
     if ($CI->response->meta->format == '') {
         $CI->response->meta->format = 'json';
         $log->message = 'Set format to ' . $CI->response->meta->format . ', because default.';
         stdlog($log);
     }
     $reserved_words = ' json json_data screen xml ';
     if (stripos($reserved_words, ' ' . $CI->response->meta->format . ' ') === false) {
         $CI->response->meta->format = 'json';
     }
     # get the limit
     if ($CI->response->meta->format == 'json') {
         $CI->response->meta->limit = '';
         $log->message = 'Set limit to ' . $CI->response->meta->limit . ', because json.';
         stdlog($log);
     } else {
         $CI->response->meta->limit = 1000;
         $log->message = 'Set limit to ' . $CI->response->meta->limit . ', because for non-json.';
         stdlog($log);
     }
     if (isset($_GET['limit'])) {
         $CI->response->meta->limit = intval($_GET['limit']);
         $log->message = 'Set limit to ' . $CI->response->meta->limit . ', according to GET.';
         stdlog($log);
     }
     if (isset($_POST['limit'])) {
         $CI->response->meta->limit = intval($_POST['limit']);
         $log->message = 'Set limit to ' . $CI->response->meta->limit . ', according to POST.';
         stdlog($log);
     }
     # get the offset
     if (isset($_GET['offset'])) {
         $CI->response->meta->offset = intval($_GET['offset']);
         $log->message = 'Set offset to ' . $CI->response->meta->offset . ', according to GET.';
         stdlog($log);
     }
     if (isset($_POST['offset'])) {
         $CI->response->meta->offset = intval($_POST['offset']);
         $log->message = 'Set offset to ' . $CI->response->meta->offset . ', according to POST.';
         stdlog($log);
     }
     if ($CI->response->meta->limit != '') {
         $CI->response->meta->internal->limit = 'LIMIT ' . $CI->response->meta->offset . ',' . $CI->response->meta->limit;
     } else {
         $CI->response->meta->internal->limit = '';
     }
     # get the list of requested properties (usually) properties=id,name,status
     if (isset($_GET['properties'])) {
         $CI->response->meta->properties = $_GET['properties'];
         $log->message = 'Set properties to ' . $CI->response->meta->properties . ', according to GET.';
         stdlog($log);
     }
     if (isset($_POST['properties'])) {
         $CI->response->meta->properties = $_POST['properties'];
         $log->message = 'Set properties to ' . $CI->response->meta->properties . ', according to POST.';
         stdlog($log);
     }
     # Allow for format of properties=["id", "name", "status"]
     if (json_decode($CI->response->meta->properties)) {
         $temp = json_decode($CI->response->meta->properties);
         unset($CI->response->meta->properties);
         $CI->response->meta->properties = '';
         foreach ($temp as $property) {
             $CI->response->meta->properties .= $property . ',';
         }
         $CI->response->meta->properties = substr($CI->response->meta->properties, 0, -1);
         $log->message = 'Set properties to ' . $CI->response->meta->properties . ', secondary format.';
         stdlog($log);
     }
     if ($CI->response->meta->properties == '') {
         # set some defaults
         if ($CI->response->meta->action == 'collection' and $CI->response->meta->collection == 'devices') {
             # we're requesting a list of devices without properties - set the below as defaults
             if ($CI->response->meta->sub_resource == '' or strtolower($CI->response->meta->sub_resource) == 'system') {
                 $CI->response->meta->properties = 'system.id, system.icon, system.type, system.name, system.domain, system.ip, system.description, system.os_family, system.status';
                 $log->message = 'Set properties to ' . $CI->response->meta->properties . ', because devices default.';
                 stdlog($log);
             } else {
                 # we're requesting a subresource - return all the subresource's properties
                 $CI->response->meta->properties = $CI->response->meta->sub_resource . '.*';
                 $log->message = 'Set properties to ' . $CI->response->meta->properties . ', because devices sub_resource default.';
                 stdlog($log);
             }
         } else {
             # we're requesting something that isn't a device (or a list of devices) - return everything
             $CI->response->meta->properties = '*';
             $log->message = 'Set properties to ' . $CI->response->meta->properties . ', because non-devices default.';
             stdlog($log);
         }
     }
     # perform some simple data cleansing
     $CI->response->meta->properties = str_replace(array('\'', '"', '(', ')'), '', $CI->response->meta->properties);
     $CI->response->meta->internal->properties = '';
     // create our internal properties list - this is what gets executed in SQL
     if ($CI->response->meta->properties != '*' and $CI->response->meta->properties != $CI->response->meta->sub_resource . '.*') {
         $temp = explode(',', $CI->response->meta->properties);
         foreach ($temp as $property) {
             if ($property == 'count') {
                 $CI->response->meta->internal->properties .= 'count(*) as `count`,';
             } elseif ($property == 'system_id') {
                 $CI->response->meta->internal->properties .= 'system.id as `system_id`,';
             } else {
                 $CI->response->meta->internal->properties .= $property . ' AS `' . trim($property) . '`,';
             }
         }
         $CI->response->meta->internal->properties = substr($CI->response->meta->internal->properties, 0, -1);
     } else {
         $CI->response->meta->internal->properties = $CI->response->meta->properties;
     }
     # get the filter
     $filter = array();
     $CI->response->meta->query_string = urldecode($_SERVER['QUERY_STRING']);
     if ($CI->response->meta->query_string != '') {
         $reserved_words = ' properties limit sub_resource sub_resource_id action sort current offset format debug groupby query include ids ';
         foreach (explode('&', urldecode($_SERVER['QUERY_STRING'])) as $item) {
             $query = new stdClass();
             $query->name = substr($item, 0, strpos($item, '='));
             $query->operator = '=';
             $query->value = str_replace($query->name . '=', '', $item);
             $operator = substr($query->value, 0, 1);
             if ($operator == '=' or $operator == '>' or $operator == '<') {
                 $query->value = substr($query->value, 1);
                 $query->operator = $operator;
             }
             $operator = substr($query->value, 0, 2);
             if ($operator == '!=' or $operator == '>=' or $operator == '<=') {
                 $query->value = substr($query->value, 2);
                 $query->operator = $operator;
             }
             $operator = substr($query->value, 0, 4);
             if (strtolower($operator) == 'like') {
                 $query->value = '%' . substr($query->value, 4) . '%';
                 $query->operator = $operator;
             }
             if (strtolower(substr($query->value, 0, 5)) == '!like') {
                 $query->value = '%' . substr($query->value, 5) . '%';
                 $query->operator = 'not like';
             }
             if (strtolower(substr($query->value, 0, 8)) == 'not like') {
                 $query->value = '%' . substr($query->value, 8) . '%';
                 $query->operator = 'not like';
             }
             $query->name = str_replace(array(',', '\'', '"', '(', ')'), '', $query->name);
             if ($query->value == false) {
                 $query->value = '';
             }
             if (strpos($reserved_words, ' ' . $query->name . ' ') === false and $query->name != '') {
                 $CI->response->meta->filter[] = $query;
             }
             unset($query);
         }
     }
     if ($query = json_decode($CI->input->get('query'))) {
         unset($CI->response->meta->filter);
         $CI->response->meta->filter = array();
         while (count($query) > 0) {
             $filter = new stdClass();
             $filter->name = array_shift($query);
             $operator = array_shift($query);
             if (stripos(' = != > >= < <= not like ', ' ' . $operator . ' ') !== false) {
                 $filter->operator = $operator;
                 if (stripos($filter->operator, 'like') !== false) {
                     $filter->value = '%' . array_shift($query) . '%';
                 } else {
                     $filter->value = array_shift($query);
                 }
             } else {
                 $filter->operator = '=';
                 $filter->value = $operator;
             }
             $CI->response->meta->filter[] = $filter;
             unset($filter);
         }
     }
     $CI->response->links = new stdClass();
     $CI->response->links->self = $CI->config->config['base_url'] . 'index.php/' . $CI->response->meta->collection;
     if (!is_null($CI->response->meta->id)) {
         $CI->response->links->self .= '/' . $CI->response->meta->id;
     }
     if ($CI->response->meta->sub_resource != '') {
         $CI->response->links->self .= '/' . $CI->response->meta->sub_resource;
     }
     if ($CI->response->meta->sub_resource_id != '') {
         $CI->response->links->self .= '/' . $CI->response->meta->sub_resource_id;
     }
     $CI->response->links->first = NULL;
     $CI->response->links->last = NULL;
     $CI->response->links->next = NULL;
     $CI->response->links->prev = NULL;
     $CI->response->errors = array();
     return;
 }
Beispiel #23
0
 public function log()
 {
     $this->load->helper('log');
     $log_details = new stdClass();
     $log_details->file = 'access';
     $log_details->severity = 5;
     stdlog($log_details);
 }
Beispiel #24
0
 public function upgrade()
 {
     error_reporting(E_ALL);
     $web_internal_version = $this->config->item('web_internal_version');
     $web_display_version = $this->config->item('web_display_version');
     $this->data['message'] = '';
     $db_internal_version = $this->config->item('internal_version');
     $this->data['output'] = "";
     if ($db_internal_version < '20111001' and $this->db->platform() == 'mysql') {
         # upgrade for beta3
         $this->db->trans_start();
         $this->data['output'] .= "Upgrading to beta3.<br />Transaction starting.<br /><br />\n";
         $sql = "ALTER TABLE sys_hw_hard_drive CHANGE hard_drive_status hard_drive_status varchar(100) NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_partition DROP FOREIGN KEY sys_hw_partition_hard_drive_index";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_man_audits ADD audit_debug text NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_service MODIFY service_path_name text NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_software ADD software_installed_by varchar(100) NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_software ADD software_installed_on datetime NOT NULL default '0000-00-00 00:00:00'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system ADD uptime varchar(50) NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system ADD pc_os_bit varchar(3) NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_config (config_name, config_value) VALUES ('internal_version', '20111001')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_config (config_name, config_value) VALUES ('display_version', 'beta3')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $this->db->trans_complete();
         if ($this->db->trans_status() === false) {
             $this->data['output'] .= "ALERT - error encountered. Transactions rolled back.<br /><br />\n";
         } else {
             $this->data['output'] .= "Transaction committed.<br />beta3 upgrade successful.<br /><br />\n";
         }
     }
     if ($db_internal_version < '20111010' and $this->db->platform() == 'mysql') {
         # upgrade for beta4
         $this->db->trans_start();
         $this->data['output'] .= "Upgrading to beta4.<br />Transaction starting.<br /><br />\n";
         $sql = "UPDATE oa_group SET group_dynamic_select = 'SELECT distinct(system.system_id) FROM system WHERE system.man_status = \\'production\\'' WHERE group_id = '1'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "CREATE TABLE sys_hw_warranty ( warranty_id int(10) unsigned NOT NULL auto_increment, system_id int(10) unsigned default NULL, warranty_provider varchar(200) NOT NULL default '', warranty_type varchar(100) NOT NULL default '', warranty_start datetime NOT NULL default '0000-00-00 00:00:00', warranty_end datetime NOT NULL default '0000-00-00 00:00:00', timestamp datetime NOT NULL default '0000-00-00 00:00:00', first_timestamp datetime NOT NULL default '0000-00-00 00:00:00', PRIMARY KEY  (warranty_id), KEY system_id (system_id), CONSTRAINT sys_hw_warranty_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_group_column VALUES  (NULL, '1', '1', 'Hostname',        'hostname',         'link',         'main/system_display/', 'system_id', '', 'left')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_group_column VALUES  (NULL, '1', '2', 'Description', 'man_description',  'text',         '',                     '', '', 'left')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_group_column VALUES  (NULL, '1', '3', 'IP Address',      'man_ip_address',   'ip_address',   '',                     '', '', 'left')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_group_column VALUES  (NULL, '1', '4', 'Type',            'man_icon',         'image',        '',                     'man_os_family', '', 'left')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_group_column VALUES  (NULL, '1', '5', 'OS / Device',     'man_os_name',      'text',         '',                     '', '', 'left')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_group_column VALUES  (NULL, '1', '6', 'Tags',            'tag',              'text',         '',                     '', '', 'left')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = '20111010' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = 'beta4' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $this->db->trans_complete();
         if ($this->db->trans_status() === false) {
             $this->data['output'] .= "ALERT - error encountered. Transactions rolled back.<br /><br />\n";
         } else {
             $this->data['output'] .= "Transaction committed.<br />beta4 upgrade successful.<br /><br />\n";
         }
     }
     if ($db_internal_version < '20120317' and $this->db->platform() == 'mysql') {
         # upgrade for beta5
         $this->db->trans_start();
         $this->data['output'] .= "Upgrading to beta5.<br />Transaction starting.<br /><br />\n";
         $sql = "ALTER TABLE sys_hw_monitor ADD size varchar(5) NOT NULL default '' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_monitor ADD aspect_ratio varchar(5) NOT NULL default '' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system ADD man_class enum ('desktop', 'laptop', 'tablet', 'workstation', 'server', 'virtual server', 'virtual desktop', '') NOT NULL default '' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system ADD last_seen DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system ADD last_seen_by VARCHAR(150) NOT NULL DEFAULT '' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system ADD last_user VARCHAR(150) NOT NULL DEFAULT '' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_alert_log DROP FOREIGN KEY oa_alert_log_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_alert_log DROP FOREIGN KEY oa_alert_log_user_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_alert_log DROP FOREIGN KEY oa_alert_oa_change";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_alert_log ADD CONSTRAINT oa_alert_log_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_alert_log ADD CONSTRAINT oa_alert_log_user_id FOREIGN KEY (user_id) REFERENCES oa_user (user_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_alert_log ADD CONSTRAINT oa_alert_oa_change FOREIGN KEY (change_id) REFERENCES oa_change (change_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_audit_log DROP FOREIGN KEY oa_audit_log_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_audit_log DROP FOREIGN KEY oa_audit_log_user_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_audit_log ADD CONSTRAINT oa_audit_log_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_audit_log ADD CONSTRAINT oa_audit_log_user_id FOREIGN KEY (user_id) REFERENCES oa_user (user_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_change DROP FOREIGN KEY oa_change_user_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_change ADD CONSTRAINT oa_change_user_id FOREIGN KEY (user_id) REFERENCES oa_user (user_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_change_log DROP FOREIGN KEY oa_change_log_change_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_change_log DROP FOREIGN KEY oa_change_log_user_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_change_log ADD CONSTRAINT oa_change_log_change_id FOREIGN KEY (change_id) REFERENCES oa_change (change_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_change_log ADD CONSTRAINT oa_change_log_user_id FOREIGN KEY (user_id) REFERENCES oa_user (user_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_graph DROP FOREIGN KEY oa_graph_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_graph ADD CONSTRAINT oa_graph_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_group_column DROP FOREIGN KEY oa_group_column_group_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_group_column ADD CONSTRAINT oa_group_column_group_id FOREIGN KEY (group_id) REFERENCES oa_group (group_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_group_sys DROP FOREIGN KEY oa_group_sys_group_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_group_sys DROP FOREIGN KEY oa_group_sys_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_group_sys ADD CONSTRAINT oa_group_sys_group_id FOREIGN KEY (group_id) REFERENCES oa_group (group_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_group_sys ADD CONSTRAINT oa_group_sys_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_group_user DROP FOREIGN KEY oa_group_user_group_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_group_user DROP FOREIGN KEY oa_group_user_user_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_group_user ADD CONSTRAINT oa_group_user_group_id FOREIGN KEY (group_id) REFERENCES oa_group (group_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_group_user ADD CONSTRAINT oa_group_user_user_id FOREIGN KEY (user_id) REFERENCES oa_user (user_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_location_org DROP FOREIGN KEY oa_loc_org_loc_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_location_org DROP FOREIGN KEY oa_loc_org_org_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_location_org ADD CONSTRAINT oa_loc_org_loc_id FOREIGN KEY (location_id) REFERENCES oa_location (location_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_location_org ADD CONSTRAINT oa_loc_org_org_id FOREIGN KEY (org_id) REFERENCES oa_org (org_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_net_nmap_ports DROP FOREIGN KEY oa_net_nmap_ports_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_net_nmap_ports ADD CONSTRAINT oa_net_nmap_ports_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_net_scan_latest DROP FOREIGN KEY oa_net_scan_latest_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_net_scan_latest ADD CONSTRAINT oa_net_scan_latest_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_net_scan_log DROP FOREIGN KEY oa_net_scan_log_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_net_scan_log ADD CONSTRAINT oa_net_scan_log_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_net_scan_type DROP FOREIGN KEY oa_net_scan_type_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_net_scan_type ADD CONSTRAINT oa_net_scan_type_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_report_column DROP FOREIGN KEY oa_report_column_group_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_report_column ADD CONSTRAINT oa_report_column_group_id FOREIGN KEY (report_id) REFERENCES oa_report (report_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_switch_ports DROP FOREIGN KEY oa_switch_ports_switch_switch_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_switch_ports DROP FOREIGN KEY oa_switch_ports_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_switch_ports ADD CONSTRAINT oa_switch_ports_switch_switch_id FOREIGN KEY (switch_system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_switch_ports ADD CONSTRAINT oa_switch_ports_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_battery DROP FOREIGN KEY sys_hw_battery_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_battery ADD CONSTRAINT sys_hw_battery_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_bios DROP FOREIGN KEY sys_hw_bios_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_bios ADD CONSTRAINT sys_hw_bios_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_graphs_disk DROP FOREIGN KEY sys_hw_graphs_disk_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_graphs_disk ADD CONSTRAINT sys_hw_graphs_disk_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_hard_drive DROP FOREIGN KEY sys_hw_hard_drive_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_hard_drive ADD CONSTRAINT sys_hw_hard_drive_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_memory DROP FOREIGN KEY sys_hw_memory_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_memory ADD CONSTRAINT sys_hw_memory_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_modem DROP FOREIGN KEY sys_hw_modem_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_modem ADD CONSTRAINT sys_hw_modem_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_monitor DROP FOREIGN KEY sys_hw_monitor_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_monitor ADD CONSTRAINT sys_hw_monitor_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_motherboard DROP FOREIGN KEY sys_hw_motherboard_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_motherboard ADD CONSTRAINT sys_hw_motherboard_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_network_card DROP FOREIGN KEY sys_hw_network_card_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_network_card ADD CONSTRAINT sys_hw_network_card_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_network_card_ip DROP FOREIGN KEY sys_hw_network_card_ip_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_network_card_ip ADD CONSTRAINT sys_hw_network_card_ip_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_optical_drive DROP FOREIGN KEY sys_hw_optical_drive_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_optical_drive ADD CONSTRAINT sys_hw_optical_drive_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_partition DROP FOREIGN KEY sys_hw_partition_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_partition ADD CONSTRAINT sys_hw_partition_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_processor DROP FOREIGN KEY sys_hw_processor_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_processor ADD CONSTRAINT sys_hw_processor_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_scsi_controller DROP FOREIGN KEY sys_hw_scsi_controller_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_scsi_controller ADD CONSTRAINT sys_hw_scsi_controller_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_sound DROP FOREIGN KEY sys_hw_sound_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_sound ADD CONSTRAINT sys_hw_sound_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_video DROP FOREIGN KEY sys_hw_video_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_video ADD CONSTRAINT sys_hw_video_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_warranty DROP FOREIGN KEY sys_hw_warranty_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_warranty ADD CONSTRAINT sys_hw_warranty_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_man_audits DROP FOREIGN KEY sys_man_audits_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_man_audits ADD CONSTRAINT sys_man_audits_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE additional_field DROP FOREIGN KEY additional_field_group_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE additional_field ADD CONSTRAINT additional_field_group_id FOREIGN KEY (group_id) REFERENCES oa_group (group_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE additional_field_item DROP FOREIGN KEY additional_field_item_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE additional_field_item ADD CONSTRAINT additional_field_item_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE additional_field_item DROP FOREIGN KEY additional_field_item_field_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE additional_field_item ADD CONSTRAINT additional_field_item_field_id FOREIGN KEY (field_id) REFERENCES additional_field (field_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_man_notes DROP FOREIGN KEY sys_man_notes_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_man_notes ADD CONSTRAINT sys_man_notes_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_man_notes DROP FOREIGN KEY sys_man_notes_user_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_man_notes ADD CONSTRAINT sys_man_notes_user_id FOREIGN KEY (user_id) REFERENCES oa_user (user_id)";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_antivirus DROP FOREIGN KEY sys_sw_antivirus_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_antivirus ADD CONSTRAINT sys_sw_antivirus_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_database DROP FOREIGN KEY sys_sw_db_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_database ADD CONSTRAINT sys_sw_db_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_database_details DROP FOREIGN KEY sys_sw_db_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_database_details ADD CONSTRAINT sys_sw_db_id FOREIGN KEY (db_id) REFERENCES sys_sw_database (db_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_database_log DROP FOREIGN KEY sys_sw_db_details_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_database_log ADD CONSTRAINT sys_sw_db_details_id FOREIGN KEY (details_id) REFERENCES sys_sw_database_details (details_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_firewall DROP FOREIGN KEY sys_sw_firewall_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_firewall ADD CONSTRAINT sys_sw_firewall_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_firewall_auth_app DROP FOREIGN KEY sys_sw_firewall_auth_app_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_firewall_auth_app ADD CONSTRAINT sys_sw_firewall_auth_app_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_firewall_ports DROP FOREIGN KEY sys_sw_firewall_ports_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_firewall_ports ADD CONSTRAINT sys_sw_firewall_ports_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_group DROP FOREIGN KEY sys_sw_groups_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_group ADD CONSTRAINT sys_sw_groups_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_log DROP FOREIGN KEY sys_sw_log_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_log ADD CONSTRAINT sys_sw_log_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_route DROP FOREIGN KEY sys_sw_ip_route_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_route ADD CONSTRAINT sys_sw_ip_route_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_pagefile DROP FOREIGN KEY sys_sw_pagefile_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_pagefile ADD CONSTRAINT sys_sw_pagefile_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_scheduled_task DROP FOREIGN KEY sys_sw_scheduled_task_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_scheduled_task ADD CONSTRAINT sys_sw_scheduled_task_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_service DROP FOREIGN KEY sys_sw_service_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_service ADD CONSTRAINT sys_sw_service_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_share DROP FOREIGN KEY sys_sw_share_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_share ADD CONSTRAINT sys_sw_share_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_share_perms DROP FOREIGN KEY sys_sw_share_perm_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_share_perms ADD CONSTRAINT sys_sw_share_perm_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_share_perms DROP FOREIGN KEY sys_sw_share_perm_share_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_share_perms ADD CONSTRAINT sys_sw_share_perm_share_id FOREIGN KEY (share_id) REFERENCES sys_sw_share (share_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_software DROP FOREIGN KEY sys_sw_software_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_software ADD CONSTRAINT sys_sw_software_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_software_key DROP FOREIGN KEY sys_sw_software_key_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_software_key ADD CONSTRAINT sys_sw_software_key_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_startup DROP FOREIGN KEY sys_sw_startup_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_startup ADD CONSTRAINT sys_sw_startup_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_user DROP FOREIGN KEY sys_sw_user_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_user ADD CONSTRAINT sys_sw_user_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_variable DROP FOREIGN KEY sys_sw_variable_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_variable ADD CONSTRAINT sys_sw_variable_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_web_server DROP FOREIGN KEY sys_sw_web_server_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_web_server ADD CONSTRAINT sys_sw_web_server_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_web_server_ext DROP FOREIGN KEY sys_sw_web_server_extn_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_web_server_ext ADD CONSTRAINT sys_sw_web_server_extn_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_web_server_ext DROP FOREIGN KEY sys_sw_web_server_extn_server_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_web_server_ext ADD CONSTRAINT sys_sw_web_server_extn_server_id FOREIGN KEY (webserver_id) REFERENCES sys_sw_web_server (webserver_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_web_site DROP FOREIGN KEY sys_sw_web_site_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_web_site ADD CONSTRAINT sys_sw_web_site_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_web_site DROP FOREIGN KEY sys_sw_web_site_server_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_web_site ADD CONSTRAINT sys_sw_web_site_server_id FOREIGN KEY (webserver_id) REFERENCES sys_sw_web_server (webserver_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_web_site_header DROP FOREIGN KEY sys_sw_web_site_header_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_web_site_header ADD CONSTRAINT sys_sw_web_site_header_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_web_site_header DROP FOREIGN KEY sys_sw_web_site_header_site_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_web_site_header ADD CONSTRAINT sys_sw_web_site_header_site_id FOREIGN KEY (site_id) REFERENCES sys_sw_web_site (site_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_web_site_virtual DROP FOREIGN KEY sys_sw_web_site_virtual_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_web_site_virtual ADD CONSTRAINT sys_sw_web_site_virtual_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_web_site_virtual DROP FOREIGN KEY sys_sw_web_site_virtual_site_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_web_site_virtual ADD CONSTRAINT sys_sw_web_site_virtual_site_id FOREIGN KEY (site_id) REFERENCES sys_sw_web_site (site_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_windows DROP FOREIGN KEY sys_sw_windows_system_id";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_windows ADD CONSTRAINT sys_sw_windows_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = '20120317' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = 'beta5' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $this->db->trans_complete();
         if ($this->db->trans_status() === false) {
             $this->data['output'] .= "ALERT - error encountered. Transactions rolled back.<br /><br />\n";
         } else {
             $this->data['output'] .= "Transaction committed.<br />beta5 upgrade successful.<br /><br />\n";
         }
     }
     if ($db_internal_version < '20120530' and $this->db->platform() == 'mysql') {
         # upgrade for beta6
         $this->data['output'] .= "Upgrading to beta6.<br /><br />\n";
         $sql = "ALTER TABLE oa_user MODIFY user_password varchar(250) NOT NULL ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "CREATE INDEX hostname ON system (hostname) ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "CREATE INDEX linked_sys ON system (linked_sys) ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "CREATE INDEX system_key ON system (system_key) ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "CREATE INDEX user_id_index ON oa_user (user_id) ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "CREATE INDEX user_id_index ON oa_group_user (user_id) ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "CREATE INDEX system_id_index ON oa_group_sys (system_id) ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "CREATE INDEX group_id_index ON oa_group (group_id) ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "DROP TABLE IF EXISTS sys_sw_dns";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "CREATE TABLE sys_sw_dns (dns_id int(10) unsigned NOT NULL auto_increment, system_id int(10) unsigned default NULL, dns_name varchar(100) NOT NULL default '', dns_full_name varchar(200) NOT NULL default '', dns_ip_address varchar(30) NOT NULL default '', timestamp datetime NOT NULL default '0000-00-00 00:00:00', first_timestamp datetime NOT NULL default '0000-00-00 00:00:00', PRIMARY KEY  (dns_id), KEY system_id (system_id), CONSTRAINT sys_sw_dns_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_database_details ADD system_id int(10) unsigned default NULL ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_database_log ADD system_id int(10) unsigned NOT NULL default '' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_database ADD db_version_string varchar(50) NOT NULL default '' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_database ADD db_edition varchar(50) NOT NULL default '' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_database_details ADD details_instance varchar(50) NOT NULL default '' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system CHANGE man_status man_status enum('production', 'retired', 'maintenance', 'deleted', 'unallocated', 'lost') NOT NULL default 'production' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system ADD printer_color varchar(5) NOT NULL default '' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system ADD printer_duplex varchar(5) NOT NULL default '' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system ADD man_service_provider varchar(100) NOT NULL default '' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system ADD man_service_number varchar(100) NOT NULL default '' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system ADD man_service_type varchar(100) NOT NULL default '' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system ADD man_service_plan varchar(100) NOT NULL default '' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system ADD man_service_network varchar(100) NOT NULL default '' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system ADD man_unlock_pin varchar(100) NOT NULL default '' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system ADD man_serial_imei varchar(100) NOT NULL default '' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system ADD man_serial_sim varchar(100) NOT NULL default '' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "CREATE TABLE sys_sw_print_queue (queue_id int(10) unsigned NOT NULL auto_increment, system_id int(10) unsigned default NULL, queue_system_key varchar(100) NOT NULL default '', queue_name varchar(100) NOT NULL default '', queue_port_name varchar(100) NOT NULL default '', queue_ip_address varchar(100) NOT NULL default '', queue_description varchar(100) NOT NULL default '', queue_model varchar(100) NOT NULL default '', queue_manufacturer varchar(100) NOT NULL default '', queue_shared varchar(100) NOT NULL default '', queue_shared_name varchar(100) NOT NULL default '', queue_location varchar(100) NOT NULL default '', queue_color varchar(100) NOT NULL default '', queue_duplex varchar(100) NOT NULL default '', queue_type enum('virtual', 'physical', '') NOT NULL default '', queue_connection_status varchar(100) NOT NULL default '', timestamp datetime NOT NULL default '0000-00-00 00:00:00', first_timestamp datetime NOT NULL default '0000-00-00 00:00:00', PRIMARY KEY (queue_id), KEY system_id (system_id), CONSTRAINT sys_sw_print_queue_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_connection ADD name varchar(100) NOT NULL default '' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_connection DROP speed ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_connection ADD speed FLOAT(7,3) NOT NULL default '0' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_connection ADD status enum('production', 'retired', 'maintenance', 'deleted') NOT NULL default 'production' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_org ADD org_group_id int(10) unsigned NOT NULL default '0' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_man_audits ADD audit_wmi_fails text NOT NULL default '' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = '20120530' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = 'beta6' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $this->data['output'] .= "Transaction committed.<br />beta6 upgrade successful.<br /><br />\n";
     }
     if ($db_internal_version < '20120830' and $this->db->platform() == 'mysql') {
         # upgrade for beta7
         $sql = "ALTER TABLE oa_location ADD location_group_id int(10) unsigned NOT NULL default '0' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = '20120830' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = 'beta7' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
     }
     if ($db_internal_version < '20121130' and $this->db->platform() == 'mysql') {
         # upgrade for beta8
         $sql = "DROP TABLE IF EXISTS sys_man_attachment";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "CREATE TABLE sys_man_attachment ( att_id int(10) unsigned NOT NULL auto_increment, system_id int(10) unsigned default NULL, user_id int(10) unsigned default NULL, att_title varchar(200) NOT NULL default '', att_filename text NOT NULL default '', timestamp datetime NOT NULL default '0000-00-00 00:00:00',  PRIMARY KEY  (att_id),  KEY system_id (system_id),  CONSTRAINT att_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE, CONSTRAINT att_user_id FOREIGN KEY (user_id) REFERENCES oa_user (user_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_man_notes DROP timestamp";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_man_notes ADD timestamp datetime NOT NULL default '0000-00-00 00:00:00'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "DROP TABLE IF EXISTS oa_device_col";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "DROP TABLE IF EXISTS oa_device";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "CREATE TABLE oa_device ( dev_id int(10) unsigned NOT NULL auto_increment, dev_name varchar(100) NOT NULL default '', dev_group_id int(10) unsigned NOT NULL default '0', PRIMARY KEY (dev_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "CREATE TABLE oa_device_col ( col_id int(10) unsigned NOT NULL auto_increment, dev_id int(10) unsigned default NULL, col_table varchar(100) NOT NULL default '', col_column varchar(100) NOT NULL default '', col_type varchar(100) NOT NULL default '', col_order int(10) unsigned default NULL, PRIMARY KEY (col_id), KEY dev_id (dev_id), CONSTRAINT oa_dev_col_dev_id FOREIGN KEY (dev_id) REFERENCES oa_device (dev_id) ON DELETE CASCADE) ENGINE=InnoDB DEFAULT CHARSET=utf8";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_config ADD config_editable varchar(1) NOT NULL default 'n'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_config ADD config_edited_date datetime NOT NULL default '0000-00-00 00:00:00'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_config ADD config_edited_by int(10) unsigned NOT NULL default '0'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_config ADD config_description varchar(200) NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = '20130126', config_editable = 'n', config_description = 'The internal numerical version.' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = 'beta8', config_editable = 'n', config_description = 'The version shown on the web pages.' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_config (config_name, config_value, config_editable, config_description) VALUES ('non_admin_search', 'y', 'y', 'Enable or disable search for non-Administrators');";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
     }
     if ($db_internal_version < '20130130' and $this->db->platform() == 'mysql') {
         # upgrade for beta8
         $sql = "UPDATE oa_config set config_value = '20130130', config_editable = 'n', config_description = 'The internal numerical version.' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = 'beta8.2', config_editable = 'n', config_description = 'The version shown on the web pages.' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
     }
     if ($db_internal_version < '20130131' and $this->db->platform() == 'mysql') {
         # upgrade for beta8
         $sql = "UPDATE oa_config set config_value = '20130131', config_editable = 'n', config_description = 'The internal numerical version.' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = 'beta8.4', config_editable = 'n', config_description = 'The version shown on the web pages.' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
     }
     if ($db_internal_version < '20130201' and $this->db->platform() == 'mysql') {
         # upgrade for beta8
         $sql = "UPDATE oa_config set config_value = '20130201', config_editable = 'n', config_description = 'The internal numerical version.' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = 'beta8.5', config_editable = 'n', config_description = 'The version shown on the web pages.' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
     }
     if ($db_internal_version < '20130202' and $this->db->platform() == 'mysql') {
         # upgrade for beta9
         $sql = "DROP TABLE IF EXISTS oa_asset_line";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "CREATE TABLE oa_asset_line ( line_id int(10) NOT NULL auto_increment, order_id int(10) unsigned default NULL, org_id int(10) unsigned default NULL, select_id int(10) unsigned default NULL, line_amount int(10) unsigned default NULL, line_cost_each int(10) unsigned default NULL, line_tax_each int(10) unsigned default NULL, line_asset_number varchar(50) NOT NULL, line_gl varchar(50) NOT NULL, line_type enum('', 'sw', 'hw') NOT NULL default '', line_sw_license_expires_date datetime NOT NULL default '0000-00-00 00:00:00', line_sw_license_key varchar(50) NOT NULL, line_sw_license_number varchar(50) NOT NULL, line_sw_license_agreement varchar(50) NOT NULL, line_sw_license_type enum('', 'license', 'license and maintenance', 'upgrade', 'upgrade and maintenance', 'maintenance') NOT NULL default '', line_vendor_producit_id varchar(50) NOT NULL, line_vendor_part_id varchar(50) NOT NULL, line_maintenance_included varchar(50) NOT NULL, line_maintenance_date_expires datetime NOT NULL default '0000-00-00 00:00:00', allocate_type enum('', 'group', 'location', 'org', 'person', 'item', 'other') NOT NULL default '', allocate_text varchar(50) NOT NULL default '', PRIMARY KEY  (line_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "DROP TABLE IF EXISTS oa_asset_order";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "CREATE TABLE oa_asset_order ( order_id int(10) NOT NULL auto_increment, order_date datetime NOT NULL default '0000-00-00 00:00:00', order_po varchar(50) NOT NULL, order_vn varchar(50) NOT NULL, order_in varchar(50) NOT NULL, order_vendor varchar(50) NOT NULL, order_auth_officer varchar(100) NOT NULL, order_cost_code varchar(50) NOT NULL, order_notes text NOT NULL default '', PRIMARY KEY  (order_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "DROP TABLE IF EXISTS oa_asset_select";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "CREATE TABLE oa_asset_select (select_id int(10) NOT NULL auto_increment, select_name varchar(50) NOT NULL, select_type enum('', 'sw', 'hw', 'service', 'other') NOT NULL default '', select_sql varchar(250) NOT NULL, group_id int(10) unsigned default NULL, group_amount int(10) unsigned default '0', PRIMARY KEY (select_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_asset_line CHANGE line_type line_type enum('', 'sw', 'hw', 'service', 'other') NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_asset_line CHANGE allocate_type allocate_type enum('', 'group', 'location', 'org', 'person', 'item', 'other') NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_asset_line CHANGE allocate_text allocate_text varchar(50) NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_config (config_name, config_value, config_editable, config_description) VALUES ('ad_domain', '', 'y', 'The domain name against which your users will validate. EG - open-audit.org') ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_config (config_name, config_value, config_editable, config_description) VALUES ('ad_server', '', 'y', 'The IP Address of your domain controller. EG - 192.168.0.1') ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = '20130202', config_editable = 'n', config_description = 'The internal numerical version.' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = 'beta 9', config_editable = 'n', config_description = 'The version shown on the web pages.' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
     }
     if ($db_internal_version < '20130204' and $this->db->platform() == 'mysql') {
         # upgrade for beta 9.1
         $sql = "DROP TABLE IF EXISTS oa_asset_line";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "CREATE TABLE oa_asset_line ( line_id int(10) NOT NULL auto_increment, order_id int(10) unsigned default NULL, org_id int(10) unsigned default NULL, select_id int(10) unsigned default NULL, line_amount int(10) unsigned default NULL, line_cost_each int(10) unsigned default NULL, line_tax_each int(10) unsigned default NULL, line_asset_number varchar(50) NOT NULL, line_gl varchar(50) NOT NULL, line_type enum('', 'sw', 'hw') NOT NULL default '', line_sw_license_expires_date datetime NOT NULL default '0000-00-00 00:00:00', line_sw_license_key varchar(50) NOT NULL, line_sw_license_number varchar(50) NOT NULL, line_sw_license_agreement varchar(50) NOT NULL, line_sw_license_type enum('', 'license', 'license and maintenance', 'upgrade', 'upgrade and maintenance', 'maintenance') NOT NULL default '', line_vendor_producit_id varchar(50) NOT NULL, line_vendor_part_id varchar(50) NOT NULL, line_maintenance_included varchar(50) NOT NULL, line_maintenance_date_expires datetime NOT NULL default '0000-00-00 00:00:00', allocate_type enum('', 'group', 'location', 'org', 'person', 'item', 'other') NOT NULL default '', allocate_text varchar(50) NOT NULL default '', PRIMARY KEY  (line_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "DROP TABLE IF EXISTS oa_asset_order";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "CREATE TABLE oa_asset_order ( order_id int(10) NOT NULL auto_increment, order_date datetime NOT NULL default '0000-00-00 00:00:00', order_po varchar(50) NOT NULL, order_vn varchar(50) NOT NULL, order_in varchar(50) NOT NULL, order_vendor varchar(50) NOT NULL, order_auth_officer varchar(100) NOT NULL, order_cost_code varchar(50) NOT NULL, order_notes text NOT NULL default '', PRIMARY KEY  (order_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_config (config_name, config_value, config_editable, config_description) VALUES ('auto_create_network_groups', 'y', 'y', 'Have Open-AudIT automatically create Groups based on Subnet.') ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = '20130204', config_editable = 'n', config_description = 'The internal numerical version.' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = 'beta 9.1', config_editable = 'n', config_description = 'The version shown on the web pages.' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
     }
     if ($db_internal_version < '20130205' and $this->db->platform() == 'mysql') {
         # upgrade for beta 9.2
         $sql = "DROP TABLE IF EXISTS oa_asset_line";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "CREATE TABLE oa_asset_line ( line_id int(10) NOT NULL auto_increment, order_id int(10) unsigned default NULL, org_id int(10) unsigned default NULL, select_id int(10) unsigned default NULL, line_amount int(10) unsigned default NULL, line_cost_each int(10) unsigned default NULL, line_tax_each int(10) unsigned default NULL, line_asset_number varchar(50) NOT NULL, line_gl varchar(50) NOT NULL, line_type enum('', 'sw', 'hw') NOT NULL default '', line_sw_license_expires_date datetime NOT NULL default '0000-00-00 00:00:00', line_sw_license_key varchar(50) NOT NULL, line_sw_license_number varchar(50) NOT NULL, line_sw_license_agreement varchar(50) NOT NULL, line_sw_license_type enum('', 'license', 'license and maintenance', 'upgrade', 'upgrade and maintenance', 'maintenance') NOT NULL default '', line_vendor_producit_id varchar(50) NOT NULL, line_vendor_part_id varchar(50) NOT NULL, line_maintenance_included varchar(50) NOT NULL, line_maintenance_date_expires datetime NOT NULL default '0000-00-00 00:00:00', allocate_type enum('', 'group', 'location', 'org', 'person', 'item', 'other') NOT NULL default '', allocate_text varchar(50) NOT NULL default '', PRIMARY KEY  (line_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "DROP TABLE IF EXISTS oa_asset_order";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "CREATE TABLE oa_asset_order ( order_id int(10) NOT NULL auto_increment, order_date datetime NOT NULL default '0000-00-00 00:00:00', order_po varchar(50) NOT NULL, order_vn varchar(50) NOT NULL, order_in varchar(50) NOT NULL, order_vendor varchar(50) NOT NULL, order_auth_officer varchar(100) NOT NULL, order_cost_code varchar(50) NOT NULL, order_notes text NOT NULL default '', PRIMARY KEY  (order_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_config (config_name, config_value, config_editable, config_description) VALUES ('auto_create_network_groups', 'y', 'y', 'Have Open-AudIT automatically create Groups based on Subnet.') ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = '20130205', config_editable = 'n', config_description = 'The internal numerical version.' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = 'beta 9.2', config_editable = 'n', config_description = 'The version shown on the web pages.' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
     }
     if ($db_internal_version < '20130512' and $this->db->platform() == 'mysql') {
         # upgrade for 1.0
         $this->data['output'] .= "New 'All Devices' Group created. Ensure you have access via Admin -> Users -> Edit User<br /><br />\n";
         $sql = "ALTER TABLE system ADD nmap_type varchar(50) NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system ADD contact_name varchar(50) NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system ADD fqdn text NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system ADD access_details text NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system ADD snmp_oid text NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system ADD nmis_group varchar(50) NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system ADD nmis_name varchar(50) NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system ADD nmis_role varchar(50) NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_report_column MODIFY column_type enum('','link','image','ip_address','text','timestamp','url', 'multi')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_location MODIFY location_latitude float(10,6)";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_location MODIFY location_longitude float(10,6)";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_location ADD location_icon varchar(100) NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_location ADD location_geotag varchar(200) NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_user ADD user_active varchar(1) NOT NULL default 'y'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_user SET user_active = 'y'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system DROP man_acting_server";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system ADD system_key_type varchar(4) NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_config (config_name, config_value, config_editable, config_description) VALUES ('nmis', 'n', 'y', 'Enable import / export to NMIS functions.')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_group_column set column_link = '/main/system_display/' WHERE group_id = '1' and column_name = 'Hostname'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE system SET type = 'computer', man_type = 'computer' WHERE type = 'system' or man_type = 'system'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         # grab a copy of the users and their access levels to group_id 1
         $sql = "SELECT user_id, group_user_access_level FROM oa_group_user WHERE group_id = '1'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $user_array = $query->result();
         $sql = "DELETE FROM oa_group WHERE group_id = '1'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "DELETE FROM oa_group_column WHERE group_id = '1'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_group VALUES  ('1', 'All Devices', '', 'SELECT distinct(system.system_id) FROM system WHERE system.man_status = \\'production\\'',1,'Any items that have their status attribute set to production.', 'device', '', 'devices')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_group_column VALUES (NULL, '1', '1', 'Icon', 'man_icon', 'image', '',  'man_os_family', '', 'left')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_group_column VALUES (NULL, '1', '2', 'Hostname', 'hostname', 'link', '/main/system_display/', 'system_id', '', 'left')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_group_column VALUES (NULL, '1', '3', 'IP Address', 'man_ip_address', 'ip_address', '',  '', '', 'left')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_group_column VALUES (NULL, '1', '4', 'Type', 'man_type', 'text', '',  '', '', 'left')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_group_column VALUES (NULL, '1', '5', 'Description', 'man_description', 'text', '',  '', '', 'left')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_group_column VALUES (NULL, '1', '6', 'OS / Device', 'man_os_name', 'text', '',  '', '', 'left')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_group_column VALUES (NULL, '1', '7', 'Tags', 'tag',  'text', '',  '', '', 'left')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         # re-insert the users who originally had access to the group_id 1 which should be the All Devices group
         foreach ($user_array as $user) {
             $sql = "INSERT INTO oa_group_user (group_user_id, user_id, group_id,\n                    group_user_access_level) VALUES (NULL, ?, '1', ?)";
             $data = array($user->id, $user->group_user_access_level);
             $query = $this->db->query($sql, $data);
             $this->data['output'] .= $this->db->last_query() . "<br /><br />\n";
         }
         $sql = "update oa_group_column set column_link = '/main/system_display/' where column_link = 'main/system_display/'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = '20130512', config_editable = 'n', config_description = 'The internal numerical version.' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = '1.0', config_editable = 'n', config_description = 'The version shown on the web pages.' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
     }
     if ($db_internal_version < '20130620' and $this->db->platform() == 'mysql') {
         # upgrade for 1.0.3
         $sql = "ALTER TABLE sys_man_audits ADD system_audits_ip varchar(30) NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_location CHANGE location_geotag location_geo varchar(200) NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_location ADD location_suburb varchar(100) NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_location ADD location_district varchar(100) NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_location ADD location_region varchar(100) NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_location ADD location_area varchar(100) NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_location ADD location_tags varchar(250) NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE sys_hw_processor SET processor_description = replace (processor_description, '(R)', '')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE sys_hw_processor SET processor_description = replace (processor_description, '(r)', '')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE sys_hw_processor SET processor_description = replace (processor_description, '(TM)', '')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE sys_hw_processor SET processor_description = replace (processor_description, '(tm)', '')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE sys_hw_processor SET processor_description = replace (processor_description, '  ', ' ')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE sys_hw_processor SET processor_description = replace (processor_description, '  ', ' ')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE sys_hw_processor SET processor_description = replace (processor_description, '  ', ' ')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE sys_hw_processor SET processor_description = replace (processor_description, '  ', ' ')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE sys_hw_processor SET processor_description = replace (processor_description, '  ', ' ')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE sys_hw_processor SET processor_description = replace (processor_description, '  ', ' ')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE sys_hw_processor SET processor_description = replace (processor_description, '  ', ' ')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE system SET man_os_name = replace (man_os_name, '(R)', '')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE system SET man_os_name = replace (man_os_name, '(r)', '')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE system SET man_os_name = replace (man_os_name, '(TM)', '')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE system SET man_os_name = replace (man_os_name, '(tm)', '')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_config (config_name, config_value, config_editable, config_description) VALUES ('nmis_url', '', 'y', 'The web server address of Open-AudIT Enterprise.')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_config (config_name, config_value, config_editable, config_description) VALUES ('oae_url', '', 'y', 'The web server address of Open-AudIT Enterprise.')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_config (config_name, config_value, config_editable, config_description) VALUES ('maps_url', '', 'y', 'The web server address of opMaps.')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = '20130620', config_editable = 'n', config_description = 'The internal numerical version.' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = '1.0.3', config_editable = 'n', config_description = 'The version shown on the web pages.' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
     }
     if ($db_internal_version < '20130810' and $this->db->platform() == 'mysql') {
         # upgrade for 1.0.4
         $this->load->model('m_oa_user');
         $sql = "ALTER TABLE sys_sw_pagefile ADD pagefile_size varchar(10) NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system ADD man_location_rack_size int(10) unsigned NOT NULL default '0'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "DROP TABLE IF EXISTS oa_net_nmap_ports";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "DROP TABLE IF EXISTS oa_net_scan_latest";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "DROP TABLE IF EXISTS oa_net_scan_log";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "DROP TABLE IF EXISTS oa_net_scan_type";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "DROP TABLE IF EXISTS sys_hw_battery";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "DROP TABLE IF EXISTS sys_hw_firewire";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "DROP TABLE IF EXISTS sys_hw_floppy";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "DROP TABLE IF EXISTS sys_hw_keyboard";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "DROP TABLE IF EXISTS sys_hw_modem";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "DROP TABLE IF EXISTS sys_hw_mouse";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "DROP TABLE IF EXISTS sys_hw_onboard_device";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "DROP TABLE IF EXISTS sys_hw_scsi_device";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "DROP TABLE IF EXISTS sys_hw_tape_drive";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "DROP TABLE IF EXISTS sys_hw_usb";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "DROP TABLE IF EXISTS sys_sw_antivirus";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "DROP TABLE IF EXISTS sys_sw_database_log";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "DROP TABLE IF EXISTS sys_sw_firewall";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "DROP TABLE IF EXISTS sys_sw_firewall_auth_app";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "DROP TABLE IF EXISTS sys_sw_firewall_ports";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "DROP TABLE IF EXISTS sys_sw_mapped";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "DROP TABLE IF EXISTS sys_sw_odbc";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "DROP TABLE IF EXISTS sys_sw_startup";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "DROP TABLE IF EXISTS sys_sw_system_security";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "DROP TABLE IF EXISTS sys_sw_system_security_bulletins";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         # Add the Open-AudIT Enterprise user if not already present
         if (!$this->m_oa_user->select_user("open-audit_enterprise")) {
             $sql = "INSERT INTO oa_user (user_id, user_name, user_password, user_full_name, user_lang, user_theme, user_admin, user_change, user_sam, user_active) VALUES (NULL, 'open-audit_enterprise', '43629bd846bb90e40221d5276c832857ca51e49e325f7344704543439ffd6b6d3a963a32a41f55fca6d995fd302acbe03ea7d8bf2b3af91d662d497b0ad9ba1e', 'Open-AudIT Enterprise', 'en', 'tango', 'n', '0', '1', 'y')";
             $this->data['output'] .= $sql . "<br /><br />\n";
             $query = $this->db->query($sql);
             $user_id = $this->db->insert_id();
             $sql = "INSERT INTO oa_group_user (user_id, group_id, group_user_access_level) VALUES ('" . $user_id . "', '1', '3')";
             $this->data['output'] .= $sql . "<br /><br />\n";
             $query = $this->db->query($sql);
             $this->data['message'] .= "A new user 'open-audit_enterprise' has been created. This user has 'list view only' access to the All Devices group. Please disable if you are not using Open-AudIT Enterprise.<br /><br />";
         }
         # Add the NMIS user if not already present
         if (!$this->m_oa_user->select_user("nmis")) {
             $sql = "INSERT INTO oa_user (user_id, user_name, user_password, user_full_name, user_lang, user_theme, user_admin, user_change, user_sam, user_active) VALUES (NULL, 'nmis', '5a7f9a638ea430196d765ef8d3875eafd64ee3d155ceddaced75467a76b97ab24080cba4a2e74cde03799a6a49dbc5c36ee204eff1d5f42e08cf7a423fdf9757', 'NMIS', 'en', 'tango', 'y', '0', '1', 'y')";
             $this->data['output'] .= $sql . "<br /><br />\n";
             $query = $this->db->query($sql);
             $user_id = $this->db->insert_id();
             $sql = "INSERT INTO oa_group_user (user_id, group_id, group_user_access_level) VALUES ('" . $user_id . "', '1', '3')";
             $this->data['output'] .= $sql . "<br /><br />\n";
             $query = $this->db->query($sql);
             $this->data['message'] .= "A new user 'nmis' has been created. This user has admin access. Please disable if you are not using Open-AudIT Enterprise.<br /><br />";
         }
         $sql = "INSERT INTO oa_config (config_name, config_value, config_editable) VALUES ('logo', 'oac-oae', 'n')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_config (config_name, config_value, config_editable, config_description) VALUES ('name_match', 'n', 'y', 'Should we match a device based only on its hostname as a last resort.')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_log CHANGE log_file_name log_file_name varchar(250) NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "DROP TABLE IF EXISTS sys_sw_netstat";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "CREATE TABLE sys_sw_netstat (id int(10) unsigned NOT NULL auto_increment, system_id int(10) unsigned default NULL, protocol enum('tcp', 'udp', 'tcp6', 'udp6', '') NOT NULL default '', ip_address varchar(45) NOT NULL default '', port int(5) NOT NULL default '0', program  varchar(250) NOT NULL default '', timestamp datetime NOT NULL default '0000-00-00 00:00:00', first_timestamp datetime NOT NULL default '0000-00-00 00:00:00',  PRIMARY KEY  (id), KEY system_id (system_id), CONSTRAINT sys_sw_netstat_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         # we are removing man_vendor from the database
         # there is a column called man_purchase_vendor which is used on several forms
         # man_vendor data (if exists) will be copied to man_purchase_vendor (if not exists)
         $sql = "SELECT system_id, man_vendor, man_purchase_vendor FROM system";
         $query = $this->db->query($sql);
         $system_array = $query->result();
         foreach ($system_array as $system) {
             if ($system->man_vendor > "" and $system->man_purchase_vendor == "") {
                 $sql = "UPDATE system SET man_purchase_vendor = ? WHERE system_id = ?";
                 $data = array($system->man_vendor, $system->system_id);
                 $query = $this->db->query($sql, $data);
                 $this->data['output'] .= $this->db->last_query() . "<br /><br />\n";
             }
         }
         $sql = "ALTER TABLE system CHANGE description description varchar(250) NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system CHANGE man_description man_description varchar(250) NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system DROP man_vendor";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_config CHANGE config_value config_value varchar(250) NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_config (config_name, config_value, config_editable, config_description) VALUES ('snmp_default_community', 'public', 'y', 'The default community string Open-AudIT will use when connecting to a new device.')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = '20130810', config_editable = 'n', config_description = 'The internal numerical version.' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = '1.0.4', config_editable = 'n', config_description = 'The version shown on the web pages.' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
     }
     if ($db_internal_version < '20131130' and $this->db->platform() == 'mysql') {
         # upgrade for 1.0.5
         $sql = "INSERT INTO oa_config (config_name, config_value, config_editable, config_description) VALUES ('distinct_groups', 'y', 'y', 'Display Groups on the homepage, separated into the type of each Group.')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = '20131130', config_editable = 'n', config_description = 'The internal numerical version.' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = '1.0.5', config_editable = 'n', config_description = 'The version shown on the web pages.' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
     }
     if ($db_internal_version < '20131211' and $this->db->platform() == 'mysql') {
         # upgrade for 1.0.6
         $sql = "UPDATE oa_config set config_value = '20131211', config_editable = 'n', config_description = 'The internal numerical version.' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = '1.0.6', config_editable = 'n', config_description = 'The version shown on the web pages.' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
     }
     if ($db_internal_version < '20131219' and $this->db->platform() == 'mysql') {
         # upgrade for 1.1
         $sql = "UPDATE oa_config set config_value = '20131219', config_editable = 'n', config_description = 'The internal numerical version.' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = '1.1', config_editable = 'n', config_description = 'The version shown on the web pages.' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
     }
     if ($db_internal_version < '20140126' and $this->db->platform() == 'mysql') {
         # upgrade for 1.1.1
         # update the details of the default group
         $sql = "UPDATE oa_location set location_name = 'Default Location', location_type = 'Office', location_city = 'Gold Coast', location_state = 'Queensland', location_country = 'Australia', location_latitude = '-28.017260', location_longitude = '153.425705', location_icon = 'office' WHERE location_id = '0'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         # insert the accompanying group
         $sql = "INSERT INTO oa_group (group_id, group_name, group_dynamic_select, group_parent, group_description, group_category, group_icon) VALUES (NULL, 'Items in Default Location', 'SELECT distinct(system.system_id) FROM system WHERE system.man_location_id = \\'0\\' and system.man_status = \\'production\\'', '1', 'Items in Default Location', 'location', 'location')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $group_id = $this->db->insert_id();
         # give Admin level users access to the group
         $sql = "INSERT INTO oa_group_user (SELECT NULL, user_id, ?, '10' FROM oa_user WHERE user_admin = 'y')";
         $data = array($group_id);
         $query = $this->db->query($sql, $data);
         $this->data['output'] .= $this->db->last_query() . "<br /><br />\n";
         # and update the location with the inserted group_id
         $sql = "UPDATE oa_location SET location_group_id = ? WHERE location_id = '0'";
         $data = array($group_id);
         $query = $this->db->query($sql, $data);
         $this->data['output'] .= $this->db->last_query() . "<br /><br />\n";
         $sql = "UPDATE oa_config set config_value = '/omk/oae' WHERE config_name = 'oae_url'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = '/omk/oae/map' WHERE config_name = 'maps_url'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_description = 'The web server address of NMIS.' WHERE config_name = 'nmis_url'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "SELECT config_value FROM oa_config WHERE config_name = 'nmis_url'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $row = $query->row();
         if ($row->config_value == 'http://localhost/cgi-nmis8/nmiscgi.pl') {
             $sql = "UPDATE oa_config set config_value = '' WHERE config_name = 'nmis_url'";
             $this->data['output'] .= $sql . "<br /><br />\n";
             $query = $this->db->query($sql);
         }
         $sql = "UPDATE oa_config set config_value = '20140126', config_editable = 'n', config_description = 'The internal numerical version.' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = '1.1.1', config_editable = 'n', config_description = 'The version shown on the web pages.' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "SELECT count(*) AS systems FROM system";
         $query = $this->db->query($sql);
         $row = $query->row();
         if ($row->systems > "0") {
             $this->data['output'] .= "<br /><span style=\"color:red;\">NOTE</span> Please click <a href=\"../admin_group/list_groups\" style=\"color: blue;\">this link</a> (or go to Admin -> List Groups) and update (icon on the right) the new Group for 'Items in Default Location'.<br />";
         }
     }
     if ($db_internal_version < '20140204' and $this->db->platform() == 'mysql') {
         # upgrade for 1.2
         $sql = "ALTER TABLE sys_hw_memory ADD memory_serial varchar(100) NOT NULL default '' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_netstat CHANGE protocol protocol enum('tcp', 'udp', 'tcp6', 'udp6', 'tcp4', 'udp4', '') NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_software ADD software_description text NOT NULL default '' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_config (config_name, config_value, config_editable, config_description) VALUES ('default_windows_username', '', 'y', 'The default username used by Open-AudIT to audit Windows PCs.')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_config (config_name, config_value, config_editable, config_description) VALUES ('default_windows_password', '', 'y', 'The default password used by Open-AudIT to audit Windows PCs.')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_config (config_name, config_value, config_editable, config_description) VALUES ('default_windows_domain', '', 'y', 'The default active directory domain used by Open-AudIT to audit Windows PCs.')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_config (config_name, config_value, config_editable, config_description) VALUES ('default_ssh_username', '', 'y', 'The default username used by Open-AudIT to audit devices via SSH.')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_config (config_name, config_value, config_editable, config_description) VALUES ('default_ssh_password', '', 'y', 'The default password used by Open-AudIT to audit devices via SSH.')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_config (config_name, config_value, config_editable, config_description) VALUES ('default_network_address', '', 'y', 'The ip address or resolvable hostname used by external devices to talk to Open-AudIT.')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config SET config_value = 'y' WHERE config_name = 'name_match'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $this->data['output'] .= "<br /><span style=\"color:red;\">NOTE</span> The configuration item name_match has been set to \"y\". This is for the new discovery features. If you do not wish to match devices based on their hostname, please go to Admin -> Config and change it to \"n\".\n";
         $sql = "UPDATE oa_config SET config_name = 'default_snmp_community' WHERE config_name = 'snmp_default_community'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "CREATE TABLE oa_temp ( temp_id int(10) unsigned NOT NULL auto_increment, temp_name text NOT NULL, temp_value text NOT NULL, temp_timestamp datetime NOT NULL default '0000-00-00 00:00:00', PRIMARY KEY  (temp_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_config (config_name, config_value, config_editable, config_description) VALUES ('show_snmp_community', 'y', 'y', 'Show the SNMP community string on forms.')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_config (config_name, config_value, config_editable, config_description) VALUES ('show_passwords', 'y', 'y', 'Show any passwords on forms.')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config SET config_value = '20140204', config_editable = 'n', config_description = 'The internal numerical version.' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config SET config_value = '1.2', config_editable = 'n', config_description = 'The version shown on the web pages.' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
     }
     if ($db_internal_version < '20140228' and $this->db->platform() == 'mysql') {
         # upgrade for 1.2.1
         $sql = "UPDATE oa_config set config_value = '20140228', config_editable = 'n', config_description = 'The internal numerical version.' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = '1.2.1', config_editable = 'n', config_description = 'The version shown on the web pages.' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
     }
     if ($db_internal_version < '20140403' and $this->db->platform() == 'mysql') {
         # upgrade for 1.3
         $sql = "ALTER TABLE sys_hw_processor ADD processor_count int(2) unsigned NOT NULL default '0' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_processor ADD processor_logical int(2) unsigned NOT NULL default '0' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         # we need to upgrade the OAE user to admin because it needs to read the config to populate the discovery page in OAE
         $sql = "UPDATE oa_user SET user_admin = 'y' WHERE user_name = 'open-audit_enterprise' ";
         $this->data['output'] .= "We need to upgrade the open-audit_enterprise user to admin level because it needs to read the config to populate the discovery page in Open-AudIT Enterprise.<br /><br />\n";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = '20140403', config_editable = 'n', config_description = 'The internal numerical version.' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = '1.3', config_editable = 'n', config_description = 'The version shown on the web pages.' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
     }
     if ($db_internal_version < '20140501' and $this->db->platform() == 'mysql') {
         # upgrade for 1.3.1
         $sql = "UPDATE oa_config set config_value = '20140501', config_editable = 'n', config_description = 'The internal numerical version.' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = '1.3.1', config_editable = 'n', config_description = 'The version shown on the web pages.' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
     }
     if ($db_internal_version < '20140515' and $this->db->platform() == 'mysql') {
         # upgrade for 1.3.2
         $sql = "ALTER TABLE sys_hw_network_card_ip ADD net_index varchar(10) NOT NULL default '' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_config (config_name, config_value, config_editable, config_description) VALUES ('rss_enable', 'y', 'y', 'Enable the RSS feed.')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_config (config_name, config_value, config_editable, config_description) VALUES ('rss_url', 'https://community.opmantek.com/rss/OA.xml', 'y', 'The RSS feed URL.')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system CHANGE man_class man_class enum('desktop','laptop','tablet','workstation','server','virtual server','virtual desktop','','hypervisor') NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "CREATE TABLE sys_sw_virtual_machine ( id int(10) unsigned NOT NULL auto_increment, system_id int(10) unsigned default NULL, guest_system_id int(10) unsigned default NULL, name varchar(100) NOT NULL default '', vm_id int(12) unsigned NOT NULL default '0', vm_group text NOT NULL default '', config_file text NOT NULL default '', uuid text NOT NULL default '', memory int(12) unsigned NOT NULL default '0', cpu int(10) unsigned NOT NULL default '0', status varchar(100) NOT NULL default '', timestamp datetime NOT NULL default '0000-00-00 00:00:00', first_timestamp datetime NOT NULL default '0000-00-00 00:00:00', PRIMARY KEY  (id), KEY system_id (system_id), CONSTRAINT sys_sw_virtual_machine_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = '20140515', config_editable = 'n', config_description = 'The internal numerical version.' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = '1.3.2', config_editable = 'n', config_description = 'The version shown on the web pages.' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
     }
     if ($db_internal_version < '20140620' and $this->db->platform() == 'mysql') {
         # upgrade for 1.3.3
         $sql = "ALTER TABLE sys_hw_network_card ADD net_alias varchar(255) NOT NULL default '' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config SET config_value = '20140620', config_editable = 'n', config_description = 'The internal numerical version.' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config SET config_value = '1.3.3', config_editable = 'n', config_description = 'The version shown on the web pages.' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
     }
     if ($db_internal_version < '20140720' and $this->db->platform() == 'mysql') {
         # upgrade for 1.4
         $sql = "ALTER TABLE sys_hw_hard_drive ADD hard_drive_firmware varchar(100) NOT NULL default '' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_processor ADD processor_architecture varchar(100) NOT NULL default '' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_config (config_name, config_value, config_editable, config_description) VALUES ('default_ipmi_username', '', 'y', 'The default username used by Open-AudIT to audit devices via IPMI.')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_config (config_name, config_value, config_editable, config_description) VALUES ('default_ipmi_password', '', 'y', 'The default password used by Open-AudIT to audit devices via IPMI.')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_network_card CHANGE net_model net_model varchar(255) NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config SET config_value = '20140720', config_editable = 'n', config_description = 'The internal numerical version.' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config SET config_value = '1.4', config_editable = 'n', config_description = 'The version shown on the web pages.' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
     }
     if ($db_internal_version < '20140827' and $this->db->platform() == 'mysql') {
         # upgrade for 1.4.1
         $sql = "INSERT INTO oa_config (config_name, config_value, config_editable, config_description) VALUES ('download_reports', 'download', 'y', 'Tells Open-AudIT to advise the browser to download as a file or display the csv, xml, json reports. Valid values are download and display.')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config SET config_value = '20140827', config_editable = 'n', config_description = 'The internal numerical version.' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config SET config_value = '1.4.1', config_editable = 'n', config_description = 'The version shown on the web pages.' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
     }
     if ($db_internal_version < '20141024' and $this->db->platform() == 'mysql') {
         # upgrade for 1.5
         $sql = "ALTER TABLE oa_user_sessions CHANGE ip_address ip_address varchar(45) DEFAULT '0' NOT NULL";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_user_sessions CHANGE user_agent user_agent varchar(120) NOT NULL";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $fields = $this->db->list_fields('sys_hw_hard_drive');
         $temp_hit = 0;
         foreach ($fields as $field) {
             if ($field == 'hard_drive_model_family') {
                 $temp_hit = 1;
             }
         }
         if ($temp_hit == 0) {
             $sql = "ALTER TABLE sys_hw_hard_drive ADD hard_drive_model_family varchar(200) NOT NULL default '' ";
             $this->data['output'] .= $sql . "<br /><br />\n";
             $query = $this->db->query($sql);
         }
         $sql = 'UPDATE oa_report_column SET column_link = "/report/Specific Software/$group_id/" WHERE column_link = "/report/specific_software/$group_id/"';
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = 'UPDATE oa_report_column SET column_link = "/report/Specific Key Name/$group_id/" WHERE column_link = "/report/specific_key_name/$group_id/"';
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = 'UPDATE oa_report_column SET column_link = "/report/Specific Key Text/$group_id/" WHERE column_link = "/report/specific_key_text/$group_id/"';
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = '20141024', config_editable = 'n', config_description = 'The internal numerical version.' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = '1.5', config_editable = 'n', config_description = 'The version shown on the web pages.' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
     }
     if ($db_internal_version < '20141130' and $this->db->platform() == 'mysql') {
         # upgrade for 1.5.1
         $sql = "ALTER TABLE system ADD sysDescr varchar(255) NOT NULL default '' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system ADD sysObjectID varchar(255) NOT NULL default '' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system ADD sysUpTime varchar(255) NOT NULL default '' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system ADD sysContact varchar(255) NOT NULL default '' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system ADD sysName varchar(255) NOT NULL default '' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system ADD sysLocation varchar(255) NOT NULL default '' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = '20141130', config_editable = 'n', config_description = 'The internal numerical version.' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = '1.5.1', config_editable = 'n', config_description = 'The version shown on the web pages.' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
     }
     if ($db_internal_version < '20141208' and $this->db->platform() == 'mysql') {
         # upgrade for 1.5.2
         $sql = "ALTER TABLE system ADD nmis_export enum('true', 'false') NOT NULL default 'false' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system CHANGE sysDescr sysDescr text NOT NULL";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system CHANGE description description text NOT NULL";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system CHANGE man_description man_description text NOT NULL";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = '20141208', config_editable = 'n', config_description = 'The internal numerical version.' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_value = '1.5.2', config_editable = 'n', config_description = 'The version shown on the web pages.' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
     }
     if ($db_internal_version < '20141225' and $this->db->platform() == 'mysql') {
         # upgrade for 1.5.3
         $log_details = new stdClass();
         $log_details->file = 'system';
         $log_details->message = 'Upgrade database to 1.5.3 commenced';
         stdlog($log_details);
         $sql = "ALTER TABLE sys_sw_windows ADD windows_workgroup varchar(255) NOT NULL default '' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system ADD man_location_latitude float(10,6) NOT NULL ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system ADD man_location_longitude float(10,6) NOT NULL ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system ADD man_purchase_service_contract_number varchar(255) NOT NULL default '' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system ADD man_lease_expiry_date date NOT NULL default '0000-00-00' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE system SET type = LOWER(type)";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE system SET man_type = LOWER(man_type)";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO `oa_report` VALUES (NULL,'Enterprise - Devices Discovered in the Last Days','','n','SELECT system.system_id, system.hostname, system.man_type, system.man_os_name, system.man_ip_address, date(system.first_timestamp) as first_timestamp, date(system.timestamp) as timestamp, man_status AS status FROM system LEFT JOIN oa_group_sys ON system.system_id = oa_group_sys.system_id WHERE system.man_status = \\'production\\' and oa_group_sys.group_id = @group and system.first_timestamp > (NOW() - INTERVAL ? DAY) and system.man_ip_address <> \\'\\' and system.man_ip_address <> \\'0.0.0.0\\' and system.man_ip_address <> \\'000.000.000.000\\' GROUP BY system.system_id ORDER BY system.hostname','','v_help_oae','','',0)";
         $query = $this->db->query($sql);
         $insert_id = $this->db->insert_id();
         $sql = "INSERT INTO `oa_report_column` VALUES\n            (NULL,{$insert_id},0,'System Name','hostname','link','/omk/oae/device_details/','system_id','','left'),\n            (NULL,{$insert_id},1,'IP Address','man_ip_address','ip_address','','','','left'),\n            (NULL,{$insert_id},2,'Type','man_type','text','','','','left'),\n            (NULL,{$insert_id},3,'OS','man_os_name','text','','','','left'),\n            (NULL,{$insert_id},4,'First Audited','first_timestamp','timestamp','','','','left'),\n            (NULL,{$insert_id},5,'Last Audited','timestamp','timestamp','','','','left'),\n            (NULL,{$insert_id},6,'Status','status','text','','','','left')";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO `oa_report` VALUES (NULL,'Enterprise - Software Discovered in the Last Days','','n','SELECT COUNT(DISTINCT system.system_id) AS software_count, sys_sw_software.software_name, sys_sw_software.software_version, sys_sw_software.software_publisher, sys_sw_software.software_url, sys_sw_software.software_email, sys_sw_software.software_id, sys_sw_software.software_comment, DATE(sys_sw_software.timestamp) AS first_attribute FROM sys_sw_software LEFT JOIN system ON sys_sw_software.system_id = system.system_id WHERE system.man_status = \\'production\\' and sys_sw_software.first_timestamp != system.first_timestamp and sys_sw_software.first_timestamp > (NOW() - INTERVAL ? DAY) GROUP BY sys_sw_software.software_name, sys_sw_software.software_version ORDER BY sys_sw_software.software_name','','v_help_oae','','',0)";
         $query = $this->db->query($sql);
         $insert_id = $this->db->insert_id();
         $sql = "INSERT INTO `oa_report_column` VALUES\n            (NULL,{$insert_id},0,'Package Name','software_name','link','/omk/oae/show_report/specific software/','software_id','first_attribute','left'),\n            (NULL,{$insert_id},1,'Type','software_comment','text','','','','center'),\n            (NULL,{$insert_id},2,'Installs','software_count','text','','','','center'),\n            (NULL,{$insert_id},3,'Contact','software_url','url','','','','center'),\n            (NULL,{$insert_id},4,'Version','software_version','text','','','','left'),\n            (NULL,{$insert_id},5,'Publisher','software_publisher','text','','','','left'),\n            (NULL,{$insert_id},6,'Google Search','','url','https://encrypted.google.com/search?q=','software_name','google','center')";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO `oa_report` VALUES (NULL,'Enterprise - Devices Not Seen by Date','','n','SELECT system.system_id, system.hostname, system.man_type, oa_location.location_name, sys_sw_windows.windows_user_name, system.man_manufacturer, system.man_model, system.man_serial, date(system.first_timestamp) as first_timestamp, GREATEST(date(system.timestamp), date(system.last_seen)) as timestamp FROM system LEFT JOIN oa_group_sys ON system.system_id = oa_group_sys.system_id LEFT JOIN oa_location on system.man_location_id = oa_location.location_id LEFT JOIN sys_sw_windows ON (system.system_id = sys_sw_windows.system_id and system.timestamp = sys_sw_windows.timestamp) WHERE GREATEST(date(system.timestamp), date(system.last_seen)) < DATE_SUB(?, INTERVAL 30 day) and oa_group_sys.group_id = @group and man_status = \\'production\\' and (system.man_ip_address <> \\'\\' and system.man_ip_address <> \\'000.000.000.000\\' and system.man_ip_address <> \\'0.0.0.0\\') GROUP BY system.system_id ORDER BY system.hostname','','v_help_oae','','',0)";
         $query = $this->db->query($sql);
         $insert_id = $this->db->insert_id();
         $sql = "INSERT INTO `oa_report_column` VALUES\n            (NULL,{$insert_id},0,'System Name','hostname','link','/omk/oae/device_details/','system_id','','left'),\n            (NULL,{$insert_id},1,'Type','man_type','text','','','','left'),\n            (NULL,{$insert_id},2,'Location','location_name','text','','','','left'),\n            (NULL,{$insert_id},3,'User','windows_user_name','text','','','','left'),\n            (NULL,{$insert_id},4,'Manufacturer','man_manufacturer','text','','','','left'),\n            (NULL,{$insert_id},5,'Model','man_model','text','','','','left'),\n            (NULL,{$insert_id},6,'Serial','man_serial','text','','','','left'),\n            (NULL,{$insert_id},7,'First Audited','first_timestamp','timestamp','','','','left'),\n            (NULL,{$insert_id},8,'Last Audited','timestamp','timestamp','','','','left')";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO `oa_report` VALUES (NULL,'Enterprise - Specific Software','','n','SELECT system.system_id, system.hostname, sys_sw_software.software_id, sys_sw_software.software_name, sys_sw_software.software_installed_by, date(sys_sw_software.software_installed_on) as software_installed_on, sys_sw_software.software_version, date(sys_sw_software.first_timestamp) as first_timestamp FROM system LEFT JOIN sys_sw_software ON (system.system_id = sys_sw_software.system_id and system.first_timestamp < sys_sw_software.first_timestamp) WHERE system.man_status = \\'production\\' and sys_sw_software.software_name = (SELECT software_name FROM sys_sw_software WHERE software_id = ? LIMIT 1) and date(sys_sw_software.first_timestamp) = date(?) GROUP BY system.system_id','','v_help_oae','','',0)";
         $query = $this->db->query($sql);
         $insert_id = $this->db->insert_id();
         $sql = "INSERT INTO `oa_report_column` VALUES\n            (NULL,{$insert_id},0,'Software Name','software_name','link','/omk/oae/show_report/Specific Software/','software_id','','left'),\n            (NULL,{$insert_id},1,'System Name','hostname','link','/omk/oae/device_details/','system_id','','left'),\n            (NULL,{$insert_id},2,'Software Version','software_version','text','','','','left'),\n            (NULL,{$insert_id},3,'Detected On','first_timestamp','timestamp','','','','center'),\n            (NULL,{$insert_id},4,'Installed By','software_installed_by','text','','','','left'),\n            (NULL,{$insert_id},5,'Installed On','software_installed_on','timestamp','','','','center')";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO `oa_report` VALUES (NULL,'Enterprise - Software Discovered by Date','','n','SELECT COUNT(DISTINCT system.system_id) AS software_count, sys_sw_software.software_name, sys_sw_software.software_version, sys_sw_software.software_publisher, sys_sw_software.software_url, sys_sw_software.software_email, sys_sw_software.software_id, sys_sw_software.software_comment, date(sys_sw_software.first_timestamp) as first_attribute FROM sys_sw_software LEFT JOIN system ON (sys_sw_software.system_id = system.system_id and sys_sw_software.first_timestamp != system.first_timestamp) LEFT JOIN oa_group_sys ON system.system_id = oa_group_sys.system_id WHERE system.man_status = \\'production\\' and oa_group_sys.group_id = @group and date(sys_sw_software.first_timestamp) = ? GROUP BY sys_sw_software.software_name ORDER BY sys_sw_software.software_name','','v_help_oae','','',0)";
         $query = $this->db->query($sql);
         $insert_id = $this->db->insert_id();
         $sql = "INSERT INTO `oa_report_column` VALUES\n            (NULL,{$insert_id},0,'Package Name','software_name','link','/omk/oae/show_report/Enterprise - Specific Software/','software_id','first_attribute','left'),\n            (NULL,{$insert_id},1,'Type','software_comment','text','','','','center'),\n            (NULL,{$insert_id},2,'Installs','software_count','text','','','','center'),\n            (NULL,{$insert_id},3,'Contact','software_url','url','','','','center'),\n            (NULL,{$insert_id},4,'Version','software_version','text','','','','left'),\n            (NULL,{$insert_id},5,'Publisher','software_publisher','text','','','','left'),\n            (NULL,{$insert_id},6,'Google Search','','url','https://encrypted.google.com/search?q=','software_name','google','center')";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO `oa_report` VALUES (NULL,'Enterprise - Devices Discovered by Date','','n','SELECT system.system_id, system.hostname, system.man_type, system.man_os_name, system.man_ip_address, man_status AS status, last_seen_by FROM system WHERE system.man_status = \\'production\\' and date(system.first_timestamp) = ? and system.man_ip_address <> \\'\\' and system.man_ip_address <> \\'0.0.0.0\\' and system.man_ip_address <> \\'000.000.000.000\\' GROUP BY system.system_id ORDER BY system.hostname','','v_help_oae','','',0)";
         $query = $this->db->query($sql);
         $insert_id = $this->db->insert_id();
         $sql = "INSERT INTO `oa_report_column` VALUES\n            (NULL,{$insert_id},0,'System Name','hostname','link','/omk/oae/device_details/','system_id','','left'),\n            (NULL,{$insert_id},1,'IP Address','man_ip_address','ip_address','','','','left'),\n            (NULL,{$insert_id},2,'Type','man_type','text','','','','left'),\n            (NULL,{$insert_id},3,'OS','man_os_name','text','','','','left'),\n            (NULL,{$insert_id},5,'Last Seen By','last_seen_by','text','','','','left'),\n            (NULL,{$insert_id},6,'Status','status','text','','','','left')";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO `oa_report` VALUES (NULL,'Enterprise - Devices Not Seen in the Last Days','','n','SELECT system.system_id, system.hostname, system.man_type, oa_location.location_name, sys_sw_windows.windows_user_name, system.man_manufacturer, system.man_model, system.man_serial, date(system.first_timestamp) as first_timestamp, GREATEST(date(system.timestamp), date(system.last_seen)) as timestamp FROM system LEFT JOIN oa_group_sys ON system.system_id = oa_group_sys.system_id LEFT JOIN oa_location on system.man_location_id = oa_location.location_id LEFT JOIN sys_sw_windows ON (system.system_id = sys_sw_windows.system_id and system.timestamp = sys_sw_windows.timestamp) WHERE GREATEST(date(system.timestamp), date(system.last_seen)) < DATE_SUB(NOW(), INTERVAL ? day) and oa_group_sys.group_id = @group and man_status = \\'production\\' and (system.man_ip_address <> \\'\\' and system.man_ip_address <> \\'000.000.000.000\\' and system.man_ip_address <> \\'0.0.0.0\\') GROUP BY system.system_id ORDER BY system.hostname','','v_help_oae','','',0)";
         $query = $this->db->query($sql);
         $insert_id = $this->db->insert_id();
         $sql = "INSERT INTO `oa_report_column` VALUES\n            (NULL,{$insert_id},0,'System Name','hostname','link','/omk/oae/device_details/','system_id','','left'),\n            (NULL,{$insert_id},1,'Type','man_type','text','','','','left'),\n            (NULL,{$insert_id},2,'Location','location_name','text','','','','left'),\n            (NULL,{$insert_id},3,'User','windows_user_name','text','','','','left'),\n            (NULL,{$insert_id},4,'Manufacturer','man_manufacturer','text','','','','left'),\n            (NULL,{$insert_id},5,'Model','man_model','text','','','','left'),\n            (NULL,{$insert_id},6,'Serial','man_serial','text','','','','left'),\n            (NULL,{$insert_id},7,'First Audited','first_timestamp','timestamp','','','','left'),\n            (NULL,{$insert_id},8,'Last Audited','timestamp','timestamp','','','','left')";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO `oa_report` VALUES (NULL,'Enterprise - OS Group','','n','SELECT system.man_icon, system.man_os_family, system.hostname, system.system_id, system.man_ip_address, system.man_type, system.man_manufacturer, system.man_model, system.man_serial, system.man_os_group, system.man_os_family, oa_location.location_name FROM system LEFT JOIN oa_location ON (system.man_location_id = oa_location.location_id) WHERE man_os_group = ? and man_status = \\'production\\'','','v_help_oae','','',0)";
         $query = $this->db->query($sql);
         $insert_id = $this->db->insert_id();
         $sql = "INSERT INTO `oa_report_column` VALUES\n            (NULL,{$insert_id},0,'Icon','man_icon','image','','man_os_family','','center'),\n            (NULL,{$insert_id},1,'OS Family','man_os_family','link','/omk/oae/show_report/Enterprise - OS Family/','man_os_family','','left'),\n            (NULL,{$insert_id},2,'Hostname','hostname','link','/omk/oae/device_details/','system_id','','left'),\n            (NULL,{$insert_id},3,'IP Address','man_ip_address','ip_address','','','','left'),\n            (NULL,{$insert_id},4,'Type','man_type','text','','','','left'),\n            (NULL,{$insert_id},5,'Manufacturer','man_manufacturer','text','','','','left'),\n            (NULL,{$insert_id},6,'Model','man_model','text','','','','left'),\n            (NULL,{$insert_id},7,'Serial','man_serial','text','','','','left'),\n            (NULL,{$insert_id},8,'Location','location_name','text','','','','left')";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO `oa_report` VALUES (NULL,'Enterprise - OS Types','','n','SELECT ceiling((COUNT(*) / (SELECT COUNT(*) FROM system WHERE man_status = \\'production\\')) * 100) AS y, IF(CHAR_LENGTH(man_os_group)=0,\\'Other\\', man_os_group) AS name, count(*) as count FROM system WHERE man_status = \\'production\\' GROUP BY name;','','v_help_oae','','',0)";
         $query = $this->db->query($sql);
         $insert_id = $this->db->insert_id();
         $sql = "INSERT INTO `oa_report_column` VALUES\n            (NULL,{$insert_id},0,'Type','name','link','/omk/oae/show_report/Enterprise - OS Group/','name','','left'),\n            (NULL,{$insert_id},1,'Count','count','text','','','','left'),\n            (NULL,{$insert_id},2,'Percent','y','text','','','','left')";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO `oa_report` VALUES (NULL,'Enterprise - OS Family','','n','SELECT system.man_icon, system.man_os_family, system.hostname, system.system_id, system.man_ip_address, system.man_type, system.man_manufacturer, system.man_model, system.man_serial, system.man_os_group, system.man_os_family, system.man_os_name, oa_location.location_name FROM system LEFT JOIN oa_location ON (system.man_location_id = oa_location.location_id) WHERE man_os_family = ? and man_status = \\'production\\'','','v_help_oae','','',0)";
         $query = $this->db->query($sql);
         $insert_id = $this->db->insert_id();
         $sql = "INSERT INTO `oa_report_column` VALUES\n            (NULL,{$insert_id},0,'Icon','man_icon','image','','man_os_family','','center'),\n            (NULL,{$insert_id},1,'OS Name','man_os_name','link','/omk/oae/show_report/Enterprise - OS Name/','man_os_name','','left'),\n            (NULL,{$insert_id},2,'Hostname','hostname','link','/omk/oae/device_details/','system_id','','left'),\n            (NULL,{$insert_id},3,'IP Address','man_ip_address','ip_address','','','','left'),\n            (NULL,{$insert_id},4,'Type','man_type','text','','','','left'),\n            (NULL,{$insert_id},5,'Manufacturer','man_manufacturer','text','','','','left'),\n            (NULL,{$insert_id},6,'Model','man_model','text','','','','left'),\n            (NULL,{$insert_id},7,'Serial','man_serial','text','','','','left'),\n            (NULL,{$insert_id},8,'Location','location_name','text','','','','left')";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO `oa_report` VALUES (NULL,'Enterprise - OS Name','','n','SELECT system.man_icon, system.man_os_family, system.hostname, system.system_id, system.man_ip_address, system.man_type, system.man_manufacturer, system.man_model, system.man_serial, system.man_os_group, system.man_os_family, system.man_os_name, oa_location.location_name FROM system LEFT JOIN oa_location ON (system.man_location_id = oa_location.location_id) WHERE man_os_name = ? and man_status = \\'production\\'','','v_help_oae','','',0)";
         $query = $this->db->query($sql);
         $insert_id = $this->db->insert_id();
         $sql = "INSERT INTO `oa_report_column` VALUES\n            (NULL,{$insert_id},0,'Icon','man_icon','image','','man_os_family','','center'),\n            (NULL,{$insert_id},1,'OS Name','man_os_name','text','','','','left'),\n            (NULL,{$insert_id},2,'Hostname','hostname','link','/omk/oae/device_details/','system_id','','left'),\n            (NULL,{$insert_id},3,'IP Address','man_ip_address','ip_address','','','','left'),\n            (NULL,{$insert_id},4,'Type','man_type','text','','','','left'),\n            (NULL,{$insert_id},5,'Manufacturer','man_manufacturer','text','','','','left'),\n            (NULL,{$insert_id},6,'Model','man_model','text','','','','left'),\n            (NULL,{$insert_id},7,'Serial','man_serial','text','','','','left'),\n            (NULL,{$insert_id},8,'Location','location_name','text','','','','left')";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO `oa_report` VALUES (NULL,'Enterprise - Device Types','','n','SELECT ceiling((COUNT(*) / (SELECT COUNT(*) FROM system WHERE man_status = \\'production\\')) * 100) AS y, man_type AS name, count(*) as count FROM system WHERE man_status = \\'production\\' GROUP BY name','','v_help_oae','','',0)";
         $query = $this->db->query($sql);
         $insert_id = $this->db->insert_id();
         $sql = "INSERT INTO `oa_report_column` VALUES\n            (NULL,{$insert_id},0,'Type','name','link','/omk/oae/show_report/Enterprise - Device Type/','name','','left'),\n            (NULL,{$insert_id},1,'Count','count','text','','','','left'),\n            (NULL,{$insert_id},2,'Percent','y','text','','','','left')";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO `oa_report` VALUES (NULL,'Enterprise - Device Type','','n','SELECT system.system_id, system.hostname, system.man_manufacturer, system.man_model, system.man_os_name, system.man_ip_address, date(system.first_timestamp) as first_timestamp, date(system.timestamp) as timestamp, man_status AS status FROM system WHERE system.man_status = \\'production\\' and man_type = ?','','v_help_oae','','',0)";
         $query = $this->db->query($sql);
         $insert_id = $this->db->insert_id();
         $sql = "INSERT INTO `oa_report_column` VALUES\n            (NULL,{$insert_id},0,'System Name','hostname','link','/omk/oae/device_details/','system_id','','left'),\n            (NULL,{$insert_id},1,'IP Address','man_ip_address','ip_address','','','','left'),\n            (NULL,{$insert_id},2,'Manufacturer','man_manufacturer','text','','','','left'),\n            (NULL,{$insert_id},3,'Model','man_model','text','','','','left'),\n            (NULL,{$insert_id},4,'OS','man_os_name','text','','','','left'),\n            (NULL,{$insert_id},5,'First Audited','first_timestamp','timestamp','','','','left'),\n            (NULL,{$insert_id},6,'Last Audited','timestamp','timestamp','','','','left'),\n            (NULL,{$insert_id},7,'Status','status','text','','','','left')";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO `oa_report` VALUES (NULL,'Enterprise - Software Discovered Range','','n','SELECT COUNT(DISTINCT system.system_id) AS software_count, sys_sw_software.software_name, sys_sw_software.software_version, sys_sw_software.software_publisher, sys_sw_software.software_url, sys_sw_software.software_email, sys_sw_software.software_id, sys_sw_software.software_comment FROM sys_sw_software LEFT JOIN system ON (sys_sw_software.system_id = system.system_id and sys_sw_software.first_timestamp != system.first_timestamp) LEFT JOIN oa_group_sys ON system.system_id = oa_group_sys.system_id WHERE system.man_status = \\'production\\' and oa_group_sys.group_id = @group and date(sys_sw_software.first_timestamp) >= ? and date(sys_sw_software.first_timestamp) <= ? GROUP BY sys_sw_software.software_name, sys_sw_software.software_version ORDER BY sys_sw_software.software_name','','v_help_oae','','',0)";
         $query = $this->db->query($sql);
         $insert_id = $this->db->insert_id();
         $sql = "INSERT INTO `oa_report_column` VALUES\n            (NULL,{$insert_id},0,'Package Name','software_name','link','/omk/oae/report/SpecificSoftwareRange/','software_id','first_attribute','left'),\n            (NULL,{$insert_id},1,'Type','software_comment','text','','','','center'),\n            (NULL,{$insert_id},2,'Installs','software_count','text','','','','center'),\n            (NULL,{$insert_id},3,'Contact','software_url','url','','','','center'),\n            (NULL,{$insert_id},4,'Version','software_version','text','','','','left'),\n            (NULL,{$insert_id},5,'Publisher','software_publisher','text','','','','left'),\n            (NULL,{$insert_id},6,'Google Search','','url','https://encrypted.google.com/search?q=','software_name','google','center')";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO `oa_report` VALUES (NULL,'Enterprise - Devices Discovered Range','','n','SELECT system.system_id, system.hostname, system.man_type, system.man_os_name, system.man_ip_address, date(system.first_timestamp) as first_timestamp, date(system.timestamp) as timestamp FROM system LEFT JOIN oa_group_sys ON system.system_id = oa_group_sys.system_id and oa_group_sys.group_id = @group WHERE system.man_status = \\'production\\' and date(system.first_timestamp) >= ? and date(system.first_timestamp) <= ? and system.man_ip_address <> \\'\\' and system.man_ip_address <> \\'0.0.0.0\\' and system.man_ip_address <> \\'000.000.000.000\\' GROUP BY system.system_id ORDER BY system.hostname','','v_help_oae','','',0)";
         $query = $this->db->query($sql);
         $insert_id = $this->db->insert_id();
         $sql = "INSERT INTO `oa_report_column` VALUES\n            (NULL,{$insert_id},0,'System Name','hostname','link','/omk/oae/device_details/','system_id','','left'),\n            (NULL,{$insert_id},1,'IP Address','man_ip_address','ip_address','','','','left'),\n            (NULL,{$insert_id},2,'Type','man_type','text','','','','left'),\n            (NULL,{$insert_id},3,'OS','man_os_name','text','','','','left'),\n            (NULL,{$insert_id},4,'First Audited','first_timestamp','timestamp','','','','left'),\n            (NULL,{$insert_id},5,'Last Audited','timestamp','timestamp','','','','left')";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_config (config_name, config_value, config_editable, config_description) VALUES ('log_style', 'syslog', 'y', 'Tells Open-AudIT which log format to use. Valid values are json and syslog.')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_config (config_name, config_value, config_editable, config_description) VALUES ('log_level', '5', 'y', 'Tells Open-AudIT which severity of event (at least) should be logged.')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_group_column VALUES (NULL, 1, 3, 'Domain', 'domain', 'text', '', '', '', 'left')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_group_column SET column_order = 4 WHERE group_id = 1 and column_variable = 'man_ip_address' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_group_column SET column_order = 5 WHERE group_id = 1 and column_variable = 'man_type' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_group_column SET column_order = 6 WHERE group_id = 1 and column_variable = 'man_description' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_group_column SET column_order = 7 WHERE group_id = 1 and column_variable = 'man_os_name' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_group_column SET column_order = 8 WHERE group_id = 1 and column_variable = 'tag' ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config SET config_value = '20141225', config_editable = 'n', config_description = 'The internal numerical version.' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config SET config_value = '1.5.3', config_editable = 'n', config_description = 'The version shown on the web pages.' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $log_details->message = 'Upgrade database to 1.5.3 completed';
         stdlog($log_details);
         unset($log_details);
     }
     if ($db_internal_version < '20150227' and $this->db->platform() == 'mysql') {
         # upgrade for 1.5.5
         $log_details = new stdClass();
         $log_details->file = 'system';
         $log_details->message = 'Upgrade database to 1.5.5 commenced';
         stdlog($log_details);
         $this->load->library('encrypt');
         $this->load->model('m_oa_group');
         $configs = array('default_ipmi_password', 'default_ssh_password', 'default_snmp_community', 'default_windows_password');
         $user_id = $this->user->id;
         $timestamp = $this->config->config['timestamp'];
         foreach ($configs as $config_name) {
             $config_value = $this->m_oa_config->get_config_item($config_name);
             $this->m_oa_config->update_config($config_name, $config_value, $user_id, $timestamp);
         }
         $this->data['output'] .= "Credentials encrypted in DB.<br /><br />\n";
         $sql = "INSERT INTO oa_config (config_name, config_value, config_editable, config_description) VALUES ('page_refresh', '300', 'y', 'Interval in seconds between auto-refreshing the page. Set to 0 to canel auto-refresh.')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE system ADD man_oae_manage enum('y', 'n') NOT NULL default 'y'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         # need to alter the allowable length of a MAC Address to cope with created addresses for 'bond' adapters
         $sql = "ALTER TABLE sys_hw_network_card CHANGE net_mac_address net_mac_address varchar(200) NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_network_card_ip CHANGE net_mac_address net_mac_address varchar(200) NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_network_card ADD net_slaves varchar(100) NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         # need to edit some Enterprise SQL
         $sql = "UPDATE oa_report SET report_sql = 'SELECT system.system_id, system.hostname, system.man_manufacturer, system.man_model, system.man_os_name, system.man_ip_address, date(system.first_timestamp) as first_timestamp, date(system.timestamp) as timestamp, man_status AS status FROM system LEFT JOIN oa_group_sys ON (system.system_id = oa_group_sys.system_id) WHERE man_type = ? and oa_group_sys.group_id = @group' WHERE report_name = 'Enterprise - Device Type'";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_report SET report_sql = \"SELECT ceiling((COUNT(*) / (SELECT COUNT(*) FROM system LEFT JOIN oa_group_sys ON (system.system_id = oa_group_sys.system_id) WHERE oa_group_sys.group_id = @group)) * 100) AS y, man_type AS name, count(*) as count FROM system LEFT JOIN oa_group_sys ON (system.system_id = oa_group_sys.system_id) WHERE oa_group_sys.group_id = @group GROUP BY name\" WHERE report_name = 'Enterprise - Device Types'";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_report SET report_sql = \"SELECT system.system_id, system.hostname, system.man_type, system.man_os_name, system.man_ip_address, man_status AS status, last_seen_by FROM system LEFT JOIN oa_group_sys ON (system.system_id = oa_group_sys.system_id) WHERE oa_group_sys.group_id = @group and date(system.first_timestamp) = ? and system.man_ip_address <> '' and system.man_ip_address <> '0.0.0.0' and system.man_ip_address <> '000.000.000.000' GROUP BY system.system_id ORDER BY system.hostname\" WHERE report_name = 'Enterprise - Devices Discovered by Date'";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_report SET report_sql = \"SELECT system.system_id, system.hostname, system.man_type, system.man_os_name, system.man_ip_address, date(system.first_timestamp) as first_timestamp, date(system.timestamp) as timestamp, man_status AS status FROM system LEFT JOIN oa_group_sys ON (system.system_id = oa_group_sys.system_id) WHERE oa_group_sys.group_id = @group and system.first_timestamp > (NOW() - INTERVAL ? DAY) and system.man_ip_address <> '' and system.man_ip_address <> '0.0.0.0' and system.man_ip_address <> '000.000.000.000' GROUP BY system.system_id ORDER BY system.hostname\" WHERE report_name = 'Enterprise - Devices Discovered in the Last Days'";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_report SET report_sql = \"SELECT system.system_id, system.hostname, system.man_type, system.man_os_name, system.man_ip_address, date(system.first_timestamp) as first_timestamp, date(system.timestamp) as timestamp FROM system LEFT JOIN oa_group_sys ON (system.system_id = oa_group_sys.system_id) WHERE oa_group_sys.group_id = @group and date(system.first_timestamp) >= ? and date(system.first_timestamp) <= ? and system.man_ip_address <> '' and system.man_ip_address <> '0.0.0.0' and system.man_ip_address <> '000.000.000.000' GROUP BY system.system_id ORDER BY system.hostname\" WHERE report_name = 'Enterprise - Devices Discovered Range'";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_report SET report_sql = \"SELECT system.system_id, system.hostname, system.man_type, oa_location.location_name, sys_sw_windows.windows_user_name, system.man_manufacturer, system.man_model, system.man_serial, date(system.first_timestamp) as first_timestamp, GREATEST(date(system.timestamp), date(system.last_seen)) as timestamp FROM system LEFT JOIN oa_group_sys ON (system.system_id = oa_group_sys.system_id) LEFT JOIN oa_location ON (system.man_location_id = oa_location.location_id) LEFT JOIN sys_sw_windows ON (system.system_id = sys_sw_windows.system_id and system.timestamp = sys_sw_windows.timestamp) WHERE GREATEST(date(system.timestamp), date(system.last_seen)) < DATE_SUB(?, INTERVAL 30 day) and oa_group_sys.group_id = @group and (system.man_ip_address <> '' and system.man_ip_address <> '000.000.000.000' and system.man_ip_address <> '0.0.0.0') GROUP BY system.system_id ORDER BY system.hostname\" WHERE report_name = 'Enterprise - Devices Not Seen by Date'";
         $query = $this->db->query($sql);
         #$sql = "UPDATE oa_report SET report_sql = \"SELECT system.system_id, system.hostname, system.man_type, oa_location.location_name, sys_sw_windows.windows_user_name, system.man_manufacturer, system.man_model, system.man_serial, date(system.first_timestamp) as first_timestamp, GREATEST(date(system.timestamp), date(system.last_seen)) as timestamp FROM system LEFT JOIN oa_group_sys ON (system.system_id = oa_group_sys.system_id) LEFT JOIN oa_location ON (system.man_location_id = oa_location.location_id) LEFT JOIN sys_sw_windows ON (system.system_id = sys_sw_windows.system_id and system.timestamp = sys_sw_windows.timestamp) WHERE GREATEST(date(system.timestamp), date(system.last_seen)) < DATE_SUB(?, INTERVAL ? day) and oa_group_sys.group_id = @group and (system.man_ip_address <> '' and system.man_ip_address <> '000.000.000.000' and system.man_ip_address <> '0.0.0.0') GROUP BY system.system_id ORDER BY system.hostname\" WHERE report_name = 'Enterprise - Devices Not Seen in the Last Days From'";
         #$query = $this->db->query($sql);
         $sql = "UPDATE oa_report SET report_sql = \"SELECT system.system_id, system.hostname, system.man_type, oa_location.location_name, sys_sw_windows.windows_user_name, system.man_manufacturer, system.man_model, system.man_serial, date(system.first_timestamp) as first_timestamp, GREATEST(date(system.timestamp), date(system.last_seen)) as timestamp FROM system LEFT JOIN oa_group_sys ON (system.system_id = oa_group_sys.system_id) LEFT JOIN oa_location ON (system.man_location_id = oa_location.location_id) LEFT JOIN sys_sw_windows ON (system.system_id = sys_sw_windows.system_id and system.timestamp = sys_sw_windows.timestamp) WHERE GREATEST(date(system.timestamp), date(system.last_seen)) < DATE_SUB(NOW(), INTERVAL ? day) and oa_group_sys.group_id = @group and (system.man_ip_address <> '' and system.man_ip_address <> '000.000.000.000' and system.man_ip_address <> '0.0.0.0') GROUP BY system.system_id ORDER BY system.hostname\" WHERE report_name = 'Enterprise - Devices Not Seen in the Last Days'";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_report SET report_sql = \"SELECT system.man_icon, system.man_os_family, system.hostname, system.system_id, system.man_ip_address, system.man_type, system.man_manufacturer, system.man_model, system.man_serial, system.man_os_group, system.man_os_family, system.man_os_name, oa_location.location_name FROM system LEFT JOIN oa_location ON (system.man_location_id = oa_location.location_id) LEFT JOIN oa_group_sys ON (system.system_id = oa_group_sys.system_id) WHERE oa_group_sys.group_id = @group and man_os_family = ?\" WHERE report_name = 'Enterprise - OS Family'";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_report SET report_sql = \"SELECT system.man_icon, system.man_os_family, system.hostname, system.system_id, system.man_ip_address, system.man_type, system.man_manufacturer, system.man_model, system.man_serial, system.man_os_group, system.man_os_family, oa_location.location_name FROM system LEFT JOIN oa_location ON (system.man_location_id = oa_location.location_id) LEFT JOIN oa_group_sys ON (system.system_id = oa_group_sys.system_id) WHERE oa_group_sys.group_id = @group and man_os_group = ?\" WHERE report_name = 'Enterprise - OS Group'";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_report SET report_sql = \"SELECT system.man_icon, system.man_os_family, system.hostname, system.system_id, system.man_ip_address, system.man_type, system.man_manufacturer, system.man_model, system.man_serial, system.man_os_group, system.man_os_family, system.man_os_name, oa_location.location_name FROM system LEFT JOIN oa_location ON (system.man_location_id = oa_location.location_id) LEFT JOIN oa_group_sys ON (system.system_id = oa_group_sys.system_id) WHERE oa_group_sys.group_id = @group and man_os_name = ?\" WHERE report_name = 'Enterprise - OS Name'";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_report SET report_sql = \"SELECT ceiling((COUNT(*) / (SELECT COUNT(*) FROM system LEFT JOIN oa_group_sys ON (system.system_id = oa_group_sys.system_id) WHERE oa_group_sys.group_id = @group)) * 100) AS y, IF(CHAR_LENGTH(man_os_group)=0,'Other', man_os_group) AS name, count(*) as count FROM system LEFT JOIN oa_group_sys ON (system.system_id = oa_group_sys.system_id) WHERE oa_group_sys.group_id = @group GROUP BY name\" WHERE report_name = 'Enterprise - OS Types'";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_report SET report_sql = \"SELECT COUNT(DISTINCT system.system_id) AS software_count, sys_sw_software.software_name, sys_sw_software.software_version, sys_sw_software.software_publisher, sys_sw_software.software_url, sys_sw_software.software_email, sys_sw_software.software_id, sys_sw_software.software_comment, date(sys_sw_software.first_timestamp) as first_attribute FROM sys_sw_software LEFT JOIN system ON (sys_sw_software.system_id = system.system_id and sys_sw_software.first_timestamp != system.first_timestamp) LEFT JOIN oa_group_sys ON (system.system_id = oa_group_sys.system_id) WHERE oa_group_sys.group_id = @group and date(sys_sw_software.first_timestamp) = ? GROUP BY sys_sw_software.software_name ORDER BY sys_sw_software.software_name\" WHERE report_name = 'Enterprise - Software Discovered by Date'";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_report SET report_sql = \"SELECT COUNT(DISTINCT system.system_id) AS software_count, sys_sw_software.software_name, sys_sw_software.software_version, sys_sw_software.software_publisher, sys_sw_software.software_url, sys_sw_software.software_email, sys_sw_software.software_id, sys_sw_software.software_comment, DATE(sys_sw_software.timestamp) AS first_attribute FROM sys_sw_software LEFT JOIN system ON sys_sw_software.system_id = system.system_id LEFT JOIN oa_group_sys ON (system.system_id = oa_group_sys.system_id) WHERE oa_group_sys.group_id = @group and sys_sw_software.first_timestamp != system.first_timestamp and sys_sw_software.first_timestamp > (NOW() - INTERVAL ? DAY) GROUP BY sys_sw_software.software_name, sys_sw_software.software_version ORDER BY sys_sw_software.software_name\" WHERE report_name = 'Enterprise - Software Discovered in the Last Days'";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_report SET report_sql = \"SELECT COUNT(DISTINCT system.system_id) AS software_count, sys_sw_software.software_name, sys_sw_software.software_version, sys_sw_software.software_publisher, sys_sw_software.software_url, sys_sw_software.software_email, sys_sw_software.software_id, sys_sw_software.software_comment FROM sys_sw_software LEFT JOIN system ON (sys_sw_software.system_id = system.system_id and sys_sw_software.first_timestamp != system.first_timestamp) LEFT JOIN oa_group_sys ON (system.system_id = oa_group_sys.system_id) WHERE oa_group_sys.group_id = @group and date(sys_sw_software.first_timestamp) >= ? and date(sys_sw_software.first_timestamp) <= ? GROUP BY sys_sw_software.software_name, sys_sw_software.software_version ORDER BY sys_sw_software.software_name\" WHERE report_name = 'Enterprise - Software Discovered Range'";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_report SET report_sql = \"SELECT system.system_id, system.hostname, sys_sw_software.software_id, sys_sw_software.software_name, sys_sw_software.software_installed_by, date(sys_sw_software.software_installed_on) as software_installed_on, sys_sw_software.software_version, date(sys_sw_software.first_timestamp) as first_timestamp FROM system LEFT JOIN sys_sw_software ON (system.system_id = sys_sw_software.system_id and system.first_timestamp < sys_sw_software.first_timestamp) LEFT JOIN oa_group_sys ON (system.system_id = oa_group_sys.system_id) WHERE oa_group_sys.group_id = @group and sys_sw_software.software_name = (SELECT software_name FROM sys_sw_software WHERE software_id = ? LIMIT 1) and date(sys_sw_software.first_timestamp) = date(?) GROUP BY system.system_id\" WHERE report_name = 'Enterprise - Specific Software'";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_report SET report_sql = \"SELECT COUNT(key_text) as count, key_name, key_text, key_id FROM system LEFT JOIN oa_group_sys ON system.system_id = oa_group_sys.system_id LEFT JOIN sys_sw_software_key ON (sys_sw_software_key.system_id = system.system_id and sys_sw_software_key.timestamp = system.timestamp) WHERE oa_group_sys.group_id = @group and key_text IS NOT NULL GROUP BY key_name, key_text ORDER BY key_name\" WHERE report_name = 'Software Keys'";
         $query = $this->db->query($sql);
         $sql = "CREATE TABLE sys_hw_module ( id int(10) unsigned NOT NULL auto_increment, system_id int(10) unsigned default NULL, description varchar(200) NOT NULL default '', module_index varchar(100) NOT NULL default '', object_id varchar(100) NOT NULL default '', contained_in varchar(100) NOT NULL default '', class varchar(10) NOT NULL default '', class_text varchar(20) NOT NULL, hardware_revision varchar(100) NOT NULL, firmware_revision varchar(100) NOT NULL default '', software_revision varchar(100) NOT NULL default '', serial_number varchar(100) NOT NULL default '', asset_id varchar(100) NOT NULL default '', is_fru varchar(100) NOT NULL default '', timestamp datetime NOT NULL default '0000-00-00 00:00:00', first_timestamp datetime NOT NULL default '0000-00-00 00:00:00', PRIMARY KEY (id), KEY system_id (system_id), CONSTRAINT sys_hw_module_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config SET config_value = '20150227' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config SET config_value = '1.5.5' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $log_details->message = 'Upgrade database to 1.5.5 completed';
         stdlog($log_details);
         unset($log_details);
     }
     if ($db_internal_version < '20150303' and $this->db->platform() == 'mysql') {
         # upgrade for 1.6
         $log_details = new stdClass();
         $log_details->file = 'system';
         $log_details->message = 'Upgrade database to 1.6 commenced';
         stdlog($log_details);
         $sql = "INSERT INTO oa_config (config_name, config_value, config_editable, config_description) VALUES ('oae_license_status', '', 'n', 'License status of Open-AudIT Enterprise.')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config SET config_value = CONCAT('logo-banner-', config_value) WHERE config_name = 'logo'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config SET config_editable = 'y', config_description = 'The logo to be used in Open-AudIT. Should be a 475x60 .png. Name should not include the file extension. logo-banner-oac-oae is the default.' WHERE config_name = 'logo'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config SET config_value = '20150303' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config SET config_value = '1.6' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $log_details->message = 'Upgrade database to 1.6 completed';
         stdlog($log_details);
         unset($log_details);
     }
     if ($db_internal_version < '20150318' and $this->db->platform() == 'mysql') {
         # upgrade for 1.6.2
         $log_details = new stdClass();
         $log_details->file = 'system';
         $log_details->message = 'Upgrade database to 1.6.2 commenced';
         stdlog($log_details);
         $sql = "UPDATE oa_report SET report_sql = 'SELECT system.system_id, system.hostname, system.man_type, oa_location.location_name, sys_sw_windows.windows_user_name, system.man_manufacturer, system.man_model, system.man_serial, date(system.first_timestamp) as first_timestamp, GREATEST(date(system.timestamp), date(system.last_seen)) as timestamp FROM system LEFT JOIN oa_group_sys ON (system.system_id = oa_group_sys.system_id) LEFT JOIN oa_location ON (system.man_location_id = oa_location.location_id) LEFT JOIN sys_sw_windows ON (system.system_id = sys_sw_windows.system_id AND system.timestamp = sys_sw_windows.timestamp) WHERE GREATEST(date(system.timestamp), date(system.last_seen)) < DATE_SUB(NOW(), INTERVAL ? day) AND oa_group_sys.group_id = @group AND (system.man_ip_address <> \"\" AND system.man_ip_address <> \"000.000.000.000\" AND system.man_ip_address <> \"0.0.0.0\") GROUP BY system.system_id ORDER BY system.hostname' WHERE report_name = 'Enterprise - Devices Not Seen in the Last Days'";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config SET config_value = '20150318' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config SET config_value = '1.6.2' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $log_details->message = 'Upgrade database to 1.6.2 completed';
         stdlog($log_details);
         unset($log_details);
     }
     if ($db_internal_version < '20150404' and $this->db->platform() == 'mysql') {
         # upgrade for 1.6.4
         $log_details = new stdClass();
         $log_details->file = 'system';
         $log_details->message = 'Upgrade database to 1.6.4 commenced';
         stdlog($log_details);
         $sql = "UPDATE oa_config SET config_value = 'logo-banner-oac-oae' WHERE config_name = 'logo'";
         $query = $this->db->query($sql);
         $sql = "SELECT report_id FROM oa_report WHERE report_name = 'Enterprise - Software Discovered Range'";
         $query = $this->db->query($sql);
         $row = $query->row();
         if (isset($row->report_id) and $row->report_id != '' and $row->report_id != '0') {
             $sql = "UPDATE oa_report_column SET column_link = '/omk/oae/show_report/Specific Software/' WHERE column_order = 0 AND report_id = " . $row->report_id;
             $query = $this->db->query($sql);
         }
         $sql = "UPDATE oa_config SET config_value = '20150404' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config SET config_value = '1.6.4' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $log_details->message = 'Upgrade database to 1.6.4 completed';
         stdlog($log_details);
         unset($log_details);
     }
     if ($db_internal_version < '20150512' and $this->db->platform() == 'mysql') {
         # upgrade for 1.8
         $log_details = new stdClass();
         $log_details->file = 'system';
         $log_details->message = 'Upgrade database to 1.8 commenced';
         stdlog($log_details);
         $sql = "INSERT INTO oa_config (config_name, config_value, config_editable, config_description) VALUES ('network_group_subnet', '30', 'y', 'If the netmask is equal to or greater than this number, do not create a network group.')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_name = 'network_group_auto_create' WHERE config_name = 'auto_create_network_groups'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_description = 'The domain name against which your users will validate to log on to Open-AudIT. EG - open-audit.org' WHERE config_name = 'ad_domain'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_description = 'The IP Address of the domain controller your users will validate to log to Open-AudIT. EG - 192.168.0.1' WHERE config_name = 'ad_server'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config set config_description = 'Interval in seconds between auto-refreshing the page. Set to 0 to cancel auto-refresh.' WHERE config_name = 'page_refresh'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_config (config_name, config_value, config_editable, config_description) VALUES ('network_group_homepage_limit', '20', 'y', 'The number of network groups to display on the homepage.')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_network_card ADD ifadminstatus varchar(100) NOT NULL default ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_hw_network_card ADD iflastchange bigint NOT NULL default '0'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config SET config_value = '20150512' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config SET config_value = '1.8' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $log_details->message = 'Upgrade database to 1.8 completed';
         stdlog($log_details);
         unset($log_details);
     }
     if ($db_internal_version < '20150610' and $this->db->platform() == 'mysql') {
         # upgrade for 1.8.1
         $log_details = new stdClass();
         $log_details->file = 'system';
         $log_details->message = 'Upgrade database to 1.8.1 commenced';
         stdlog($log_details);
         $sql = 'UPDATE oa_report_column SET column_link = "/report/specific_software/$group_id/" WHERE column_link = "/report/Specific Software/$group_id/"';
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config SET config_value = '20150610' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config SET config_value = '1.8.1' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $log_details->message = 'Upgrade database to 1.8.1 completed';
         stdlog($log_details);
         unset($log_details);
     }
     if ($db_internal_version < '20150620' and $this->db->platform() == 'mysql') {
         # upgrade for 1.8.2
         $log_details = new stdClass();
         $log_details->file = 'system';
         $log_details->message = 'Upgrade database to 1.8.2 commenced';
         stdlog($log_details);
         $sql = "INSERT INTO oa_config (config_name, config_value, config_editable, config_description) VALUES ('oae_prompt', '2015-06-01', 'n', 'Prompt to activate a license for Open-AudIT Enterprise.')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_config (config_name, config_value, config_editable, config_description) VALUES ('discovery_create_alerts', 'y', 'y', 'Should Open-AudIT create an entry in the alert table if a change is detected.')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_config (config_name, config_value, config_editable, config_description) VALUES ('discovery_update_groups', 'y', 'y', 'Should Open-AudIT update the device groups after discovering a device.')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config SET config_name = 'oae_license' WHERE config_name = 'oae_license_status'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config SET config_name = 'discovery_name_match', config_description = 'Should we match a device based only on its hostname during discovery.' WHERE config_name = 'name_match'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_config VALUES ('discovery_ip_match','n','y','0000-00-00 00:00:00',0,'Should we match a device based only on its ip during discovery.')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "INSERT INTO oa_config VALUES ('discovery_use_ipmi','y','y','0000-00-00 00:00:00',0,'Should we use ipmitool for discovering management ports if ipmitool is installed.')";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "CREATE INDEX net_index ON sys_hw_network_card (net_index) ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "CREATE INDEX `timestamp` ON sys_hw_network_card (`timestamp`) ";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         # Activate a couple of reports
         $this->load->model('m_oa_report');
         $this->load->model('m_oa_report_column');
         $sql = "SELECT report_name from oa_report";
         $query = $this->db->query($sql);
         $result = $query->result();
         $activate_disk = 'y';
         $activate_interfaces = 'y';
         foreach ($result as $key => $value) {
             if ($value == 'Disk Partition Use') {
                 $activate_disk = 'n';
             }
             if ($value == 'Interfaces Used - Available') {
                 $activate_interfaces = 'n';
             }
         }
         # The Disk Partition Use report
         if ($activate_disk == 'y') {
             $file_report = BASEPATH . '../application/controllers/reports/DiskPartitionUse.xml';
             $file_handle = fopen($file_report, "rb");
             $contents = fread($file_handle, filesize($file_report));
             $xml = new SimpleXMLElement(utf8_encode($contents));
             foreach ($xml->children() as $child) {
                 if ($child->getName() == 'details') {
                     $report_id = $this->m_oa_report->import_report($child);
                 }
                 if ($child->getName() == 'columns') {
                     $this->m_oa_report_column->import_report($child, $report_id);
                 }
             }
         }
         # The Interfaces Used / Available report
         if ($activate_interfaces == 'y') {
             $file_report = BASEPATH . '../application/controllers/reports/InterfacesUsed-Available.xml';
             $file_handle = fopen($file_report, "rb");
             $contents = fread($file_handle, filesize($file_report));
             $xml = new SimpleXMLElement(utf8_encode($contents));
             foreach ($xml->children() as $child) {
                 if ($child->getName() == 'details') {
                     $report_id = $this->m_oa_report->import_report($child);
                 }
                 if ($child->getName() == 'columns') {
                     $this->m_oa_report_column->import_report($child, $report_id);
                 }
             }
         }
         $sql = "UPDATE oa_report SET report_sql = 'SELECT system.system_id, system.hostname, system.man_type, system.man_manufacturer, system.man_model, system.man_os_name, system.man_ip_address, date(system.first_timestamp) as first_timestamp, date(system.timestamp) as timestamp, man_status AS status FROM system INNER JOIN (SELECT oa_group_sys.system_id FROM oa_group_sys LEFT JOIN system on oa_group_sys.system_id = system.system_id WHERE group_id = @group ORDER BY system.system_id LIMIT @limit) AS grp ON system.system_id = grp.system_id WHERE man_type = ?' WHERE report_name = 'Enterprise - Device Type'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_report SET report_sql = 'SELECT CEILING(COUNT(*) / (SELECT COUNT(system.system_id) FROM system INNER JOIN (SELECT oa_group_sys.system_id FROM oa_group_sys LEFT JOIN system on oa_group_sys.system_id = system.system_id WHERE group_id = @group ORDER BY system.system_id LIMIT @limit) AS grp ON system.system_id = grp.system_id) * 100) AS y, man_type AS name, count(*) as count FROM system INNER JOIN (SELECT oa_group_sys.system_id FROM oa_group_sys LEFT JOIN system on oa_group_sys.system_id = system.system_id WHERE group_id = @group ORDER BY system.system_id LIMIT @limit) AS grp2 ON system.system_id = grp2.system_id GROUP BY name' WHERE report_name = 'Enterprise - Device Types'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_report SET report_sql = 'SELECT system.system_id, system.hostname, system.man_type, system.man_os_name, system.man_ip_address, man_status AS status, last_seen_by FROM system LEFT JOIN oa_group_sys ON system.system_id = oa_group_sys.system_id WHERE oa_group_sys.group_id = @group AND date(system.first_timestamp) = ? AND system.man_ip_address <> \\'\\' AND system.man_ip_address <> \\'0.0.0.0\\' AND system.man_ip_address <> \\'000.000.000.000\\' GROUP BY system.system_id ORDER BY system.hostname LIMIT @limit' WHERE report_name = 'Enterprise - Devices Discovered by Date'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_report SET report_sql = 'SELECT system.system_id, system.hostname, system.man_type, system.man_os_name, system.man_ip_address, date(system.first_timestamp) as first_timestamp, date(system.timestamp) as timestamp, man_status AS status FROM system INNER JOIN (SELECT oa_group_sys.system_id FROM oa_group_sys LEFT JOIN system on oa_group_sys.system_id = system.system_id WHERE group_id = @group ORDER BY system.system_id LIMIT @limit) AS grp ON system.system_id = grp.system_id WHERE system.first_timestamp > (NOW() - INTERVAL ? DAY) AND system.man_ip_address <> \\'\\' AND system.man_ip_address <> \\'0.0.0.0\\' AND system.man_ip_address <> \\'000.000.000.000\\' GROUP BY system.system_id ORDER BY system.hostname' WHERE report_name = 'Enterprise - Devices Discovered in the Last Days'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_report SET report_sql = 'SELECT system.system_id, system.hostname, system.man_type, system.man_os_name, system.man_ip_address, date(system.first_timestamp) as first_timestamp, date(system.timestamp) as timestamp FROM system INNER JOIN (SELECT oa_group_sys.system_id FROM oa_group_sys LEFT JOIN system on oa_group_sys.system_id = system.system_id WHERE group_id = @group ORDER BY system.system_id LIMIT @limit) AS grp ON system.system_id = grp.system_id WHERE date(system.first_timestamp) >= ? AND date(system.first_timestamp) <= ? AND system.man_ip_address <> \\'\\' AND system.man_ip_address <> \\'0.0.0.0\\' AND system.man_ip_address <> \\'000.000.000.000\\' GROUP BY system.system_id ORDER BY system.hostname' WHERE report_name = 'Enterprise - Devices Discovered Range'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_report SET report_sql = 'SELECT system.system_id, system.hostname, system.man_type, oa_location.location_name, sys_sw_windows.windows_user_name, system.man_manufacturer, system.man_model, system.man_serial, date(system.first_timestamp) as first_timestamp, GREATEST(date(system.timestamp), date(system.last_seen)) as timestamp FROM system INNER JOIN (SELECT oa_group_sys.system_id FROM oa_group_sys LEFT JOIN system on oa_group_sys.system_id = system.system_id WHERE group_id = @group ORDER BY system.system_id LIMIT @limit) AS grp ON system.system_id = grp.system_id  LEFT JOIN oa_location ON (system.man_location_id = oa_location.location_id) LEFT JOIN sys_sw_windows ON (system.system_id = sys_sw_windows.system_id AND system.timestamp = sys_sw_windows.timestamp) WHERE GREATEST(date(system.timestamp), date(system.last_seen)) < DATE_SUB(?, INTERVAL 30 day) AND (system.man_ip_address <> \\'\\' AND system.man_ip_address <> \\'000.000.000.000\\' AND system.man_ip_address <> \\'0.0.0.0\\') GROUP BY system.system_id ORDER BY system.hostname' WHERE report_name = 'Enterprise - Devices Not Seen by Date'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_report SET report_sql = 'SELECT system.system_id, system.hostname, system.man_type, oa_location.location_name, sys_sw_windows.windows_user_name, system.man_manufacturer, system.man_model, system.man_serial, date(system.first_timestamp) as first_timestamp, GREATEST(date(system.timestamp), date(system.last_seen)) as timestamp FROM system INNER JOIN (SELECT oa_group_sys.system_id FROM oa_group_sys LEFT JOIN system on oa_group_sys.system_id = system.system_id WHERE group_id = @group ORDER BY system.system_id LIMIT @limit) AS grp ON system.system_id = grp.system_id LEFT JOIN oa_location ON (system.man_location_id = oa_location.location_id) LEFT JOIN sys_sw_windows ON (system.system_id = sys_sw_windows.system_id AND system.timestamp = sys_sw_windows.timestamp) WHERE GREATEST(date(system.timestamp), date(system.last_seen)) < DATE_SUB(?, INTERVAL ? day) AND (system.man_ip_address <> \\'\\' AND system.man_ip_address <> \\'000.000.000.000\\' AND system.man_ip_address <> \\'0.0.0.0\\') GROUP BY system.system_id ORDER BY system.hostname' WHERE report_name = 'Enterprise - Devices Not Seen in the Last Days From'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_report SET report_sql = 'SELECT system.man_icon, system.man_os_family, system.hostname, system.system_id, system.man_ip_address, system.man_type, system.man_manufacturer, system.man_model, system.man_serial, system.man_os_group, system.man_os_family, system.man_os_name, oa_location.location_name FROM system LEFT JOIN oa_location ON (system.man_location_id = oa_location.location_id) INNER JOIN (SELECT oa_group_sys.system_id FROM oa_group_sys LEFT JOIN system on oa_group_sys.system_id = system.system_id WHERE group_id = @group ORDER BY system.system_id LIMIT @limit) AS grp ON system.system_id = grp.system_id WHERE man_os_family = ?' WHERE report_name = 'Enterprise - OS Family'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_report SET report_sql = 'SELECT system.man_icon, system.man_os_family, system.hostname, system.system_id, system.man_ip_address, system.man_type, system.man_manufacturer, system.man_model, system.man_serial, system.man_os_group, system.man_os_family, oa_location.location_name FROM system LEFT JOIN oa_location ON (system.man_location_id = oa_location.location_id) INNER JOIN (SELECT oa_group_sys.system_id FROM oa_group_sys LEFT JOIN system on oa_group_sys.system_id = system.system_id WHERE group_id = @group ORDER BY system.system_id LIMIT @limit) AS grp ON system.system_id = grp.system_id WHERE man_os_group = ?' WHERE report_name = 'Enterprise - OS Group'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_report SET report_sql = 'SELECT system.man_icon, system.man_os_family, system.hostname, system.system_id, system.man_ip_address, system.man_type, system.man_manufacturer, system.man_model, system.man_serial, system.man_os_group, system.man_os_family, system.man_os_name, oa_location.location_name FROM system LEFT JOIN oa_location ON (system.man_location_id = oa_location.location_id) INNER JOIN (SELECT oa_group_sys.system_id FROM oa_group_sys LEFT JOIN system on oa_group_sys.system_id = system.system_id WHERE group_id = @group ORDER BY system.system_id LIMIT @limit) AS grp ON system.system_id = grp.system_id WHERE man_os_name = ?' WHERE report_name = 'Enterprise - OS Name'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_report SET report_sql = 'SELECT ceiling((COUNT(*) / (SELECT COUNT(*) FROM system INNER JOIN (SELECT oa_group_sys.system_id FROM oa_group_sys LEFT JOIN system on oa_group_sys.system_id = system.system_id WHERE group_id = @group ORDER BY system.system_id LIMIT @limit) AS grp ON system.system_id = grp.system_id)) * 100) AS y, IF(CHAR_LENGTH(man_os_group)=0,\\'Other\\', man_os_group) AS name, count(*) as count FROM system INNER JOIN (SELECT oa_group_sys.system_id FROM oa_group_sys LEFT JOIN system on oa_group_sys.system_id = system.system_id WHERE group_id = @group ORDER BY system.system_id LIMIT @limit) AS grp ON system.system_id = grp.system_id GROUP BY name' WHERE report_name = 'Enterprise - OS Types'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_report SET report_sql = 'SELECT COUNT(DISTINCT system.system_id) AS software_count, sys_sw_software.software_name, sys_sw_software.software_version, sys_sw_software.software_publisher, sys_sw_software.software_url, sys_sw_software.software_email, sys_sw_software.software_id, sys_sw_software.software_comment, date(sys_sw_software.first_timestamp) as first_attribute FROM sys_sw_software LEFT JOIN system ON (sys_sw_software.system_id = system.system_id AND sys_sw_software.first_timestamp != system.first_timestamp) LEFT JOIN (SELECT oa_group_sys.system_id FROM oa_group_sys LEFT JOIN system on oa_group_sys.system_id = system.system_id WHERE group_id = @group ORDER BY system.system_id LIMIT @limit) AS grp ON system.system_id = grp.system_id WHERE date(sys_sw_software.first_timestamp) = ? GROUP BY sys_sw_software.software_name, sys_sw_software.software_version ORDER BY sys_sw_software.software_name' WHERE report_name = 'Enterprise - Software Discovered by Date'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_report SET report_sql = 'SELECT COUNT(DISTINCT system.system_id) AS software_count, sys_sw_software.software_name, sys_sw_software.software_version, sys_sw_software.software_publisher, sys_sw_software.software_url, sys_sw_software.software_email, sys_sw_software.software_id, sys_sw_software.software_comment, DATE(sys_sw_software.timestamp) AS first_attribute FROM sys_sw_software LEFT JOIN system ON sys_sw_software.system_id = system.system_id INNER JOIN (SELECT oa_group_sys.system_id FROM oa_group_sys LEFT JOIN system on oa_group_sys.system_id = system.system_id WHERE group_id = @group ORDER BY system.system_id LIMIT @limit) AS grp ON system.system_id = grp.system_id WHERE sys_sw_software.first_timestamp != system.first_timestamp AND sys_sw_software.first_timestamp > (NOW() - INTERVAL ? DAY) GROUP BY sys_sw_software.software_name, sys_sw_software.software_version ORDER BY sys_sw_software.software_name' WHERE report_name = 'Enterprise - Software Discovered in the Last Days'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_report SET report_sql = 'SELECT COUNT(DISTINCT system.system_id) AS software_count, sys_sw_software.software_name, sys_sw_software.software_version, sys_sw_software.software_publisher, sys_sw_software.software_url, sys_sw_software.software_email, sys_sw_software.software_id, sys_sw_software.software_comment FROM sys_sw_software LEFT JOIN system ON (sys_sw_software.system_id = system.system_id AND sys_sw_software.first_timestamp != system.first_timestamp) INNER JOIN (SELECT oa_group_sys.system_id FROM oa_group_sys LEFT JOIN system on oa_group_sys.system_id = system.system_id WHERE group_id = @group ORDER BY system.system_id LIMIT @limit) AS grp ON system.system_id = grp.system_id WHERE date(sys_sw_software.first_timestamp) >= ? AND date(sys_sw_software.first_timestamp) <= ? GROUP BY sys_sw_software.software_name, sys_sw_software.software_version ORDER BY sys_sw_software.software_name' WHERE report_name = 'Enterprise - Software Discovered Range'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_report SET report_sql = 'SELECT system.system_id, system.hostname, sys_sw_software.software_id, sys_sw_software.software_name, sys_sw_software.software_installed_by, date(sys_sw_software.software_installed_on) as software_installed_on, sys_sw_software.software_version, date(sys_sw_software.first_timestamp) as first_timestamp FROM system LEFT JOIN sys_sw_software ON (system.system_id = sys_sw_software.system_id and system.first_timestamp < sys_sw_software.first_timestamp) INNER JOIN (SELECT oa_group_sys.system_id FROM oa_group_sys LEFT JOIN system on oa_group_sys.system_id = system.system_id WHERE group_id = @group ORDER BY system.system_id LIMIT @limit) AS grp ON system.system_id = grp.system_id WHERE sys_sw_software.software_name = (SELECT software_name FROM sys_sw_software WHERE software_id = ? LIMIT 1) AND date(sys_sw_software.first_timestamp) = date(?) GROUP BY system.system_id' WHERE report_name = 'Enterprise - Specific Software'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_group_sys DROP group_sys_type";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE sys_sw_service CHANGE service_start_mode service_start_mode varchar(100) NOT NULL DEFAULT ''";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config SET config_value = '20150620' WHERE config_name = 'internal_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_config SET config_value = '1.8.2' WHERE config_name = 'display_version'";
         $this->data['output'] .= $sql . "<br /><br />\n";
         $query = $this->db->query($sql);
         $log_details->message = 'Upgrade database to 1.8.2 completed';
         stdlog($log_details);
         unset($log_details);
     }
     if ($db_internal_version < '20151112' and $this->db->platform() == 'mysql') {
         # upgrade for 1.8.4
         $log_details = new stdClass();
         $log_details->file = 'system';
         $log_details->message = 'Upgrade database to 1.8.4 commenced';
         stdlog($log_details);
         $sql = array();
         $sql[] = "ALTER TABLE sys_sw_service MODIFY service_start_mode varchar(200) NOT NULL default ''";
         $sql[] = "ALTER TABLE sys_sw_service MODIFY service_state varchar(200) NOT NULL default ''";
         $sql[] = "DELETE FROM oa_config WHERE config_name = 'discovery_ip_exclude'";
         $sql[] = "INSERT INTO oa_config (config_name, config_value, config_editable, config_description) VALUES ('discovery_ip_exclude', '', 'y', 'Populate this list with ip addresses to be excluded from discovery. IPs should be separated by a space.')";
         $sql[] = "UPDATE oa_config SET config_value = '20151112' WHERE config_name = 'internal_version'";
         $sql[] = "UPDATE oa_config SET config_value = '1.8.4' WHERE config_name = 'display_version'";
         foreach ($sql as $this_query) {
             $this->data['output'] .= $this_query . "<br /><br />\n";
             $log_details->message = $this_query;
             stdlog($log_details);
             $query = $this->db->query($this_query);
         }
         $log_details->message = 'Upgrade database to 1.8.4 completed';
         stdlog($log_details);
         unset($log_details);
     }
     if ($db_internal_version < '20160104' and $this->db->platform() == 'mysql') {
         # upgrade for 1.10
         $log_details = new stdClass();
         $log_details->file = 'system';
         $log_details->message = 'Upgrade database to 1.10 commenced';
         stdlog($log_details);
         $sql = array();
         # We know these tables aren't used - drop them
         $sql[] = "DROP TABLE IF EXISTS oa_change_log";
         $sql[] = "DROP TABLE IF EXISTS oa_contact";
         $sql[] = "DROP TABLE IF EXISTS oa_location_org";
         $sql[] = "DROP TABLE IF EXISTS oa_asset_line";
         $sql[] = "DROP TABLE IF EXISTS oa_asset_order";
         $sql[] = "DROP TABLE IF EXISTS oa_device_col";
         $sql[] = "DROP TABLE IF EXISTS oa_device";
         $sql[] = "DROP TABLE IF EXISTS oa_graph";
         $sql[] = "DROP TABLE IF EXISTS sys_sw_antivirus";
         $sql[] = "DROP TABLE IF EXISTS oa_switch_ports";
         $sql[] = "DROP TABLE IF EXISTS sys_sw_share_perms";
         # bios
         $sql[] = "DELETE sys_hw_bios FROM sys_hw_bios LEFT JOIN system ON system.system_id = sys_hw_bios.system_id WHERE sys_hw_bios.timestamp <> system.timestamp";
         $sql[] = "ALTER TABLE sys_hw_bios CHANGE bios_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE sys_hw_bios ADD current enum('y','n') NOT NULL DEFAULT 'y' AFTER system_id";
         $sql[] = "ALTER TABLE sys_hw_bios CHANGE timestamp last_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER current";
         $sql[] = "ALTER TABLE sys_hw_bios CHANGE first_timestamp first_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER last_seen";
         $sql[] = "ALTER TABLE sys_hw_bios CHANGE bios_manufacturer manufacturer varchar(200) NOT NULL DEFAULT '' AFTER first_seen";
         $sql[] = "ALTER TABLE sys_hw_bios CHANGE bios_serial serial varchar(100) NOT NULL DEFAULT '' AFTER manufacturer";
         $sql[] = "ALTER TABLE sys_hw_bios CHANGE bios_description description varchar(200) NOT NULL DEFAULT '' AFTER serial";
         $sql[] = "ALTER TABLE sys_hw_bios CHANGE bios_smversion smversion varchar(100) NOT NULL DEFAULT '' AFTER description";
         $sql[] = "ALTER TABLE sys_hw_bios CHANGE bios_version version varchar(100) NOT NULL DEFAULT '' AFTER smversion";
         $sql[] = "ALTER TABLE sys_hw_bios CHANGE bios_asset_tag asset_tag varchar(100) NOT NULL DEFAULT '' AFTER version";
         $sql[] = "RENAME TABLE sys_hw_bios TO `bios`";
         # disk
         $sql[] = "DELETE sys_hw_hard_drive FROM sys_hw_hard_drive LEFT JOIN system ON system.system_id = sys_hw_hard_drive.system_id WHERE sys_hw_hard_drive.timestamp <> system.timestamp";
         $sql[] = "ALTER TABLE sys_hw_hard_drive CHANGE hard_drive_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE sys_hw_hard_drive CHANGE system_id system_id int(10) unsigned DEFAULT NULL AFTER id";
         $sql[] = "ALTER TABLE sys_hw_hard_drive ADD current enum('y','n') NOT NULL DEFAULT 'y' AFTER system_id";
         $sql[] = "ALTER TABLE sys_hw_hard_drive CHANGE first_timestamp first_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER current";
         $sql[] = "ALTER TABLE sys_hw_hard_drive CHANGE `timestamp` last_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER first_seen";
         $sql[] = "ALTER TABLE sys_hw_hard_drive CHANGE hard_drive_manufacturer manufacturer varchar(100) NOT NULL DEFAULT '' AFTER last_seen";
         $sql[] = "ALTER TABLE sys_hw_hard_drive CHANGE hard_drive_model model varchar(100) NOT NULL DEFAULT '' AFTER manufacturer";
         $sql[] = "ALTER TABLE sys_hw_hard_drive CHANGE hard_drive_serial serial varchar(100) NOT NULL DEFAULT '' AFTER model";
         $sql[] = "ALTER TABLE sys_hw_hard_drive CHANGE hard_drive_device_id device varchar(200) NOT NULL DEFAULT '' AFTER serial";
         $sql[] = "ALTER TABLE sys_hw_hard_drive CHANGE hard_drive_caption caption varchar(100) NOT NULL DEFAULT '' AFTER device";
         $sql[] = "ALTER TABLE sys_hw_hard_drive CHANGE hard_drive_index hard_drive_index varchar(100) NOT NULL DEFAULT '' AFTER caption";
         $sql[] = "ALTER TABLE sys_hw_hard_drive CHANGE hard_drive_interface_type interface_type varchar(100) NOT NULL DEFAULT '' AFTER hard_drive_index";
         $sql[] = "ALTER TABLE sys_hw_hard_drive CHANGE hard_drive_partitions partition_count tinyint unsigned NOT NULL DEFAULT '0' AFTER interface_type";
         $sql[] = "ALTER TABLE sys_hw_hard_drive CHANGE hard_drive_scsi_bus scsi_bus varchar(10) NOT NULL DEFAULT '' AFTER partition_count";
         $sql[] = "ALTER TABLE sys_hw_hard_drive CHANGE hard_drive_scsi_logical_unit scsi_logical_unit varchar(100) NOT NULL DEFAULT '' AFTER scsi_bus";
         $sql[] = "ALTER TABLE sys_hw_hard_drive CHANGE hard_drive_scsi_port scsi_port varchar(10) NOT NULL DEFAULT '' AFTER scsi_logical_unit";
         $sql[] = "ALTER TABLE sys_hw_hard_drive CHANGE hard_drive_size size int unsigned NOT NULL DEFAULT '0' AFTER scsi_port";
         $sql[] = "ALTER TABLE sys_hw_hard_drive CHANGE hard_drive_status status varchar(100) NOT NULL DEFAULT '' AFTER size";
         $sql[] = "ALTER TABLE sys_hw_hard_drive CHANGE hard_drive_firmware firmware varchar(100) NOT NULL DEFAULT '' AFTER status";
         $sql[] = "ALTER TABLE sys_hw_hard_drive CHANGE hard_drive_model_family model_family varchar(200) NOT NULL DEFAULT '' AFTER firmware";
         $sql[] = "RENAME TABLE sys_hw_hard_drive TO `disk`";
         # dns
         $sql[] = "DELETE sys_sw_dns FROM sys_sw_dns LEFT JOIN system ON system.system_id = sys_sw_dns.system_id WHERE sys_sw_dns.timestamp <> system.timestamp";
         $sql[] = "DELETE sys_sw_dns FROM sys_sw_dns WHERE (dns_name = '' AND dns_full_name = '')";
         $sql[] = "ALTER TABLE sys_sw_dns CHANGE dns_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE sys_sw_dns CHANGE system_id system_id int(10) unsigned DEFAULT NULL AFTER id";
         $sql[] = "ALTER TABLE sys_sw_dns ADD current enum('y','n') NOT NULL DEFAULT 'y' AFTER system_id";
         $sql[] = "ALTER TABLE sys_sw_dns CHANGE first_timestamp first_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER current";
         $sql[] = "ALTER TABLE sys_sw_dns CHANGE `timestamp` last_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER first_seen";
         $sql[] = "ALTER TABLE sys_sw_dns CHANGE dns_name name varchar(100) NOT NULL DEFAULT '' AFTER last_seen";
         $sql[] = "ALTER TABLE sys_sw_dns CHANGE dns_full_name fqdn varchar(200) NOT NULL DEFAULT '' AFTER name";
         $sql[] = "ALTER TABLE sys_sw_dns CHANGE dns_ip_address ip varchar(45) NOT NULL DEFAULT '' AFTER fqdn";
         $sql[] = "RENAME TABLE sys_sw_dns TO `dns`";
         # graphs
         $sql[] = "DROP TABLE IF EXISTS sys_hw_graph";
         $sql[] = "CREATE TABLE `graph` (\n                        `id` int(10) unsigned NOT NULL AUTO_INCREMENT,\n                        `system_id` int(10) unsigned DEFAULT NULL,\n                        `linked_table` varchar(100) NOT NULL DEFAULT '',\n                        `linked_row` varchar(100) NOT NULL DEFAULT '',\n                        `type` enum('disk','partition','directory','file','database','share','other') NOT NULL DEFAULT 'partition',\n                        `used_percent` tinyint unsigned NOT NULL DEFAULT '0',\n                        `free_percent` tinyint unsigned NOT NULL DEFAULT '0',\n                        `used` int unsigned NOT NULL DEFAULT '0',\n                        `free` int unsigned NOT NULL DEFAULT '0',\n                        `size` int unsigned NOT NULL DEFAULT '0',\n                        `timestamp` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',\n                        PRIMARY KEY (`id`), KEY `system_id` (`system_id`),\n                        CONSTRAINT `sys_hw_graph_system_id` FOREIGN KEY (`system_id`) REFERENCES `system` (`system_id`) ON DELETE CASCADE)\n                        ENGINE=InnoDB DEFAULT CHARSET=utf8";
         $sql[] = "INSERT INTO graph SELECT NULL, system_id, 'partition', partition_id, 'partition', used_percent, free_percent, used, free, total as size, `timestamp` FROM sys_hw_graphs_disk";
         $sql[] = "DROP TABLE IF EXISTS sys_hw_graphs_disk";
         # log
         $sql[] = "DELETE sys_sw_log FROM sys_sw_log LEFT JOIN system ON system.system_id = sys_sw_log.system_id WHERE sys_sw_log.timestamp <> system.timestamp";
         $sql[] = "ALTER TABLE sys_sw_log CHANGE log_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE sys_sw_log CHANGE system_id system_id int(10) unsigned DEFAULT NULL AFTER id";
         $sql[] = "ALTER TABLE sys_sw_log ADD current enum('y','n') NOT NULL DEFAULT 'y' AFTER system_id";
         $sql[] = "ALTER TABLE sys_sw_log CHANGE first_timestamp first_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER current";
         $sql[] = "ALTER TABLE sys_sw_log CHANGE timestamp last_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER first_seen";
         $sql[] = "ALTER TABLE sys_sw_log CHANGE log_name name varchar(50) NOT NULL DEFAULT '' AFTER last_seen";
         $sql[] = "ALTER TABLE sys_sw_log CHANGE log_file_name file_name varchar(250) NOT NULL DEFAULT '' AFTER name";
         $sql[] = "ALTER TABLE sys_sw_log CHANGE log_file_size file_size int unsigned NOT NULL DEFAULT '0' AFTER file_name";
         $sql[] = "ALTER TABLE sys_sw_log CHANGE log_max_file_size max_file_size int unsigned NOT NULL DEFAULT '0' AFTER file_size";
         $sql[] = "ALTER TABLE sys_sw_log CHANGE log_overwrite overwrite varchar(30) NOT NULL DEFAULT '' AFTER max_file_size";
         $sql[] = "RENAME TABLE sys_sw_log TO `log`";
         # memory
         $sql[] = "DELETE sys_hw_memory FROM sys_hw_memory LEFT JOIN system ON system.system_id = sys_hw_memory.system_id WHERE sys_hw_memory.timestamp <> system.timestamp";
         $sql[] = "ALTER TABLE sys_hw_memory CHANGE memory_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE sys_hw_memory ADD current enum('y','n') NOT NULL DEFAULT 'y' AFTER system_id";
         $sql[] = "ALTER TABLE sys_hw_memory CHANGE first_timestamp first_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER current";
         $sql[] = "ALTER TABLE sys_hw_memory CHANGE timestamp last_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER first_seen";
         $sql[] = "ALTER TABLE sys_hw_memory CHANGE memory_serial serial varchar(100) NOT NULL DEFAULT '' AFTER last_seen";
         $sql[] = "ALTER TABLE sys_hw_memory CHANGE memory_bank bank varchar(100) NOT NULL DEFAULT '' AFTER serial";
         $sql[] = "ALTER TABLE sys_hw_memory CHANGE memory_type type varchar(100) NOT NULL DEFAULT '' AFTER bank";
         $sql[] = "ALTER TABLE sys_hw_memory CHANGE memory_form_factor form_factor varchar(100) NOT NULL DEFAULT '' AFTER type";
         $sql[] = "ALTER TABLE sys_hw_memory CHANGE memory_detail detail varchar(100) NOT NULL DEFAULT '' AFTER form_factor";
         $sql[] = "ALTER TABLE sys_hw_memory CHANGE memory_capacity size int unsigned NOT NULL DEFAULT '0' AFTER detail";
         $sql[] = "ALTER TABLE sys_hw_memory CHANGE memory_speed speed int unsigned NOT NULL DEFAULT '0' AFTER size";
         $sql[] = "ALTER TABLE sys_hw_memory CHANGE memory_tag tag varchar(100) NOT NULL DEFAULT '' AFTER speed";
         $sql[] = "RENAME TABLE sys_hw_memory TO `memory`";
         # module
         $sql[] = "DELETE sys_hw_module FROM sys_hw_module LEFT JOIN system ON system.system_id = sys_hw_module.system_id WHERE sys_hw_module.timestamp <> system.timestamp";
         $sql[] = "ALTER TABLE sys_hw_module CHANGE system_id system_id int(10) unsigned DEFAULT NULL AFTER id";
         $sql[] = "ALTER TABLE sys_hw_module ADD current enum('y','n') NOT NULL DEFAULT 'y' AFTER system_id";
         $sql[] = "ALTER TABLE sys_hw_module CHANGE first_timestamp first_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER current";
         $sql[] = "ALTER TABLE sys_hw_module CHANGE timestamp last_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER first_seen";
         $sql[] = "ALTER TABLE sys_hw_module CHANGE class_text class_text varchar(20) NOT NULL DEFAULT '' AFTER class";
         $sql[] = "ALTER TABLE sys_hw_module CHANGE hardware_revision hardware_revision varchar(100) NOT NULL DEFAULT '' AFTER class_text";
         $sql[] = "ALTER TABLE sys_hw_module CHANGE serial_number serial varchar(100) NOT NULL DEFAULT '' AFTER software_revision";
         $sql[] = "ALTER TABLE sys_hw_module CHANGE object_id object_ident varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE sys_hw_module CHANGE asset_id asset_ident varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "RENAME TABLE sys_hw_module TO `module`";
         # monitor
         $sql[] = "DELETE sys_hw_monitor FROM sys_hw_monitor LEFT JOIN system ON system.system_id = sys_hw_monitor.system_id WHERE sys_hw_monitor.timestamp <> system.timestamp";
         $sql[] = "ALTER TABLE sys_hw_monitor CHANGE monitor_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE sys_hw_monitor ADD current enum('y','n') NOT NULL DEFAULT 'y' AFTER system_id";
         $sql[] = "ALTER TABLE sys_hw_monitor CHANGE first_timestamp first_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER current";
         $sql[] = "ALTER TABLE sys_hw_monitor CHANGE timestamp last_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER first_seen";
         $sql[] = "ALTER TABLE sys_hw_monitor CHANGE manufacturer manufacturer varchar(100) NOT NULL DEFAULT '' AFTER last_seen";
         $sql[] = "ALTER TABLE sys_hw_monitor CHANGE model model varchar(100) NOT NULL DEFAULT '' AFTER manufacturer";
         $sql[] = "ALTER TABLE sys_hw_monitor CHANGE serial serial varchar(50) NOT NULL DEFAULT '' AFTER model";
         $sql[] = "ALTER TABLE sys_hw_monitor CHANGE man_description description varchar(200) NOT NULL DEFAULT '' AFTER serial";
         $sql[] = "ALTER TABLE sys_hw_monitor CHANGE device_id device varchar(100) NOT NULL DEFAULT '' AFTER description";
         $sql[] = "ALTER TABLE sys_hw_monitor CHANGE manufacture_date manufacture_date varchar(20) NOT NULL DEFAULT '' AFTER device";
         $sql[] = "ALTER TABLE sys_hw_monitor CHANGE size size tinyint unsigned NOT NULL DEFAULT '0' AFTER manufacture_date";
         $sql[] = "ALTER TABLE sys_hw_monitor DROP man_serial";
         $sql[] = "ALTER TABLE sys_hw_monitor DROP man_value";
         $sql[] = "ALTER TABLE sys_hw_monitor DROP man_purchase_order_number";
         $sql[] = "ALTER TABLE sys_hw_monitor DROP man_date_purchased";
         $sql[] = "RENAME TABLE sys_hw_monitor TO `monitor`";
         # motherboard
         $sql[] = "DELETE sys_hw_motherboard FROM sys_hw_motherboard LEFT JOIN system ON system.system_id = sys_hw_motherboard.system_id WHERE sys_hw_motherboard.timestamp <> system.timestamp";
         $sql[] = "ALTER TABLE sys_hw_motherboard CHANGE motherboard_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE sys_hw_motherboard CHANGE system_id system_id int(10) unsigned DEFAULT NULL AFTER id";
         $sql[] = "ALTER TABLE sys_hw_motherboard ADD current enum('y','n') NOT NULL DEFAULT 'y' AFTER system_id";
         $sql[] = "ALTER TABLE sys_hw_motherboard CHANGE first_timestamp first_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER current";
         $sql[] = "ALTER TABLE sys_hw_motherboard CHANGE timestamp last_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER first_seen";
         $sql[] = "ALTER TABLE sys_hw_motherboard CHANGE manufacturer manufacturer varchar(50) NOT NULL DEFAULT '' AFTER last_seen";
         $sql[] = "ALTER TABLE sys_hw_motherboard CHANGE model model varchar(50) NOT NULL DEFAULT '' AFTER manufacturer";
         $sql[] = "ALTER TABLE sys_hw_motherboard CHANGE serial serial varchar(100) NOT NULL DEFAULT '' AFTER model";
         $sql[] = "ALTER TABLE sys_hw_motherboard CHANGE memory_slots memory_slot_count tinyint unsigned NOT NULL DEFAULT '0' AFTER serial";
         $sql[] = "ALTER TABLE sys_hw_motherboard CHANGE processor_slots processor_slot_count tinyint unsigned NOT NULL DEFAULT '0' AFTER memory_slot_count";
         $sql[] = "RENAME TABLE sys_hw_motherboard TO `motherboard`";
         # optical drive
         $sql[] = "DELETE sys_hw_optical_drive FROM sys_hw_optical_drive LEFT JOIN system ON system.system_id = sys_hw_optical_drive.system_id WHERE sys_hw_optical_drive.timestamp <> system.timestamp";
         $sql[] = "ALTER TABLE sys_hw_optical_drive CHANGE optical_drive_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE sys_hw_optical_drive CHANGE system_id system_id int(10) unsigned DEFAULT NULL AFTER id";
         $sql[] = "ALTER TABLE sys_hw_optical_drive ADD current enum('y','n') NOT NULL DEFAULT 'y' AFTER system_id";
         $sql[] = "ALTER TABLE sys_hw_optical_drive CHANGE first_timestamp first_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER current";
         $sql[] = "ALTER TABLE sys_hw_optical_drive CHANGE timestamp last_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER first_seen";
         $sql[] = "ALTER TABLE sys_hw_optical_drive CHANGE optical_drive_model model varchar(100) NOT NULL DEFAULT '' AFTER last_seen";
         $sql[] = "ALTER TABLE sys_hw_optical_drive CHANGE optical_drive_caption description varchar(100) NOT NULL DEFAULT '' AFTER model";
         $sql[] = "ALTER TABLE sys_hw_optical_drive CHANGE optical_drive_device_id device varchar(100) NOT NULL DEFAULT '' AFTER description";
         $sql[] = "ALTER TABLE sys_hw_optical_drive CHANGE optical_drive_mount_point mount_point varchar(10) NOT NULL DEFAULT '' AFTER device";
         $sql[] = "RENAME TABLE sys_hw_optical_drive TO `optical`";
         # netstat
         $sql[] = "DELETE sys_sw_netstat FROM sys_sw_netstat LEFT JOIN system ON system.system_id = sys_sw_netstat.system_id WHERE sys_sw_netstat.timestamp <> system.timestamp";
         $sql[] = "ALTER TABLE sys_sw_netstat ADD current enum('y','n') NOT NULL DEFAULT 'y' AFTER system_id";
         $sql[] = "ALTER TABLE sys_sw_netstat CHANGE first_timestamp first_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER current";
         $sql[] = "ALTER TABLE sys_sw_netstat CHANGE timestamp last_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER first_seen";
         $sql[] = "ALTER TABLE sys_sw_netstat CHANGE ip_address ip varchar(45) NOT NULL DEFAULT '' AFTER protocol";
         $sql[] = "RENAME TABLE sys_sw_netstat TO `netstat`";
         # network card
         $sql[] = "DELETE sys_hw_network_card FROM sys_hw_network_card LEFT JOIN system ON system.system_id = sys_hw_network_card.system_id WHERE sys_hw_network_card.timestamp <> system.timestamp";
         $sql[] = "ALTER TABLE sys_hw_network_card CHANGE net_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE sys_hw_network_card CHANGE system_id system_id int(10) unsigned DEFAULT NULL AFTER id";
         $sql[] = "ALTER TABLE sys_hw_network_card ADD current enum('y','n') NOT NULL DEFAULT 'y' AFTER system_id";
         $sql[] = "ALTER TABLE sys_hw_network_card CHANGE first_timestamp first_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER current";
         $sql[] = "ALTER TABLE sys_hw_network_card CHANGE timestamp last_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER first_seen";
         $sql[] = "ALTER TABLE sys_hw_network_card CHANGE net_mac_address mac varchar(200) NOT NULL DEFAULT '' AFTER last_seen";
         $sql[] = "ALTER TABLE sys_hw_network_card CHANGE net_manufacturer manufacturer varchar(100) NOT NULL DEFAULT '' AFTER mac";
         $sql[] = "ALTER TABLE sys_hw_network_card CHANGE net_model model varchar(255) NOT NULL DEFAULT '' AFTER manufacturer";
         $sql[] = "ALTER TABLE sys_hw_network_card CHANGE net_description description varchar(255) NOT NULL DEFAULT '' AFTER model";
         $sql[] = "ALTER TABLE sys_hw_network_card CHANGE net_alias alias varchar(255) NOT NULL DEFAULT '' AFTER description";
         $sql[] = "ALTER TABLE sys_hw_network_card CHANGE net_ip_enabled ip_enabled varchar(10) NOT NULL DEFAULT '' AFTER alias";
         $sql[] = "ALTER TABLE sys_hw_network_card CHANGE net_index net_index varchar(10) NOT NULL DEFAULT '' AFTER ip_enabled";
         $sql[] = "ALTER TABLE sys_hw_network_card CHANGE net_dhcp_enabled dhcp_enabled varchar(100) NOT NULL DEFAULT '' AFTER net_index";
         $sql[] = "ALTER TABLE sys_hw_network_card CHANGE net_dhcp_server dhcp_server varchar(30) NOT NULL DEFAULT '' AFTER dhcp_enabled";
         $sql[] = "ALTER TABLE sys_hw_network_card CHANGE net_dhcp_lease_obtained dhcp_lease_obtained varchar(14) NOT NULL DEFAULT '' AFTER dhcp_server";
         $sql[] = "ALTER TABLE sys_hw_network_card CHANGE net_dhcp_lease_expires dhcp_lease_expires varchar(14) NOT NULL DEFAULT '' AFTER dhcp_lease_obtained";
         $sql[] = "ALTER TABLE sys_hw_network_card CHANGE net_dns_host_name dns_host_name varchar(100) NOT NULL DEFAULT '' AFTER dhcp_lease_expires";
         $sql[] = "ALTER TABLE sys_hw_network_card CHANGE net_dns_server dns_server varchar(100) NOT NULL DEFAULT '' AFTER dns_host_name";
         $sql[] = "ALTER TABLE sys_hw_network_card CHANGE net_dns_domain dns_domain varchar(100) NOT NULL DEFAULT '' AFTER dns_server";
         $sql[] = "ALTER TABLE sys_hw_network_card CHANGE net_dns_domain_reg_enabled dns_domain_reg_enabled varchar(10) NOT NULL DEFAULT '' AFTER dns_domain";
         $sql[] = "ALTER TABLE sys_hw_network_card CHANGE net_adapter_type type varchar(100) NOT NULL DEFAULT '' AFTER dns_domain_reg_enabled";
         $sql[] = "ALTER TABLE sys_hw_network_card CHANGE net_connection_id connection varchar(255) NOT NULL DEFAULT '' AFTER type";
         $sql[] = "ALTER TABLE sys_hw_network_card CHANGE net_connection_status connection_status varchar(30) NOT NULL DEFAULT '' AFTER connection";
         $sql[] = "ALTER TABLE sys_hw_network_card CHANGE net_speed speed int(10) unsigned NOT NULL DEFAULT '0' AFTER connection_status";
         $sql[] = "ALTER TABLE sys_hw_network_card CHANGE net_slaves slaves varchar(100) NOT NULL DEFAULT '' AFTER speed";
         $sql[] = "ALTER TABLE sys_hw_network_card DROP net_dns_domain_suffix";
         $sql[] = "ALTER TABLE sys_hw_network_card DROP net_wins_primary";
         $sql[] = "ALTER TABLE sys_hw_network_card DROP net_wins_secondary";
         $sql[] = "ALTER TABLE sys_hw_network_card DROP net_wins_lmhosts_enabled";
         $sql[] = "ALTER TABLE sys_hw_network_card DROP KEY net_mac_address";
         $sql[] = "ALTER TABLE sys_hw_network_card ADD KEY mac (`mac`)";
         $sql[] = "RENAME TABLE sys_hw_network_card TO `network`";
         # partition
         $sql[] = "DELETE sys_hw_partition FROM sys_hw_partition LEFT JOIN system ON system.system_id = sys_hw_partition.system_id WHERE sys_hw_partition.timestamp <> system.timestamp";
         $sql[] = "UPDATE sys_hw_partition SET partition_type = 'volume'                                         WHERE partition_type = 'Volume'";
         $sql[] = "UPDATE sys_hw_partition SET partition_type = 'local'                                          WHERE partition_type = 'Local Disk'";
         $sql[] = "UPDATE sys_hw_partition SET partition_type = 'local removable'                                WHERE partition_type = 'Removable Disk'";
         $sql[] = "UPDATE sys_hw_partition SET partition_type = 'local'                                          WHERE partition_type = 'local hard disk'";
         $sql[] = "UPDATE sys_hw_partition SET partition_mount_type = 'partition', partition_type = 'local'      WHERE partition_type = 'partition'";
         $sql[] = "UPDATE sys_hw_partition SET partition_mount_type = 'mount point', partition_type = 'smb'      WHERE partition_type = 'Network Drive'";
         $sql[] = "UPDATE sys_hw_partition SET partition_mount_type = 'mount point'                              WHERE partition_type LIKE 'raid%'";
         $sql[] = "UPDATE sys_hw_partition SET partition_mount_type = 'mount point'                              WHERE partition_mount_type = 'lvm'";
         $sql[] = "UPDATE sys_hw_partition SET partition_mount_type = 'other' WHERE (partition_mount_type != 'partition' AND partition_mount_type != 'mount point')";
         $sql[] = "ALTER TABLE sys_hw_partition CHANGE partition_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE sys_hw_partition CHANGE system_id system_id int(10) unsigned DEFAULT NULL AFTER id";
         $sql[] = "ALTER TABLE sys_hw_partition ADD current enum('y','n') NOT NULL DEFAULT 'y' AFTER system_id";
         $sql[] = "ALTER TABLE sys_hw_partition CHANGE first_timestamp first_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER current";
         $sql[] = "ALTER TABLE sys_hw_partition CHANGE timestamp last_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER first_seen";
         $sql[] = "ALTER TABLE sys_hw_partition CHANGE partition_serial serial varchar(100) NOT NULL DEFAULT '' AFTER last_seen";
         $sql[] = "ALTER TABLE sys_hw_partition CHANGE partition_name name varchar(100) NOT NULL DEFAULT '' AFTER serial";
         $sql[] = "ALTER TABLE sys_hw_partition CHANGE partition_caption description varchar(100) NOT NULL DEFAULT '' AFTER name";
         $sql[] = "ALTER TABLE sys_hw_partition CHANGE partition_device_id device varchar(100) NOT NULL DEFAULT '' AFTER description";
         $sql[] = "ALTER TABLE sys_hw_partition CHANGE hard_drive_index hard_drive_index varchar(100) NOT NULL DEFAULT '' AFTER device";
         $sql[] = "ALTER TABLE sys_hw_partition CHANGE partition_disk_index partition_disk_index varchar(50) NOT NULL DEFAULT '' AFTER hard_drive_index";
         $sql[] = "ALTER TABLE sys_hw_partition CHANGE partition_mount_type mount_type enum('mount point', 'partition', 'other') NOT NULL DEFAULT 'partition' AFTER partition_disk_index";
         $sql[] = "ALTER TABLE sys_hw_partition CHANGE partition_mount_point mount_point varchar(100) NOT NULL DEFAULT '' AFTER mount_type";
         $sql[] = "ALTER TABLE sys_hw_partition CHANGE partition_size size int unsigned NOT NULL DEFAULT '1' AFTER mount_point";
         $sql[] = "ALTER TABLE sys_hw_partition CHANGE partition_free_space free int unsigned NOT NULL DEFAULT '1' AFTER size";
         $sql[] = "ALTER TABLE sys_hw_partition CHANGE partition_used_space used int unsigned NOT NULL DEFAULT '1' AFTER free";
         $sql[] = "ALTER TABLE sys_hw_partition CHANGE partition_format format varchar(20) NOT NULL DEFAULT '' AFTER used";
         $sql[] = "ALTER TABLE sys_hw_partition CHANGE partition_bootable bootable varchar(10) NOT NULL DEFAULT '' AFTER format";
         $sql[] = "ALTER TABLE sys_hw_partition CHANGE partition_type `type` varchar(100) NOT NULL DEFAULT 'local' AFTER bootable";
         $sql[] = "ALTER TABLE sys_hw_partition DROP partition_quotas_supported";
         $sql[] = "ALTER TABLE sys_hw_partition DROP partition_quotas_enabled";
         $sql[] = "RENAME TABLE sys_hw_partition TO `partition`";
         # processor
         $sql[] = "DELETE sys_hw_processor FROM sys_hw_processor LEFT JOIN system ON system.system_id = sys_hw_processor.system_id WHERE sys_hw_processor.timestamp <> system.timestamp";
         $sql[] = "ALTER TABLE sys_hw_processor CHANGE processor_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE sys_hw_processor CHANGE system_id system_id int(10) unsigned DEFAULT NULL AFTER id";
         $sql[] = "ALTER TABLE sys_hw_processor ADD current enum('y', 'n') NOT NULL default 'y' AFTER system_id";
         $sql[] = "ALTER TABLE sys_hw_processor CHANGE first_timestamp first_seen datetime NOT NULL default '0000-00-00 00:00:00' AFTER current";
         $sql[] = "ALTER TABLE sys_hw_processor CHANGE timestamp last_seen datetime NOT NULL default '0000-00-00 00:00:00' AFTER first_seen";
         $sql[] = "ALTER TABLE sys_hw_processor CHANGE processor_count physical_count tinyint unsigned NOT NULL default '1' AFTER last_seen";
         $sql[] = "UPDATE sys_hw_processor SET physical_count = 1 WHERE physical_count = 0 OR physical_count = ''";
         $sql[] = "ALTER TABLE sys_hw_processor CHANGE processor_cores core_count tinyint unsigned NOT NULL default '1' AFTER physical_count";
         $sql[] = "ALTER TABLE sys_hw_processor CHANGE processor_logical logical_count tinyint unsigned NOT NULL default '1' AFTER core_count";
         $sql[] = "ALTER TABLE sys_hw_processor CHANGE processor_description description varchar(100) NOT NULL default '' AFTER logical_count";
         $sql[] = "ALTER TABLE sys_hw_processor CHANGE processor_speed speed int unsigned NOT NULL default '0' AFTER description";
         $sql[] = "ALTER TABLE sys_hw_processor CHANGE processor_manufacturer manufacturer varchar(100) NOT NULL default '' AFTER speed";
         $sql[] = "ALTER TABLE sys_hw_processor CHANGE processor_architecture architecture varchar(100) NOT NULL default '' AFTER manufacturer";
         $sql[] = "ALTER TABLE sys_hw_processor ADD socket varchar(100) NOT NULL default '' AFTER architecture";
         $sql[] = "ALTER TABLE sys_hw_processor DROP COLUMN processor_power_management_supported";
         $sql[] = "RENAME TABLE sys_hw_processor TO `processor`";
         $sql[] = "UPDATE processor SET manufacturer = 'Intel' WHERE manufacturer = 'GenuineIntel'";
         $sql[] = "UPDATE processor SET manufacturer = 'AMD' WHERE manufacturer = 'AuthenticAMD'";
         # san (new table)
         $sql[] = "DROP TABLE IF EXISTS `san`";
         $sql[] = "CREATE TABLE `san` (\n                id int(10) unsigned NOT NULL AUTO_INCREMENT,\n                system_id int(10) unsigned DEFAULT NULL,\n                current enum('y','n') NOT NULL DEFAULT 'y',\n                first_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00',\n                last_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00',\n                type varchar(100) NOT NULL DEFAULT '',\n                manufacturer varchar(100) NOT NULL DEFAULT '',\n                `serial` varchar(50) NOT NULL DEFAULT '',\n                part_number varchar(100) NOT NULL DEFAULT '',\n                location varchar(100) NOT NULL DEFAULT '',\n                attached_to varchar(100) NOT NULL DEFAULT '',\n                status varchar(100) NOT NULL DEFAULT '',\n                date_of_manufacture varchar(100) NOT NULL DEFAULT '',\n                notes text NOT NULL DEFAULT '',\n                PRIMARY KEY (`id`), KEY `system_id` (`system_id`),\n                CONSTRAINT `san_system_id` FOREIGN KEY (`system_id`) REFERENCES `system` (`system_id`) ON DELETE CASCADE)\n                ENGINE=InnoDB DEFAULT CHARSET=utf8";
         # scsi controller
         $sql[] = "DELETE sys_hw_scsi_controller FROM sys_hw_scsi_controller LEFT JOIN system ON system.system_id = sys_hw_scsi_controller.system_id WHERE sys_hw_scsi_controller.timestamp <> system.timestamp";
         $sql[] = "ALTER TABLE sys_hw_scsi_controller CHANGE scsi_controller_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE sys_hw_scsi_controller CHANGE system_id system_id int(10) unsigned DEFAULT NULL AFTER id";
         $sql[] = "ALTER TABLE sys_hw_scsi_controller ADD current enum('y','n') NOT NULL DEFAULT 'y' AFTER system_id";
         $sql[] = "ALTER TABLE sys_hw_scsi_controller CHANGE first_timestamp first_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER current";
         $sql[] = "ALTER TABLE sys_hw_scsi_controller CHANGE timestamp last_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER first_seen";
         $sql[] = "ALTER TABLE sys_hw_scsi_controller CHANGE scsi_controller_manufacturer manufacturer varchar(100) NOT NULL DEFAULT '' AFTER last_seen";
         $sql[] = "ALTER TABLE sys_hw_scsi_controller CHANGE scsi_controller_name model varchar(200) NOT NULL DEFAULT '' AFTER manufacturer";
         $sql[] = "ALTER TABLE sys_hw_scsi_controller ADD `serial` varchar(200) NOT NULL DEFAULT '' AFTER model";
         $sql[] = "ALTER TABLE sys_hw_scsi_controller CHANGE scsi_controller_device_id device varchar(200) NOT NULL DEFAULT '' AFTER `serial`";
         $sql[] = "ALTER TABLE sys_hw_scsi_controller CHANGE scsi_controller_type type enum('raid','hba','other','san controller','san shelf') NOT NULL DEFAULT 'other' AFTER device";
         $sql[] = "RENAME TABLE sys_hw_scsi_controller TO `scsi`";
         # group
         $sql[] = "DELETE sys_sw_group FROM sys_sw_group LEFT JOIN system ON system.system_id = sys_sw_group.system_id WHERE sys_sw_group.timestamp <> system.timestamp";
         $sql[] = "ALTER TABLE sys_sw_group CHANGE group_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE sys_sw_group CHANGE system_id system_id int(10) unsigned DEFAULT NULL AFTER id";
         $sql[] = "ALTER TABLE sys_sw_group ADD current enum('y','n') NOT NULL DEFAULT 'y' AFTER system_id";
         $sql[] = "ALTER TABLE sys_sw_group CHANGE first_timestamp first_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER current";
         $sql[] = "ALTER TABLE sys_sw_group CHANGE timestamp last_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER first_seen";
         $sql[] = "ALTER TABLE sys_sw_group CHANGE group_name name varchar(100) NOT NULL DEFAULT '' AFTER last_seen";
         $sql[] = "ALTER TABLE sys_sw_group CHANGE group_description description varchar(200) NOT NULL DEFAULT '' AFTER name";
         $sql[] = "ALTER TABLE sys_sw_group CHANGE group_sid sid varchar(100) NOT NULL DEFAULT '' AFTER description";
         $sql[] = "ALTER TABLE sys_sw_group CHANGE group_members members text NOT NULL AFTER sid";
         $sql[] = "RENAME TABLE sys_sw_group TO `user_group`";
         # pagefile
         $sql[] = "DELETE sys_sw_pagefile FROM sys_sw_pagefile LEFT JOIN system ON system.system_id = sys_sw_pagefile.system_id WHERE sys_sw_pagefile.timestamp <> system.timestamp";
         $sql[] = "ALTER TABLE sys_sw_pagefile CHANGE pagefile_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE sys_sw_pagefile CHANGE system_id system_id int(10) unsigned DEFAULT NULL AFTER id";
         $sql[] = "ALTER TABLE sys_sw_pagefile ADD current enum('y','n') NOT NULL DEFAULT 'y' AFTER system_id";
         $sql[] = "ALTER TABLE sys_sw_pagefile CHANGE first_timestamp first_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER current";
         $sql[] = "ALTER TABLE sys_sw_pagefile CHANGE timestamp last_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER first_seen";
         $sql[] = "ALTER TABLE sys_sw_pagefile CHANGE pagefile_name name varchar(100) NOT NULL DEFAULT '' AFTER last_seen";
         $sql[] = "ALTER TABLE sys_sw_pagefile CHANGE pagefile_size size int unsigned NOT NULL DEFAULT '0' AFTER name";
         $sql[] = "ALTER TABLE sys_sw_pagefile CHANGE pagefile_initial_size initial_size int unsigned NOT NULL DEFAULT '0' AFTER size";
         $sql[] = "ALTER TABLE sys_sw_pagefile CHANGE pagefile_max_size max_size int unsigned NOT NULL DEFAULT '0' AFTER initial_size";
         $sql[] = "RENAME TABLE sys_sw_pagefile TO `pagefile`";
         # print queue
         $sql[] = "DELETE sys_sw_print_queue FROM sys_sw_print_queue LEFT JOIN system ON system.system_id = sys_sw_print_queue.system_id WHERE sys_sw_print_queue.timestamp <> system.timestamp";
         $sql[] = "ALTER TABLE sys_sw_print_queue CHANGE queue_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE sys_sw_print_queue CHANGE system_id system_id int(10) unsigned DEFAULT NULL AFTER id";
         $sql[] = "ALTER TABLE sys_sw_print_queue ADD current enum('y','n') NOT NULL DEFAULT 'y' AFTER system_id";
         $sql[] = "ALTER TABLE sys_sw_print_queue CHANGE first_timestamp first_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER current";
         $sql[] = "ALTER TABLE sys_sw_print_queue CHANGE timestamp last_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER first_seen";
         $sql[] = "ALTER TABLE sys_sw_print_queue CHANGE queue_manufacturer manufacturer varchar(100) NOT NULL DEFAULT '' AFTER last_seen";
         $sql[] = "ALTER TABLE sys_sw_print_queue CHANGE queue_model model varchar(100) NOT NULL DEFAULT '' AFTER manufacturer";
         $sql[] = "ALTER TABLE sys_sw_print_queue CHANGE queue_description description varchar(100) NOT NULL DEFAULT '' AFTER model";
         $sql[] = "ALTER TABLE sys_sw_print_queue CHANGE queue_system_key system_key varchar(100) NOT NULL DEFAULT '' AFTER description";
         $sql[] = "ALTER TABLE sys_sw_print_queue CHANGE queue_name name varchar(100) NOT NULL DEFAULT '' AFTER system_key";
         $sql[] = "ALTER TABLE sys_sw_print_queue CHANGE queue_port_name port_name varchar(100) NOT NULL DEFAULT '' AFTER name";
         $sql[] = "ALTER TABLE sys_sw_print_queue CHANGE queue_ip_address ip varchar(45) NOT NULL DEFAULT '' AFTER port_name";
         $sql[] = "ALTER TABLE sys_sw_print_queue CHANGE queue_shared shared varchar(100) NOT NULL DEFAULT '' AFTER ip";
         $sql[] = "ALTER TABLE sys_sw_print_queue CHANGE queue_shared_name shared_name varchar(100) NOT NULL DEFAULT '' AFTER shared";
         $sql[] = "ALTER TABLE sys_sw_print_queue CHANGE queue_location location varchar(100) NOT NULL DEFAULT '' AFTER shared_name";
         $sql[] = "ALTER TABLE sys_sw_print_queue CHANGE queue_color color varchar(100) NOT NULL DEFAULT '' AFTER location";
         $sql[] = "ALTER TABLE sys_sw_print_queue CHANGE queue_duplex duplex varchar(100) NOT NULL DEFAULT '' AFTER color";
         $sql[] = "ALTER TABLE sys_sw_print_queue CHANGE queue_type type enum('virtual','physical','') NOT NULL DEFAULT '' AFTER duplex";
         $sql[] = "ALTER TABLE sys_sw_print_queue CHANGE queue_connection_status connection_status varchar(100) NOT NULL DEFAULT '' AFTER type";
         $sql[] = "RENAME TABLE sys_sw_print_queue TO `print_queue`";
         # route
         $sql[] = "DELETE sys_sw_route FROM sys_sw_route LEFT JOIN system ON system.system_id = sys_sw_route.system_id WHERE sys_sw_route.timestamp <> system.timestamp";
         $sql[] = "ALTER TABLE sys_sw_route CHANGE route_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE sys_sw_route CHANGE system_id system_id int(10) unsigned DEFAULT NULL AFTER id";
         $sql[] = "ALTER TABLE sys_sw_route ADD current enum('y','n') NOT NULL DEFAULT 'y' AFTER system_id";
         $sql[] = "ALTER TABLE sys_sw_route CHANGE first_timestamp first_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER current";
         $sql[] = "ALTER TABLE sys_sw_route CHANGE timestamp last_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER first_seen";
         $sql[] = "ALTER TABLE sys_sw_route CHANGE next_hop next_hop varchar(40) NOT NULL DEFAULT ''";
         $sql[] = "RENAME TABLE sys_sw_route TO `route`";
         # service
         $sql[] = "DELETE sys_sw_service FROM sys_sw_service LEFT JOIN system ON system.system_id = sys_sw_service.system_id WHERE sys_sw_service.timestamp <> system.timestamp";
         $sql[] = "ALTER TABLE sys_sw_service DROP KEY `timestamp`";
         $sql[] = "ALTER TABLE sys_sw_service DROP KEY `first_timestamp`";
         $sql[] = "ALTER TABLE sys_sw_service DROP KEY `service_name`";
         $sql[] = "ALTER TABLE sys_sw_service DROP KEY `service_display_name`";
         $sql[] = "ALTER TABLE sys_sw_service CHANGE service_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE sys_sw_service CHANGE system_id system_id int(10) unsigned DEFAULT NULL AFTER id";
         $sql[] = "ALTER TABLE sys_sw_service ADD current enum('y','n') NOT NULL DEFAULT 'y' AFTER system_id";
         $sql[] = "ALTER TABLE sys_sw_service CHANGE first_timestamp first_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER current";
         $sql[] = "ALTER TABLE sys_sw_service CHANGE timestamp last_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER first_seen";
         $sql[] = "ALTER TABLE sys_sw_service DROP user_id";
         $sql[] = "ALTER TABLE sys_sw_service CHANGE service_name name varchar(100) NOT NULL DEFAULT '' AFTER last_seen";
         $sql[] = "ALTER TABLE sys_sw_service CHANGE service_display_name description varchar(100) NOT NULL DEFAULT '' AFTER name";
         $sql[] = "ALTER TABLE sys_sw_service CHANGE service_path_name executable text NOT NULL AFTER description";
         $sql[] = "ALTER TABLE sys_sw_service DROP service_started";
         $sql[] = "ALTER TABLE sys_sw_service CHANGE service_start_name user varchar(100) NOT NULL DEFAULT '' AFTER executable";
         $sql[] = "ALTER TABLE sys_sw_service CHANGE service_start_mode start_mode varchar(200) NOT NULL DEFAULT '' AFTER user";
         $sql[] = "ALTER TABLE sys_sw_service CHANGE service_state state varchar(200) NOT NULL DEFAULT '' AFTER start_mode";
         $sql[] = "ALTER TABLE sys_sw_service CHANGE service_count count varchar(5) NOT NULL DEFAULT '' AFTER state";
         $sql[] = "ALTER TABLE sys_sw_service ADD KEY `first_seen` (`first_seen`)";
         $sql[] = "ALTER TABLE sys_sw_service ADD KEY `last_seen` (`last_seen`)";
         $sql[] = "ALTER TABLE sys_sw_service ADD KEY `name` (`name`)";
         $sql[] = "ALTER TABLE sys_sw_service ADD KEY `description` (`description`)";
         $sql[] = "RENAME TABLE sys_sw_service TO `service`";
         # share
         $sql[] = "DELETE sys_sw_share FROM sys_sw_share LEFT JOIN system ON system.system_id = sys_sw_share.system_id WHERE sys_sw_share.timestamp <> system.timestamp";
         $sql[] = "ALTER TABLE sys_sw_share CHANGE share_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE sys_sw_share CHANGE system_id system_id int(10) unsigned DEFAULT NULL AFTER id";
         $sql[] = "ALTER TABLE sys_sw_share ADD current enum('y','n') NOT NULL DEFAULT 'y' AFTER system_id";
         $sql[] = "ALTER TABLE sys_sw_share CHANGE first_timestamp first_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER current";
         $sql[] = "ALTER TABLE sys_sw_share CHANGE `timestamp` last_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER first_seen";
         $sql[] = "ALTER TABLE sys_sw_share CHANGE share_caption description varchar(250) NOT NULL DEFAULT '' AFTER last_seen";
         $sql[] = "ALTER TABLE sys_sw_share CHANGE share_name name varchar(250) NOT NULL DEFAULT '' AFTER description";
         $sql[] = "ALTER TABLE sys_sw_share CHANGE share_path `path` varchar(250) NOT NULL DEFAULT '' AFTER name";
         $sql[] = "ALTER TABLE sys_sw_share CHANGE share_size size int unsigned NOT NULL DEFAULT '0' AFTER `path`";
         $sql[] = "ALTER TABLE sys_sw_share CHANGE share_users users varchar(200) NOT NULL DEFAULT '' AFTER size";
         $sql[] = "RENAME TABLE sys_sw_share TO `share`";
         # software
         $sql[] = "DELETE sys_sw_software FROM sys_sw_software LEFT JOIN system ON system.system_id = sys_sw_software.system_id WHERE sys_sw_software.timestamp <> system.timestamp";
         $sql[] = "ALTER TABLE sys_sw_software CHANGE software_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE sys_sw_software CHANGE system_id system_id int(10) unsigned DEFAULT NULL AFTER id";
         $sql[] = "ALTER TABLE sys_sw_software ADD current enum('y','n') NOT NULL DEFAULT 'y' AFTER system_id";
         $sql[] = "ALTER TABLE sys_sw_software CHANGE first_timestamp first_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER current";
         $sql[] = "ALTER TABLE sys_sw_software CHANGE `timestamp` last_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER first_seen";
         $sql[] = "ALTER TABLE sys_sw_software CHANGE software_name name varchar(255) NOT NULL DEFAULT '' AFTER last_seen";
         $sql[] = "ALTER TABLE sys_sw_software CHANGE software_version version varchar(255) NOT NULL DEFAULT '' AFTER name";
         $sql[] = "ALTER TABLE sys_sw_software CHANGE software_description description text NOT NULL AFTER version";
         $sql[] = "ALTER TABLE sys_sw_software CHANGE software_location location varchar(255) NOT NULL DEFAULT '' AFTER description";
         $sql[] = "ALTER TABLE sys_sw_software CHANGE software_uninstall uninstall mediumtext NOT NULL AFTER location";
         $sql[] = "ALTER TABLE sys_sw_software CHANGE software_install_date install_date varchar(100) NOT NULL DEFAULT '' AFTER uninstall";
         $sql[] = "ALTER TABLE sys_sw_software CHANGE software_installed_by installed_by varchar(100) NOT NULL DEFAULT '' AFTER install_date";
         $sql[] = "ALTER TABLE sys_sw_software CHANGE software_installed_on installed_on datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER installed_by";
         $sql[] = "ALTER TABLE sys_sw_software CHANGE software_publisher publisher varchar(255) NOT NULL DEFAULT '' AFTER installed_on";
         $sql[] = "ALTER TABLE sys_sw_software CHANGE software_install_source install_source varchar(200) NOT NULL DEFAULT '' AFTER publisher";
         $sql[] = "ALTER TABLE sys_sw_software CHANGE software_system_component system_component varchar(2) NOT NULL DEFAULT '' AFTER install_source";
         $sql[] = "ALTER TABLE sys_sw_software CHANGE software_url url varchar(255) NOT NULL DEFAULT '' AFTER system_component";
         $sql[] = "ALTER TABLE sys_sw_software CHANGE software_email email varchar(255) NOT NULL DEFAULT '' AFTER url";
         $sql[] = "ALTER TABLE sys_sw_software CHANGE software_comment type varchar(200) NOT NULL DEFAULT '' AFTER email";
         $sql[] = "ALTER TABLE sys_sw_software ADD version_padded text NOT NULL AFTER type";
         $sql[] = "ALTER TABLE sys_sw_software DROP software_key";
         $sql[] = "ALTER TABLE sys_sw_software DROP software_key_release";
         $sql[] = "ALTER TABLE sys_sw_software DROP software_key_edition";
         $sql[] = "ALTER TABLE sys_sw_software DROP software_man_comment";
         $sql[] = "ALTER TABLE sys_sw_software DROP software_count";
         $sql[] = "ALTER TABLE sys_sw_software DROP software_code_base";
         $sql[] = "ALTER TABLE sys_sw_software DROP software_status";
         $sql[] = "ALTER TABLE sys_sw_software DROP KEY `timestamp`";
         $sql[] = "ALTER TABLE sys_sw_software DROP KEY `first_timestamp`";
         $sql[] = "ALTER TABLE sys_sw_software DROP KEY `software_name`";
         $sql[] = "ALTER TABLE sys_sw_software ADD KEY `first_seen` (`first_seen`)";
         $sql[] = "ALTER TABLE sys_sw_software ADD KEY `last_seen` (`last_seen`)";
         $sql[] = "ALTER TABLE sys_sw_software ADD KEY `name` (`name`)";
         $sql[] = "RENAME TABLE sys_sw_software TO `software`";
         # software key
         $sql[] = "DELETE sys_sw_software_key FROM sys_sw_software_key LEFT JOIN system ON system.system_id = sys_sw_software_key.system_id WHERE sys_sw_software_key.timestamp <> system.timestamp";
         $sql[] = "ALTER TABLE sys_sw_software_key CHANGE key_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE sys_sw_software_key CHANGE system_id system_id int(10) unsigned DEFAULT NULL AFTER id";
         $sql[] = "ALTER TABLE sys_sw_software_key ADD current enum('y','n') NOT NULL DEFAULT 'y' AFTER system_id";
         $sql[] = "ALTER TABLE sys_sw_software_key CHANGE first_timestamp first_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER current";
         $sql[] = "ALTER TABLE sys_sw_software_key CHANGE timestamp last_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER first_seen";
         $sql[] = "ALTER TABLE sys_sw_software_key CHANGE key_name name varchar(250) NOT NULL DEFAULT '' AFTER last_seen";
         $sql[] = "ALTER TABLE sys_sw_software_key CHANGE key_text string varchar(100) NOT NULL DEFAULT '' AFTER name";
         $sql[] = "ALTER TABLE sys_sw_software_key CHANGE key_release rel varchar(100) NOT NULL DEFAULT '' AFTER string";
         $sql[] = "ALTER TABLE sys_sw_software_key CHANGE key_edition edition varchar(100) NOT NULL DEFAULT '' AFTER rel";
         $sql[] = "RENAME TABLE sys_sw_software_key TO `software_key`";
         # sound
         $sql[] = "DELETE sys_hw_sound FROM sys_hw_sound LEFT JOIN system ON system.system_id = sys_hw_sound.system_id WHERE sys_hw_sound.timestamp <> system.timestamp";
         $sql[] = "ALTER TABLE sys_hw_sound CHANGE sound_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE sys_hw_sound CHANGE system_id system_id int(10) unsigned DEFAULT NULL AFTER id";
         $sql[] = "ALTER TABLE sys_hw_sound ADD current enum('y','n') NOT NULL DEFAULT 'y' AFTER system_id";
         $sql[] = "ALTER TABLE sys_hw_sound CHANGE first_timestamp first_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER current";
         $sql[] = "ALTER TABLE sys_hw_sound CHANGE timestamp last_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER first_seen";
         $sql[] = "ALTER TABLE sys_hw_sound CHANGE sound_manufacturer manufacturer varchar(100) NOT NULL DEFAULT '' AFTER last_seen";
         $sql[] = "ALTER TABLE sys_hw_sound CHANGE sound_name model varchar(100) NOT NULL DEFAULT '' AFTER manufacturer";
         $sql[] = "ALTER TABLE sys_hw_sound CHANGE sound_device_id device varchar(100) NOT NULL DEFAULT '' AFTER model";
         $sql[] = "RENAME TABLE sys_hw_sound TO `sound`";
         # user
         $sql[] = "DELETE sys_sw_user FROM sys_sw_user LEFT JOIN system ON system.system_id = sys_sw_user.system_id WHERE sys_sw_user.timestamp <> system.timestamp";
         $sql[] = "ALTER TABLE sys_sw_user CHANGE user_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE sys_sw_user CHANGE system_id system_id int(10) unsigned DEFAULT NULL AFTER id";
         $sql[] = "ALTER TABLE sys_sw_user ADD current enum('y','n') NOT NULL DEFAULT 'y' AFTER system_id";
         $sql[] = "ALTER TABLE sys_sw_user CHANGE first_timestamp first_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER current";
         $sql[] = "ALTER TABLE sys_sw_user CHANGE timestamp last_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER first_seen";
         $sql[] = "ALTER TABLE sys_sw_user CHANGE user_name name varchar(100) NOT NULL DEFAULT '' AFTER last_seen";
         $sql[] = "ALTER TABLE sys_sw_user CHANGE user_caption caption varchar(255) NOT NULL DEFAULT '' AFTER name";
         $sql[] = "ALTER TABLE sys_sw_user CHANGE user_sid sid varchar(100) NOT NULL DEFAULT '' AFTER caption";
         $sql[] = "ALTER TABLE sys_sw_user CHANGE user_domain domain varchar(100) NOT NULL DEFAULT '' AFTER sid";
         $sql[] = "ALTER TABLE sys_sw_user CHANGE user_disabled disabled varchar(20) NOT NULL DEFAULT '' AFTER domain";
         $sql[] = "ALTER TABLE sys_sw_user CHANGE user_full_name full_name varchar(100) NOT NULL DEFAULT '' AFTER disabled";
         $sql[] = "ALTER TABLE sys_sw_user CHANGE user_password_changeable password_changeable varchar(20) NOT NULL DEFAULT '' AFTER full_name";
         $sql[] = "ALTER TABLE sys_sw_user CHANGE user_password_expires password_expires varchar(20) NOT NULL DEFAULT '' AFTER password_changeable";
         $sql[] = "ALTER TABLE sys_sw_user CHANGE user_password_required password_required varchar(20) NOT NULL DEFAULT '' AFTER password_expires";
         $sql[] = "ALTER TABLE sys_sw_user CHANGE user_status status varchar(100) NOT NULL DEFAULT '' AFTER password_required";
         $sql[] = "ALTER TABLE sys_sw_user CHANGE user_type type enum('local','domain','database','application','other') NOT NULL DEFAULT 'local' AFTER status";
         $sql[] = "RENAME TABLE sys_sw_user TO `user`";
         # variable
         $sql[] = "DELETE sys_sw_variable FROM sys_sw_variable LEFT JOIN system ON system.system_id = sys_sw_variable.system_id WHERE sys_sw_variable.timestamp <> system.timestamp";
         $sql[] = "ALTER TABLE sys_sw_variable CHANGE variable_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE sys_sw_variable CHANGE system_id system_id int(10) unsigned DEFAULT NULL AFTER id";
         $sql[] = "ALTER TABLE sys_sw_variable ADD current enum('y','n') NOT NULL DEFAULT 'y' AFTER system_id";
         $sql[] = "ALTER TABLE sys_sw_variable CHANGE first_timestamp first_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER current";
         $sql[] = "ALTER TABLE sys_sw_variable CHANGE timestamp last_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER first_seen";
         $sql[] = "ALTER TABLE sys_sw_variable CHANGE variable_name name varchar(100) NOT NULL DEFAULT '' AFTER last_seen";
         $sql[] = "ALTER TABLE sys_sw_variable CHANGE variable_value value text NOT NULL AFTER name";
         $sql[] = "RENAME TABLE sys_sw_variable TO `variable`";
         # video
         $sql[] = "DELETE sys_hw_video FROM sys_hw_video LEFT JOIN system ON system.system_id = sys_hw_video.system_id WHERE sys_hw_video.timestamp <> system.timestamp";
         $sql[] = "ALTER TABLE sys_hw_video CHANGE video_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE sys_hw_video CHANGE system_id system_id int(10) unsigned DEFAULT NULL AFTER id";
         $sql[] = "ALTER TABLE sys_hw_video ADD current enum('y','n') NOT NULL DEFAULT 'y' AFTER system_id";
         $sql[] = "ALTER TABLE sys_hw_video CHANGE first_timestamp first_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER current";
         $sql[] = "ALTER TABLE sys_hw_video CHANGE timestamp last_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER first_seen";
         $sql[] = "ALTER TABLE sys_hw_video CHANGE video_manufacturer manufacturer varchar(100) NOT NULL DEFAULT '' AFTER last_seen";
         $sql[] = "ALTER TABLE sys_hw_video CHANGE video_description model varchar(100) NOT NULL DEFAULT '' AFTER manufacturer";
         $sql[] = "ALTER TABLE sys_hw_video CHANGE video_device_id device varchar(100) NOT NULL DEFAULT '' AFTER model";
         $sql[] = "ALTER TABLE sys_hw_video CHANGE video_memory size int unsigned NOT NULL DEFAULT '0' AFTER device";
         $sql[] = "ALTER TABLE sys_hw_video CHANGE video_caption caption varchar(100) NOT NULL DEFAULT '' AFTER size";
         $sql[] = "ALTER TABLE sys_hw_video DROP video_current_horizontal_res";
         $sql[] = "ALTER TABLE sys_hw_video DROP video_current_vertical_res";
         $sql[] = "ALTER TABLE sys_hw_video DROP video_current_number_colours";
         $sql[] = "ALTER TABLE sys_hw_video DROP video_current_refresh_rate";
         $sql[] = "ALTER TABLE sys_hw_video DROP video_driver_date";
         $sql[] = "ALTER TABLE sys_hw_video DROP video_driver_version";
         $sql[] = "ALTER TABLE sys_hw_video DROP video_max_refresh_rate";
         $sql[] = "ALTER TABLE sys_hw_video DROP video_min_refresh_rate";
         $sql[] = "RENAME TABLE sys_hw_video TO `video`";
         # vm
         $sql[] = "DELETE sys_sw_virtual_machine FROM sys_sw_virtual_machine LEFT JOIN system ON system.system_id = sys_sw_virtual_machine.system_id WHERE sys_sw_virtual_machine.timestamp <> system.timestamp";
         $sql[] = "ALTER TABLE sys_sw_virtual_machine ADD current enum('y','n') NOT NULL DEFAULT 'y' AFTER system_id";
         $sql[] = "ALTER TABLE sys_sw_virtual_machine CHANGE first_timestamp first_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER current";
         $sql[] = "ALTER TABLE sys_sw_virtual_machine CHANGE timestamp last_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER first_seen";
         $sql[] = "ALTER TABLE sys_sw_virtual_machine CHANGE memory memory_count int(12) unsigned NOT NULL DEFAULT '0'";
         $sql[] = "ALTER TABLE sys_sw_virtual_machine CHANGE cpu cpu_count int(10) unsigned NOT NULL DEFAULT '0'";
         $sql[] = "ALTER TABLE sys_sw_virtual_machine CHANGE vm_id vm_id int(12) unsigned DEFAULT NULL";
         $sql[] = "ALTER TABLE sys_sw_virtual_machine ADD icon varchar(50) NOT NULL DEFAULT ''";
         $sql[] = "RENAME TABLE sys_sw_virtual_machine TO `vm`";
         # warranty
         $sql[] = "ALTER TABLE sys_hw_warranty CHANGE warranty_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE sys_hw_warranty CHANGE system_id system_id int(10) unsigned DEFAULT NULL AFTER id";
         $sql[] = "ALTER TABLE sys_hw_warranty ADD current enum('y','n') NOT NULL DEFAULT 'y' AFTER system_id";
         $sql[] = "ALTER TABLE sys_hw_warranty CHANGE first_timestamp first_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER current";
         $sql[] = "ALTER TABLE sys_hw_warranty CHANGE timestamp last_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER first_seen";
         $sql[] = "ALTER TABLE sys_hw_warranty CHANGE warranty_provider provider varchar(200) NOT NULL DEFAULT '' AFTER last_seen";
         $sql[] = "ALTER TABLE sys_hw_warranty CHANGE warranty_type type varchar(100) NOT NULL DEFAULT '' AFTER provider";
         $sql[] = "ALTER TABLE sys_hw_warranty CHANGE warranty_start start datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER type";
         $sql[] = "ALTER TABLE sys_hw_warranty CHANGE warranty_end end datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER start";
         $sql[] = "RENAME TABLE sys_hw_warranty TO `warranty`";
         # windows
         $sql[] = "DELETE sys_sw_windows FROM sys_sw_windows LEFT JOIN system ON system.system_id = sys_sw_windows.system_id WHERE sys_sw_windows.timestamp <> system.timestamp";
         $sql[] = "ALTER TABLE sys_sw_windows CHANGE windows_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE sys_sw_windows CHANGE system_id system_id int(10) unsigned DEFAULT NULL AFTER id";
         $sql[] = "ALTER TABLE sys_sw_windows ADD current enum('y','n') NOT NULL DEFAULT 'y' AFTER system_id";
         $sql[] = "ALTER TABLE sys_sw_windows CHANGE first_timestamp first_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER current";
         $sql[] = "ALTER TABLE sys_sw_windows CHANGE timestamp last_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER first_seen";
         $sql[] = "ALTER TABLE sys_sw_windows CHANGE windows_build_number build_number varchar(20) NOT NULL DEFAULT '' AFTER last_seen";
         $sql[] = "ALTER TABLE sys_sw_windows CHANGE windows_user_name user_name varchar(100) NOT NULL DEFAULT '' AFTER build_number";
         $sql[] = "ALTER TABLE sys_sw_windows CHANGE windows_client_site_name client_site_name varchar(100) NOT NULL DEFAULT '' AFTER user_name";
         $sql[] = "ALTER TABLE sys_sw_windows CHANGE windows_domain_short domain_short varchar(100) NOT NULL DEFAULT '' AFTER client_site_name";
         $sql[] = "ALTER TABLE sys_sw_windows CHANGE windows_domain_controller_address domain_controller_address varchar(100) NOT NULL DEFAULT '' AFTER domain_short";
         $sql[] = "ALTER TABLE sys_sw_windows CHANGE windows_domain_controller_name domain_controller_name varchar(100) NOT NULL DEFAULT '' AFTER domain_controller_address";
         $sql[] = "ALTER TABLE sys_sw_windows CHANGE windows_domain_role domain_role varchar(40) NOT NULL DEFAULT '' AFTER domain_controller_name";
         $sql[] = "ALTER TABLE sys_sw_windows CHANGE windows_part_of_domain part_of_domain varchar(10) NOT NULL DEFAULT '' AFTER domain_role";
         $sql[] = "ALTER TABLE sys_sw_windows CHANGE windows_id_number id_number varchar(100) NOT NULL DEFAULT '' AFTER part_of_domain";
         $sql[] = "ALTER TABLE sys_sw_windows CHANGE windows_time_caption time_caption varchar(100) NOT NULL DEFAULT '' AFTER id_number";
         $sql[] = "ALTER TABLE sys_sw_windows CHANGE windows_time_daylight time_daylight varchar(100) NOT NULL DEFAULT '' AFTER time_caption";
         $sql[] = "ALTER TABLE sys_sw_windows CHANGE windows_boot_device boot_device varchar(100) NOT NULL DEFAULT '' AFTER time_daylight";
         $sql[] = "ALTER TABLE sys_sw_windows CHANGE windows_country_code country_code varchar(50) NOT NULL DEFAULT '' AFTER boot_device";
         $sql[] = "ALTER TABLE sys_sw_windows CHANGE windows_organisation organisation varchar(80) NOT NULL DEFAULT '' AFTER country_code";
         $sql[] = "ALTER TABLE sys_sw_windows CHANGE windows_language language varchar(50) NOT NULL DEFAULT '' AFTER organisation";
         $sql[] = "ALTER TABLE sys_sw_windows CHANGE windows_registered_user registered_user varchar(100) NOT NULL DEFAULT '' AFTER language";
         $sql[] = "ALTER TABLE sys_sw_windows CHANGE windows_service_pack service_pack varchar(20) NOT NULL DEFAULT '' AFTER registered_user";
         $sql[] = "ALTER TABLE sys_sw_windows CHANGE windows_version version varchar(20) NOT NULL DEFAULT '' AFTER service_pack";
         $sql[] = "ALTER TABLE sys_sw_windows CHANGE windows_install_directory install_directory varchar(20) NOT NULL DEFAULT '' AFTER version";
         $sql[] = "ALTER TABLE sys_sw_windows CHANGE windows_active_directory_ou active_directory_ou varchar(200) NOT NULL DEFAULT '' AFTER install_directory";
         $sql[] = "ALTER TABLE sys_sw_windows CHANGE windows_workgroup workgroup varchar(255) NOT NULL DEFAULT '' AFTER active_directory_ou";
         $sql[] = "RENAME TABLE sys_sw_windows TO `windows`";
         # oa_alert_log -> change_log (list of detected changes)
         $sql[] = "DROP TABLE IF EXISTS change_log";
         $sql[] = "ALTER TABLE oa_alert_log DROP FOREIGN KEY oa_alert_log_user_id";
         $sql[] = "ALTER TABLE oa_alert_log DROP FOREIGN KEY oa_alert_log_system_id";
         $sql[] = "ALTER TABLE oa_alert_log DROP FOREIGN KEY oa_alert_oa_change";
         $sql[] = "ALTER TABLE oa_alert_log DROP KEY oa_alert_log_user_id";
         $sql[] = "ALTER TABLE oa_alert_log DROP KEY oa_alert_change_id";
         $sql[] = "ALTER TABLE oa_alert_log CHANGE alert_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE oa_alert_log CHANGE system_id system_id int(10) unsigned DEFAULT NULL AFTER id";
         $sql[] = "ALTER TABLE oa_alert_log CHANGE alert_table db_table varchar(50) NOT NULL DEFAULT '' AFTER system_id";
         $sql[] = "ALTER TABLE oa_alert_log CHANGE alert_foreign_row db_row int(10) unsigned NOT NULL DEFAULT '0' AFTER db_table";
         $sql[] = "ALTER TABLE oa_alert_log ADD db_action enum('','create','update','delete') NOT NULL DEFAULT '' AFTER db_row";
         $sql[] = "ALTER TABLE oa_alert_log CHANGE alert_details details varchar(200) NOT NULL DEFAULT '' AFTER db_action";
         $sql[] = "ALTER TABLE oa_alert_log CHANGE alert_ack_time ack_time datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER user_id";
         $sql[] = "ALTER TABLE oa_alert_log CHANGE alert_note note varchar(200) NOT NULL DEFAULT '' AFTER ack_time";
         $sql[] = "ALTER TABLE oa_alert_log CHANGE external_change_id external_ident varchar(200) NOT NULL DEFAULT '' AFTER ack_time";
         $sql[] = "ALTER TABLE oa_alert_log CHANGE external_change_link external_link varchar(200) NOT NULL DEFAULT '' AFTER ack_time";
         $sql[] = "ALTER TABLE oa_alert_log ADD CONSTRAINT change_log_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE";
         $sql[] = "RENAME TABLE oa_alert_log TO `change_log`";
         # sys_man_audits -> audit_log (list of audits)
         $sql[] = "DROP TABLE IF EXISTS audit_log";
         $sql[] = "CREATE TABLE audit_log ( \n                id int(10) unsigned NOT NULL AUTO_INCREMENT,\n                system_id int(10) unsigned DEFAULT '0',\n                username varchar(45) NOT NULL DEFAULT '',\n                type varchar(45) NOT NULL DEFAULT '',\n                ip varchar(45) NOT NULL DEFAULT '',\n                debug text NOT NULL DEFAULT '',\n                wmi_fails text NOT NULL DEFAULT '',\n                timestamp datetime NOT NULL DEFAULT '0000-00-00 00:00:00',\n                PRIMARY KEY (id),\n                KEY system_id (system_id),\n                CONSTRAINT audit_log_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE\n                ) ENGINE=InnoDB DEFAULT CHARSET=utf8";
         $sql[] = "INSERT INTO audit_log SELECT NULL, system_id, system_audits_username, system_audits_type, system_audits_ip, audit_debug, audit_wmi_fails, `timestamp` FROM sys_man_audits";
         $sql[] = "DROP TABLE IF EXISTS sys_man_audits";
         # oa_audit_log -> edit_log (list of edits by who [user||audit||snmp||etc])
         $sql[] = "DROP TABLE IF EXISTS edit_log";
         $sql[] = "CREATE TABLE edit_log (\n                id int(10) NOT NULL AUTO_INCREMENT,\n                user_id int(10) unsigned DEFAULT NULL,\n                system_id int(10) unsigned DEFAULT NULL,\n                details varchar(200) NOT NULL DEFAULT '',\n                source varchar(100) NOT NULL DEFAULT '',\n                weight int(10) unsigned NOT NULL DEFAULT '0',\n                db_table varchar(100) NOT NULL DEFAULT '',\n                db_column varchar(100) NOT NULL DEFAULT '',\n                timestamp datetime NOT NULL DEFAULT '0000-00-00 00:00:00',\n                value text NOT NULL DEFAULT '',\n                previous_value text NOT NULL DEFAULT '',\n                PRIMARY KEY (id),\n                KEY user_id (user_id),\n                KEY edit_log_system_id (system_id),\n                CONSTRAINT edit_log_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE,\n                CONSTRAINT edit_log_user_id FOREIGN KEY (user_id) REFERENCES oa_user (user_id)\n                ) ENGINE=InnoDB DEFAULT CHARSET=utf8";
         $sql[] = "INSERT INTO edit_log SELECT NULL as id, oa_audit_log.user_id, system_id, CONCAT(oa_user.user_full_name, ' edited the ', SUBSTRING(`audit_log_event_details`, 5, LOCATE(' ', `audit_log_event_details`) - 5), ' attribute.') as details, 'user' as source, '1000' as weight, 'system' as db_table, SUBSTRING(`audit_log_event_details`, 5, LOCATE(' ', `audit_log_event_details`) - 5) as db_column, timestamp, SUBSTRING(`audit_log_event_details` FROM LOCATE(' - ', `audit_log_event_details`)+3) as value, '' as previous_value FROM oa_audit_log LEFT JOIN oa_user on oa_audit_log.user_id = oa_user.user_id WHERE audit_log_event_details LIKE 'man_%'";
         $sql[] = "INSERT INTO edit_log SELECT NULL as id, oa_audit_log.user_id, system_id, CONCAT(oa_user.user_full_name, ' edited the name attribute.') as details, 'user' as source, '1000' as weight, 'system' as db_table, 'name' as db_column, timestamp, SUBSTRING(`audit_log_event_details` FROM LOCATE(' - ', `audit_log_event_details`)+3) as value, '' as previous_value FROM oa_audit_log LEFT JOIN oa_user on oa_audit_log.user_id = oa_user.user_id WHERE audit_log_event_details LIKE 'hostname - %'";
         $sql[] = "INSERT INTO edit_log SELECT NULL as id, oa_audit_log.user_id, system_id, CONCAT(oa_user.user_full_name, ' edited a custom attribute.') as details, 'user' as source, '1000' as weight, 'sys_additional_fields_data' as db_table, '' db_column, timestamp, SUBSTRING(`audit_log_event_details` FROM LOCATE(' - ', `audit_log_event_details`)+3) as value, '' as previous_value FROM oa_audit_log LEFT JOIN oa_user on oa_audit_log.user_id = oa_user.user_id WHERE audit_log_event_details LIKE 'additional_field_item%'";
         $sql[] = "DROP TABLE IF EXISTS oa_audit_log";
         # tasks (scheduled tasks / cron)
         $sql[] = "DROP TABLE IF EXISTS sys_sw_scheduled_task";
         $sql[] = "CREATE TABLE `task` (\n                  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,\n                  `system_id` int(10) unsigned DEFAULT NULL,\n                  `current` enum('y','n') NOT NULL DEFAULT 'y',\n                  `first_seen` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',\n                  `last_seen` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',\n                  `name` varchar(100) NOT NULL DEFAULT '',\n                  `next_run` varchar(50) NOT NULL DEFAULT '',\n                  `status` varchar(50) NOT NULL DEFAULT '',\n                  `last_run` varchar(50) NOT NULL DEFAULT '',\n                  `last_result` varchar(50) NOT NULL DEFAULT '',\n                  `creator` varchar(50) NOT NULL DEFAULT '',\n                  `schedule` varchar(100) NOT NULL DEFAULT '',\n                  `task` varchar(100) NOT NULL DEFAULT '',\n                  `state` varchar(10) NOT NULL DEFAULT '',\n                  `runas` varchar(50) NOT NULL DEFAULT '',\n                  PRIMARY KEY (`id`),\n                  KEY `system_id` (`system_id`),\n                  CONSTRAINT `task_system_id` FOREIGN KEY (`system_id`) REFERENCES `system` (`system_id`) ON DELETE CASCADE\n                ) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
         # server - new table
         $sql[] = "DROP TABLE IF EXISTS server";
         $sql[] = "CREATE TABLE server ( id int(10) unsigned NOT NULL AUTO_INCREMENT,\n                system_id int(10) unsigned DEFAULT NULL,\n                current enum('y','n') NOT NULL DEFAULT 'y',\n                first_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00',\n                last_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00',\n                type varchar(100) NOT NULL DEFAULT '',\n                name varchar(100) NOT NULL DEFAULT '',\n                full_name varchar(100) NOT NULL DEFAULT '',\n                description varchar(100) NOT NULL DEFAULT '',\n                version varchar(100) NOT NULL DEFAULT '',\n                version_string varchar(100) NOT NULL DEFAULT '',\n                edition varchar(100) NOT NULL DEFAULT '',\n                status varchar(100) NOT NULL DEFAULT '',\n                ip varchar(45) NOT NULL DEFAULT '',\n                port smallint unsigned NOT NULL DEFAULT '0',\n                PRIMARY KEY (id), KEY system_id (system_id),\n                CONSTRAINT server_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE )\n                ENGINE=InnoDB DEFAULT CHARSET=utf8";
         # server item - new table
         $sql[] = "DROP TABLE IF EXISTS server_item";
         $sql[] = "CREATE TABLE server_item (\n                id int(10) unsigned NOT NULL AUTO_INCREMENT,\n                system_id int(10) unsigned DEFAULT NULL,\n                current enum('y','n') NOT NULL DEFAULT 'y',\n                first_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00',\n                last_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00',\n                server_id int(10) unsigned DEFAULT NULL,\n                type varchar(100) NOT NULL DEFAULT '',\n                parent_name varchar(100) NOT NULL DEFAULT '',\n                name varchar(100) NOT NULL DEFAULT '',\n                description varchar(100) NOT NULL DEFAULT '',\n                id_internal varchar(100) NOT NULL DEFAULT '',\n                ip varchar(45) NOT NULL DEFAULT '',\n                hostname varchar(100) NOT NULL DEFAULT '',\n                port smallint unsigned NOT NULL DEFAULT '0',\n                status varchar(100) NOT NULL DEFAULT '',\n                parent_id int(11) unsigned DEFAULT NULL,\n                instance varchar(100) NOT NULL DEFAULT '',\n                `path` varchar(250) NOT NULL DEFAULT '',\n                size int unsigned NOT NULL DEFAULT '0',\n                log_status varchar(100) NOT NULL DEFAULT '',\n                log_format varchar(100) NOT NULL DEFAULT '',\n                log_path varchar(100) NOT NULL DEFAULT '',\n                log_rotation varchar(100) NOT NULL DEFAULT '',\n                PRIMARY KEY (id), KEY system_id (system_id),\n                CONSTRAINT server_item_system_id FOREIGN KEY (system_id) REFERENCES system (system_id) ON DELETE CASCADE)\n                ENGINE=InnoDB DEFAULT CHARSET=utf8";
         $sql[] = "UPDATE sys_sw_database SET db_version_string = 'SQL Server 2012 RTM'            WHERE db_version LIKE '11.0.2100%' OR db_version LIKE '11.00.2100%'";
         $sql[] = "UPDATE sys_sw_database SET db_version_string = 'SQL Server 2012 Service Pack 1' WHERE db_version LIKE '11.0.3000%' OR db_version LIKE '11.00.3000%'";
         $sql[] = "UPDATE sys_sw_database SET db_version_string = 'SQL Server 2012 Service Pack 2' WHERE db_version LIKE '11.0.5058%' OR db_version LIKE '11.00.5058%'";
         $sql[] = "UPDATE sys_sw_database SET db_version_string = 'SQL Server 2014 Community Technology Preview 1 (CTP1)' WHERE db_version LIKE '11.0.9120%' OR db_version LIKE '11.00.9120%'";
         $sql[] = "UPDATE sys_sw_database SET db_version_string = 'SQL Server 2014 Community Technology Preview 2 (CTP2)' WHERE db_version LIKE '12.0.1524%' OR db_version LIKE '12.00.1524%'";
         $sql[] = "UPDATE sys_sw_database SET db_version_string = 'SQL Server 2014 RTM'                                   WHERE db_version LIKE '12.0.2000%' OR db_version LIKE '12.00.2000%'";
         $sql[] = "DELETE sys_sw_database FROM sys_sw_database LEFT JOIN system ON system.system_id = sys_sw_database.system_id WHERE sys_sw_database.timestamp <> system.timestamp";
         $sql[] = "INSERT INTO server SELECT db_id, sys_sw_database.system_id, 'y', sys_sw_database.first_timestamp, sys_sw_database.timestamp, 'database', db_type, db_version_string, '', db_version, '', db_edition, '', '', db_port FROM sys_sw_database LEFT JOIN system ON sys_sw_database.system_id = system.system_id AND sys_sw_database.timestamp = system.last_seen";
         $sql[] = "DELETE sys_sw_database_details FROM sys_sw_database_details LEFT JOIN system ON system.system_id = sys_sw_database_details.system_id WHERE sys_sw_database_details.timestamp <> system.timestamp";
         $sql[] = "INSERT INTO server_item SELECT NULL, sys_sw_database.system_id, 'y', sys_sw_database_details.first_timestamp, sys_sw_database_details.timestamp, sys_sw_database_details.db_id, 'database', sys_sw_database.db_type, sys_sw_database_details.details_name, '', sys_sw_database_details.details_internal_id, '', '', '', '', '', sys_sw_database_details.details_instance, sys_sw_database_details.details_filename, sys_sw_database_details.details_current_size, '', '', '', '' FROM sys_sw_database_details LEFT JOIN sys_sw_database ON sys_sw_database_details.db_id = sys_sw_database.db_id AND sys_sw_database_details.timestamp = sys_sw_database.timestamp";
         $sql[] = "DELETE sys_sw_web_server FROM sys_sw_web_server LEFT JOIN system ON system.system_id = sys_sw_web_server.system_id WHERE sys_sw_web_server.timestamp <> system.timestamp";
         $sql[] = "INSERT INTO server SELECT NULL, sys_sw_web_server.system_id, 'y', sys_sw_web_server.first_timestamp, sys_sw_web_server.timestamp, 'web', 'IIS', '', '', sys_sw_web_server.webserver_version, '', '', sys_sw_web_server.webserver_state, '', '' FROM sys_sw_web_server";
         $sql[] = "DELETE sys_sw_web_site FROM sys_sw_web_site LEFT JOIN system ON system.system_id = sys_sw_web_site.system_id WHERE sys_sw_web_site.timestamp <> system.timestamp";
         $sql[] = "INSERT INTO server_item SELECT NULL as id, sys_sw_web_site.system_id, 'y' as current, sys_sw_web_site.first_timestamp as first_seen, sys_sw_web_site.timestamp as last_seen, '' as server_id, 'website' as type, 'IIS' as parent_name, sys_sw_web_site.site_description as name, sys_sw_web_site.site_description as description, sys_sw_web_site.site_internal_id as id_internal, '' as ip, '' as hostname, '' as port, sys_sw_web_site.site_state as status, '' as parent_id, sys_sw_web_site.site_app_pool as instance, sys_sw_web_site.site_path as path, sys_sw_web_site.site_size as size, '' as log_status, sys_sw_web_site.site_log_format as log_format, sys_sw_web_site.site_log_directory as log_path, sys_sw_web_site.site_log_rotation as log_rotation FROM sys_sw_web_site";
         $sql[] = "DROP TABLE IF EXISTS sys_sw_database_details";
         $sql[] = "DROP TABLE IF EXISTS sys_sw_database";
         $sql[] = "DROP TABLE IF EXISTS sys_sw_web_server_ext";
         $sql[] = "DROP TABLE IF EXISTS sys_sw_web_site_header";
         $sql[] = "DROP TABLE IF EXISTS sys_sw_web_site_virtual";
         $sql[] = "DROP TABLE IF EXISTS sys_sw_web_site";
         $sql[] = "DROP TABLE IF EXISTS sys_sw_web_server";
         $sql[] = "UPDATE system SET description = '', man_description = '' WHERE man_description LIKE 'general purpose|%' AND description = man_description";
         $sql[] = "UPDATE system SET description = '', man_description = '' WHERE man_description LIKE '%\\%)' AND description = man_description";
         $sql[] = "UPDATE system SET description = '', man_description = '' WHERE man_description LIKE '%|%|%' AND description = man_description";
         $sql[] = "UPDATE oa_config SET config_value = '20160104' WHERE config_name = 'internal_version'";
         $sql[] = "UPDATE oa_config SET config_value = '1.10' WHERE config_name = 'display_version'";
         foreach ($sql as $this_query) {
             $this->data['output'] .= $this_query . "<br /><br />\n";
             $log_details->message = $this_query;
             stdlog($log_details);
             $query = $this->db->query($this_query);
         }
         $this->load->model('m_oa_report');
         $sql = "DELETE oa_report FROM oa_report WHERE report_name = 'Changes'";
         if ($this->db->affected_rows() > 0) {
             $this->m_oa_report->activate_file('Changes - Acknowledged');
         }
         $sql = "DELETE oa_report FROM oa_report WHERE report_name = 'Alerts'";
         if ($this->db->affected_rows() > 0) {
             $this->m_oa_report->activate_file('Changes');
         }
         $sql = "DELETE oa_report FROM oa_report WHERE report_name = 'Alerts - Hardware'";
         if ($this->db->affected_rows() > 0) {
             $this->m_oa_report->activate_file('Changes - Hardware');
         }
         $sql = "DELETE oa_report FROM oa_report WHERE report_name = 'Alerts - Netstat Ports'";
         if ($this->db->affected_rows() > 0) {
             $this->m_oa_report->activate_file('Changes - Netstat Ports');
         }
         $sql = "DELETE oa_report FROM oa_report WHERE report_name = 'Alerts - New Systems'";
         if ($this->db->affected_rows() > 0) {
             $this->m_oa_report->activate_file('Changes - New Devices');
         }
         $sql = "DELETE oa_report FROM oa_report WHERE report_name = 'Alerts - Software'";
         if ($this->db->affected_rows() > 0) {
             $this->m_oa_report->activate_file('Changes - Software');
         }
         $sql = "DELETE oa_report FROM oa_report WHERE report_name = 'Alerts - Software Updates'";
         $log_details->message = 'Upgrade database to 1.10 completed';
         stdlog($log_details);
         unset($log_details);
     }
     if ($db_internal_version < '20160126' and $this->db->platform() == 'mysql') {
         # upgrade for 1.10.1
         $log_details = new stdClass();
         $log_details->file = 'system';
         $log_details->message = 'Upgrade database to 1.10.1 commenced';
         stdlog($log_details);
         $sql = array();
         $sql[] = "ALTER TABLE variable ADD program varchar(100) NOT NULL default '' AFTER last_seen";
         $sql[] = "UPDATE variable SET program = 'environment'";
         $sql[] = "UPDATE oa_config SET config_value = '20160126' WHERE config_name = 'internal_version'";
         $sql[] = "UPDATE oa_config SET config_value = '1.10.1' WHERE config_name = 'display_version'";
         foreach ($sql as $this_query) {
             $this->data['output'] .= $this_query . "<br /><br />\n";
             $log_details->message = $this_query;
             stdlog($log_details);
             $query = $this->db->query($this_query);
         }
         $log_details->message = 'Upgrade database to 1.10.1 completed';
         stdlog($log_details);
         unset($log_details);
     }
     if ($db_internal_version < '20160130' and $this->db->platform() == 'mysql') {
         # upgrade for 1.12
         $log_details = new stdClass();
         $log_details->file = 'system';
         $log_details->message = 'Upgrade database to 1.12 commenced';
         stdlog($log_details);
         $sql = array();
         $sql[] = "ALTER TABLE system ADD comments text NOT NULL AFTER description";
         $sql[] = "UPDATE oa_config SET config_value = '20160130' WHERE config_name = 'internal_version'";
         $sql[] = "UPDATE oa_config SET config_value = '1.12' WHERE config_name = 'display_version'";
         foreach ($sql as $this_query) {
             $this->data['output'] .= $this_query . "<br /><br />\n";
             $log_details->message = $this_query;
             stdlog($log_details);
             $query = $this->db->query($this_query);
         }
         $log_details->message = 'Upgrade database to 1.12 completed';
         stdlog($log_details);
         unset($log_details);
     }
     if ($db_internal_version < '20160303' and $this->db->platform() == 'mysql') {
         # upgrade for 1.12.2
         $log_details = new stdClass();
         $log_details->file = 'system';
         $log_details->message = 'Upgrade database to 1.12.2 commenced';
         stdlog($log_details);
         $sql = array();
         $sql[] = "UPDATE system SET man_class = 'virtual server' WHERE (manufacturer LIKE '%vmware%' OR manufacturer LIKE '%Parallels%') AND os_family IN ('Windows 2008', 'Windows 2012', 'Windows 2003')";
         $sql[] = "UPDATE system SET man_class = 'hypervisor' WHERE os_family LIKE 'VMware ESX%'";
         $sql[] = "UPDATE system SET man_class = 'virtual desktop' WHERE manufacturer LIKE '%vmware%' AND os_family IN ('Windows XP', 'Windows 7', 'Windows 8', 'Windows 10')";
         $sql[] = "DELETE FROM `oa_config` WHERE config_name = 'discovery_mac_match'";
         $sql[] = "INSERT INTO `oa_config` VALUES ('discovery_mac_match','n','y','0000-00-00 00:00:00',0,'Should we match a device based only on its mac address during discovery.')";
         $sql[] = "DELETE FROM `oa_config` WHERE config_name = 'discovery_linux_script_directory'";
         $sql[] = "INSERT INTO `oa_config` VALUES ('discovery_linux_script_directory','/tmp/','y','0000-00-00 00:00:00',0,'The directory the script is copied into on the target device.')";
         $sql[] = "DELETE FROM `oa_config` WHERE config_name = 'discovery_linux_script_permissions'";
         $sql[] = "INSERT INTO `oa_config` VALUES ('discovery_linux_script_permissions','700','y','0000-00-00 00:00:00',0,'The permissions set on the audit_linux.sh script when it is copied to the target device.')";
         $sql[] = "DELETE FROM `oa_config` WHERE config_name = 'discovery_nmap_os'";
         $sql[] = "INSERT INTO `oa_config` VALUES ('discovery_nmap_os','n','y','0000-00-00 00:00:00',0,'When discovery runs Nmap, should we use the -O flag to capture OS information (will slow down scan and requires SUID on the Nmap binary under Linux).')";
         $sql[] = "ALTER TABLE oa_user ADD permissions text NOT NULL default ''";
         $sql[] = "UPDATE oa_org SET org_name = 'Default Organisation' WHERE org_name = '' AND org_id = 0";
         $sql[] = "UPDATE oa_org SET org_comments = '' WHERE org_comments = 'Default Organisation.' AND org_id = 0";
         $sql[] = "DROP TABLE IF EXISTS `oa_user_org`";
         $sql[] = "CREATE TABLE `oa_user_org` (\n                      `id` int(10) NOT NULL AUTO_INCREMENT,\n                      `user_id` int(10) unsigned NOT NULL,\n                      `org_id` int(10) unsigned NOT NULL,\n                      `access_level` int(10) unsigned NOT NULL,\n                      `permissions` text NOT NULL DEFAULT '',\n                      PRIMARY KEY (`id`),\n                      KEY `user_id` (`user_id`),\n                      KEY `org_id` (`org_id`),\n                      CONSTRAINT `oa_user_org_user_id` FOREIGN KEY (`user_id`) REFERENCES `oa_user` (`user_id`) ON DELETE CASCADE,\n                      CONSTRAINT `oa_user_org_org_id` FOREIGN KEY (`org_id`) REFERENCES `oa_org` (`org_id`) ON DELETE CASCADE\n                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
         $sql[] = "INSERT INTO oa_user_org (SELECT NULL, oa_user.user_id, 0, 10, '' FROM oa_user LEFT JOIN oa_group_user ON (oa_user.user_id = oa_group_user.user_id AND oa_group_user.group_user_access_level = 10) WHERE oa_user.user_admin = 'y' OR oa_group_user.group_id = 1 GROUP BY oa_user.user_id)";
         $sql[] = "DROP TABLE IF EXISTS ip";
         $sql[] = "CREATE TABLE `ip` (\n              `id` int(10) unsigned NOT NULL AUTO_INCREMENT,\n              `system_id` int(10) unsigned DEFAULT NULL,\n              `current` enum('y','n') NOT NULL DEFAULT 'y',\n              `first_seen` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',\n              `last_seen` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',\n              `mac` varchar(200) NOT NULL DEFAULT '',\n              `net_index` varchar(10) NOT NULL DEFAULT '',\n              `ip` varchar(45) NOT NULL DEFAULT '',\n              `netmask` varchar(30) NOT NULL DEFAULT '',\n              `cidr` varchar(4) NOT NULL DEFAULT '',\n              `version` tinyint(3) unsigned NOT NULL DEFAULT '4',\n              `network` varchar(40) NOT NULL DEFAULT '',\n              `set_by` enum('','dhcp','static','auto','local') NOT NULL DEFAULT '',\n              PRIMARY KEY (`id`),\n              KEY `system_id` (`system_id`),\n              KEY `mac` (`mac`),\n              CONSTRAINT `ip_system_id` FOREIGN KEY (`system_id`) REFERENCES `system` (`system_id`) ON DELETE CASCADE\n            ) ENGINE=InnoDB DEFAULT CHARSET=utf8";
         $sql[] = "INSERT INTO ip (SELECT NULL, system_id, 'y', first_timestamp, `timestamp`, net_mac_address, net_index, ip_address_v4, ip_subnet, NULL, '4', '', '' FROM sys_hw_network_card_ip WHERE ip_address_version = '4')";
         $sql[] = "INSERT INTO ip (SELECT NULL, system_id, 'y', first_timestamp, `timestamp`, net_mac_address, net_index, ip_address_v6, NULL, ip_subnet, '6', '', '' FROM sys_hw_network_card_ip WHERE ip_address_version = '6')";
         $sql[] = "DROP TABLE IF EXISTS sys_hw_network_card_ip";
         $sql[] = "UPDATE oa_config SET config_value = '20160303' WHERE config_name = 'internal_version'";
         $sql[] = "UPDATE oa_config SET config_value = '1.12.2' WHERE config_name = 'display_version'";
         foreach ($sql as $this_query) {
             $this->data['output'] .= $this_query . "<br /><br />\n";
             $log_details->message = $this_query;
             stdlog($log_details);
             $query = $this->db->query($this_query);
         }
         // update the network groups
         $this->data['output'] .= "Converting network groups.<br /><br />\n";
         $sql = "SELECT group_id, group_dynamic_select, group_name FROM oa_group WHERE group_category = 'network'";
         $log_details->message = $sql;
         stdlog($log_details);
         $query = $this->db->query($sql);
         $result = $query->result();
         foreach ($result as $group) {
             $dynamic_select = $group->group_dynamic_select;
             $dynamic_select = str_replace("SELECT distinct(system.system_id) FROM system, sys_hw_network_card_ip", "SELECT distinct(system.system_id) FROM system, ip", $dynamic_select);
             $dynamic_select = str_replace("WHERE ( sys_hw_network_card_ip", "WHERE ( ip.version = '4' AND ip", $dynamic_select);
             $dynamic_select = str_replace("sys_hw_network_card_ip.ip_address_v4", "ip.ip", $dynamic_select);
             $dynamic_select = str_replace("sys_hw_network_card_ip.ip_subnet", "ip.netmask", $dynamic_select);
             $dynamic_select = str_replace("sys_hw_network_card_ip.timestamp = system.timestamp", "ip.current = 'y'", $dynamic_select);
             $dynamic_select = str_replace("oa_group_sys.group_id = ?", "oa_group_sys.group_id = @group", $dynamic_select);
             $dynamic_select = str_replace("ip.ip_address_v4", "ip.ip", $dynamic_select);
             $dynamic_select = str_replace("sys_hw_network_card_ip.system_id", "ip.system_id", $dynamic_select);
             $sql = "UPDATE oa_group SET group_dynamic_select = '" . $dynamic_select . "' WHERE group_id = " . intval($group->group_id);
             $sql = "UPDATE oa_group SET group_dynamic_select = \"" . $dynamic_select . "\" WHERE group_id = " . intval($group->group_id);
             $log_details->message = $sql;
             stdlog($log_details);
             $query = $this->db->query($sql);
             $this->data['output'] .= $this->db->last_query() . "<br /><br />\n";
         }
         # remove any groups that are using sys_hw_network_card_ip
         $sql = "SELECT group_name, group_dynamic_select from oa_group WHERE group_dynamic_select like '%sys_hw_network_card_ip%'";
         $query = $this->db->query($sql);
         $log_details->message = $sql;
         stdlog($log_details);
         $result = $query->result();
         foreach ($result as $row) {
             $this->data['output'] .= 'WARNING - the folloing group has been deleted as it used incompatible SQL. We no longer have a table named sys_hw_network_ip_address (it is now \'ip\' with renamed columns). Please recreate this group: ' . $row->group_name . '\\n<br />The SQL for this group was: ' . $row->group_dynamic_select . "<br /><br />\n";
         }
         $sql = "DELETE oa_group FROM oa_group WHERE group_dynamic_select like '%sys_hw_network_card_ip%'";
         $log_details->message = $sql;
         stdlog($log_details);
         $query = $this->db->query($sql);
         # remove any incorrectly formatted netmasks
         $sql = "UPDATE ip SET netmask = '0.0.0.0' WHERE netmask = '000.000.000.000'";
         $log_details->message = $sql;
         stdlog($log_details);
         $this->db->query($sql);
         # get all our candidate ip addresses and add a network name and a CIDR
         $sql = "SELECT * FROM ip WHERE ip.ip != '' AND ip.netmask != '' AND ip.netmask != '0.0.0.0' AND ip.version = 4 and ip.network = ''";
         $log_details->message = $sql;
         stdlog($log_details);
         $query = $this->db->query($sql);
         $result = $query->result();
         foreach ($result as $row) {
             $temp_long = ip2long($row->netmask);
             $temp_base = ip2long('255.255.255.255');
             $temp_cidr = 32 - log(($temp_long ^ $temp_base) + 1, 2);
             $network_details = network_details($row->ip . '/' . $temp_cidr);
             if (isset($network_details) and isset($network_details->network) and $network_details->network != '') {
                 $temp_network = $network_details->network . ' / ' . $temp_cidr;
                 $sql = "UPDATE ip SET network = ?, cidr = ? WHERE id = ?";
                 $data = array("{$temp_network}", "{$temp_cidr}", $row->id);
                 $this->db->query($sql, $data);
             }
             unset($temp_long);
             unset($temp_base);
             unset($temp_cidr);
             unset($network_details);
             unset($temp_network);
         }
         $log_details->message = 'Upgrade database to 1.12.2 completed';
         stdlog($log_details);
         unset($log_details);
     }
     if ($db_internal_version < '20160401' and $this->db->platform() == 'mysql') {
         # upgrade for 1.12.4
         $log_details = new stdClass();
         $log_details->file = 'system';
         $log_details->message = 'Upgrade database to 1.12.4 commenced';
         stdlog($log_details);
         $sql = array();
         $sql[] = "UPDATE oa_group SET group_category = 'org' WHERE group_category = 'owner'";
         $sql[] = "ALTER TABLE oa_group CHANGE group_category group_category enum('application','device','general','location','network','org','os') NOT NULL DEFAULT 'general'";
         $sql[] = "ALTER TABLE print_queue CHANGE system_key device varchar(200) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE print_queue DROP ip";
         $sql[] = "ALTER TABLE print_queue DROP type";
         $sql[] = "ALTER TABLE print_queue ADD type varchar(100) NOT NULL DEFAULT '' AFTER duplex";
         $sql[] = "ALTER TABLE print_queue CHANGE connection_status status varchar(100) NOT NULL DEFAULT '' AFTER type";
         $sql[] = "ALTER TABLE print_queue ADD capabilities varchar(200) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE print_queue ADD driver varchar(200) NOT NULL DEFAULT ''";
         $sql[] = "UPDATE oa_config SET config_value = '20160401' WHERE config_name = 'internal_version'";
         $sql[] = "UPDATE oa_config SET config_value = '1.12.4' WHERE config_name = 'display_version'";
         foreach ($sql as $this_query) {
             $this->data['output'] .= $this_query . "<br /><br />\n";
             $log_details->message = $this_query;
             stdlog($log_details);
             $query = $this->db->query($this_query);
         }
         $log_details->message = 'Upgrade database to 1.12.4 completed';
         stdlog($log_details);
         unset($log_details);
     }
     if ($db_internal_version < '20160409' and $this->db->platform() == 'mysql') {
         # upgrade for 1.12.6
         $log_details = new stdClass();
         $log_details->file = 'system';
         $log_details->message = 'Upgrade database to 1.12.6 commenced';
         stdlog($log_details);
         unset($sql);
         $sql = array();
         # we're removving the foreign key between additional fields and groups
         $sql[] = "ALTER TABLE sys_man_additional_fields DROP FOREIGN KEY `sys_man_additional_fields_group_id`";
         $sql[] = "ALTER TABLE sys_man_additional_fields DROP KEY `sys_man_additional_fields_group`";
         # this should be unused now - groups and reports refreshed further down
         $sql[] = "ALTER TABLE system DROP man_icon";
         # drop this key so we can change org_id to id
         $sql[] = "ALTER TABLE oa_user_org DROP FOREIGN KEY oa_user_org_org_id";
         # change the oa_org to the new SQL schema style
         $sql[] = "ALTER TABLE oa_org CHANGE org_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE oa_org CHANGE org_name name varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE oa_org CHANGE org_parent_id parent_id int(10) unsigned DEFAULT '0'";
         $sql[] = "ALTER TABLE oa_org CHANGE org_group_id group_id int(10) unsigned DEFAULT '0'";
         $sql[] = "ALTER TABLE oa_org DROP contact_id";
         $sql[] = "ALTER TABLE oa_org DROP org_picture";
         $sql[] = "ALTER TABLE oa_org CHANGE org_comments comments text NOT NULL DEFAULT ''";
         $sql[] = "UPDATE oa_org SET name = 'Default Organisation' WHERE id = 0";
         # now add the key back
         $sql[] = "ALTER TABLE oa_user_org ADD CONSTRAINT oa_user_org_org_id FOREIGN KEY (org_id) REFERENCES oa_org (id) ON DELETE CASCADE";
         # drop these foreign keys so we can change user_id to id
         $sql[] = "ALTER TABLE edit_log DROP FOREIGN KEY edit_log_user_id";
         $sql[] = "ALTER TABLE oa_change DROP FOREIGN KEY oa_change_user_id";
         $sql[] = "ALTER TABLE oa_group_user DROP FOREIGN KEY oa_group_user_user_id";
         $sql[] = "ALTER TABLE oa_user_org DROP FOREIGN KEY oa_user_org_user_id";
         $sql[] = "ALTER TABLE sys_man_attachment DROP FOREIGN KEY att_user_id";
         $sql[] = "ALTER TABLE sys_man_attachment DROP KEY att_user_id";
         $sql[] = "ALTER TABLE sys_man_notes DROP FOREIGN KEY sys_man_notes_user_id";
         # change the user table to the new SQL schema format
         $sql[] = "ALTER TABLE oa_user CHANGE user_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE oa_user CHANGE user_name name varchar(100) NOT NULL";
         $sql[] = "ALTER TABLE oa_user CHANGE user_password password varchar(250) NOT NULL";
         $sql[] = "ALTER TABLE oa_user CHANGE user_full_name full_name varchar(100) NOT NULL";
         $sql[] = "ALTER TABLE oa_user CHANGE user_email email varchar(100) NOT NULL";
         $sql[] = "ALTER TABLE oa_user CHANGE user_lang lang varchar(100) NOT NULL";
         $sql[] = "ALTER TABLE oa_user CHANGE user_display_number display_count smallint(6) NOT NULL DEFAULT '10'";
         $sql[] = "ALTER TABLE oa_user CHANGE user_theme theme varchar(100) NOT NULL";
         $sql[] = "ALTER TABLE oa_user CHANGE user_admin admin varchar(1) NOT NULL";
         $sql[] = "ALTER TABLE oa_user CHANGE user_active active varchar(1) NOT NULL DEFAULT 'y'";
         $sql[] = "ALTER TABLE oa_user CHANGE user_sam sam int(10) NOT NULL DEFAULT '1'";
         $sql[] = "ALTER TABLE oa_user DROP user_change";
         # now add the foreign keys back
         $sql[] = "ALTER TABLE edit_log ADD CONSTRAINT edit_log_user_id FOREIGN KEY (user_id) REFERENCES oa_user (id)";
         $sql[] = "ALTER TABLE oa_change ADD CONSTRAINT oa_change_user_id FOREIGN KEY (user_id) REFERENCES oa_user (id)";
         $sql[] = "ALTER TABLE oa_group_user ADD CONSTRAINT oa_group_user_user_id FOREIGN KEY (user_id) REFERENCES oa_user (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE oa_user_org ADD CONSTRAINT oa_user_org_user_id FOREIGN KEY (user_id) REFERENCES oa_user (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE sys_man_notes ADD CONSTRAINT sys_man_notes_user_id FOREIGN KEY (user_id) REFERENCES oa_user (id)";
         # change the location table to use the new SQL schema format
         $sql[] = "ALTER TABLE oa_location CHANGE location_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE oa_location CHANGE location_name name varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE oa_location CHANGE location_type type varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE oa_location CHANGE location_room room varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE oa_location CHANGE location_suite suite varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE oa_location CHANGE location_level level varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE oa_location CHANGE location_address address varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE oa_location CHANGE location_suburb suburb varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE oa_location CHANGE location_city city varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE oa_location CHANGE location_district district varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE oa_location CHANGE location_region region varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE oa_location CHANGE location_area area varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE oa_location CHANGE location_state state varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE oa_location CHANGE location_postcode postcode varchar(10) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE oa_location CHANGE location_country country varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE oa_location CHANGE location_tags tags varchar(250) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE oa_location CHANGE location_phone phone varchar(20) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE oa_location CHANGE location_picture picture varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE oa_location CHANGE location_latitude latitude float(10,6) NOT NULL";
         $sql[] = "ALTER TABLE oa_location CHANGE location_longitude longitude float(10,6) NOT NULL";
         $sql[] = "ALTER TABLE oa_location CHANGE location_geo geo varchar(200) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE oa_location CHANGE location_comments comments varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE oa_location CHANGE location_icon icon varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE oa_location CHANGE location_group_id group_id int(10) unsigned NOT NULL DEFAULT '0'";
         # this is unused and having 'count' as a column name is not ideal because it's a SQL reserved word
         $sql[] = "ALTER TABLE service DROP count";
         # allow for some silly long serial numbers
         $sql[] = "ALTER TABLE system CHANGE `serial` `serial` varchar(250) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE system CHANGE `man_serial` `man_serial` varchar(250) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE system ADD `dbus_identifier` varchar(255) NOT NULL DEFAULT '' AFTER uuid";
         # a new function we'll use for checking if an IP is in a blessed subnet
         $sql[] = "DROP FUNCTION IF EXISTS cidr_to_mask";
         $sql[] = "CREATE FUNCTION cidr_to_mask (cidr INT(2)) RETURNS CHAR(15) DETERMINISTIC RETURN INET_NTOA(CONV(CONCAT(REPEAT(1,cidr),REPEAT(0,32-cidr)),2,10))";
         # our new blessed subnets config item
         $sql[] = "UPDATE `ip` SET `network` = REPLACE(`network`, ' ', '')";
         $sql[] = "INSERT INTO `oa_config` VALUES ('blessed_subnets_use','y','y','0000-00-00 00:00:00',0,'Should we only accept data from the blessed subnets list.')";
         # new table for network descriptions and blessed subnets
         $sql[] = "DROP TABLE IF EXISTS `networks`";
         $sql[] = "CREATE TABLE `networks` (`id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(200) NOT NULL DEFAULT '', `description` text NOT NULL, `edited_by` varchar(200) NOT NULL DEFAULT '', `edited_date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8";
         $sql[] = "INSERT INTO `networks` SELECT NULL, REPLACE(REPLACE(`group_name`, ' ', ''), 'Network-', '')  AS name, TRIM(both '\t' from group_description) as description, 'system upgrade' as edited_by, NOW() as edited_date FROM oa_group WHERE group_category = 'network' AND SUBSTR(REPLACE(REPLACE(`group_name`, ' ', ''), 'Network-', ''),1,LOCATE('/',REPLACE(REPLACE(`group_name`, ' ', ''), 'Network-', ''))-1) != `group_description`";
         $sql[] = "INSERT INTO `networks` (SELECT NULL, ip.network as name, '' as description, 'system upgrade' as edited_by, NOW() as edited_date FROM ip WHERE network NOT IN (SELECT networks.name FROM networks) AND ip.network != '' GROUP BY ip.network)";
         $sql[] = "DROP TABLE IF EXISTS `chart`";
         $sql[] = "CREATE TABLE `chart` ( `when` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', `what` varchar(50) NOT NULL DEFAULT '', `org_id` int unsigned NOT NULL DEFAULT 0, `count` int unsigned NOT NULL DEFAULT 0, PRIMARY KEY (`when`, `what`, `org_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8";
         $sql[] = "INSERT INTO chart (`when`, `what`, `org_id`, `count`) (SELECT DATE(audit_log.timestamp) as `when`, 'audit' as `what`, system.man_org_id as `org_id`, count(audit_log.system_id) AS `new_count` FROM audit_log LEFT JOIN system ON (audit_log.system_id = system.system_id) WHERE audit_log.type = 'audit' AND system.man_org_id IS NOT NULL GROUP BY system.man_org_id, DATE(audit_log.timestamp) ORDER BY DATE(audit_log.timestamp))";
         $sql[] = "INSERT INTO chart (`when`, `what`, `org_id`, `count`) (SELECT DATE(audit_log.timestamp) as `when`, 'snmp' as `what`, system.man_org_id as `org_id`, count(audit_log.system_id) AS `count` FROM audit_log LEFT JOIN system ON (audit_log.system_id = system.system_id) WHERE audit_log.type = 'snmp' AND system.man_org_id IS NOT NULL GROUP BY system.man_org_id, DATE(audit_log.timestamp) ORDER BY DATE(audit_log.timestamp))";
         $sql[] = "INSERT INTO chart (`when`, `what`, `org_id`, `count`) (SELECT DATE(audit_log.timestamp) as `when`, 'nmap' as `what`, system.man_org_id as `org_id`, count(audit_log.system_id) AS `count` FROM audit_log LEFT JOIN system ON (audit_log.system_id = system.system_id) WHERE audit_log.type = 'nmap' AND system.man_org_id IS NOT NULL GROUP BY system.man_org_id, DATE(audit_log.timestamp) ORDER BY DATE(audit_log.timestamp))";
         $sql[] = "INSERT INTO chart (`when`, `what`, `org_id`, `count`) (SELECT DATE(change_log.timestamp) as `when`, CONCAT(change_log.db_table, '_', change_log.db_action) as `what`, system.man_org_id as `org_id`, count(change_log.id) AS `count` FROM change_log LEFT JOIN system ON (change_log.system_id = system.system_id) WHERE DATE(change_log.timestamp) >= '2015-01-01' AND change_log.db_table != 'system' GROUP BY system.man_org_id, CONCAT(change_log.db_table, '_', change_log.db_action), DATE(change_log.timestamp) ORDER BY DATE(change_log.timestamp))";
         $sql[] = "INSERT INTO chart (`when`, `what`, `org_id`, `count`) (SELECT DATE(`first_timestamp`) as `when`, 'system_create' as `what`, system.man_org_id as `org_id`, count(system_id) AS `count` FROM system WHERE DATE(`first_timestamp`) >= '2015-01-01' GROUP BY DATE(`first_timestamp`), man_org_id ORDER BY DATE(`first_timestamp`))";
         # set our versions
         $sql[] = "UPDATE oa_config SET config_value = '20160409' WHERE config_name = 'internal_version'";
         $sql[] = "UPDATE oa_config SET config_value = '1.12.6' WHERE config_name = 'display_version'";
         foreach ($sql as $this_query) {
             $this->data['output'] .= $this_query . "<br /><br />\n";
             $log_details->message = $this_query;
             stdlog($log_details);
             $query = $this->db->query($this_query);
         }
         // update any leftover group definitions by changing man_icon to icon
         $sql = "UPDATE oa_group SET group_display_sql = REPLACE(group_display_sql, 'man_icon', 'icon')";
         $log_details->message = $sql;
         stdlog($log_details);
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_group_column SET column_variable = 'icon' WHERE column_variable = 'man_icon'";
         $log_details->message = $sql;
         stdlog($log_details);
         $query = $this->db->query($sql);
         // update any leftover report definitions by changing man_icon to icon
         $sql = "UPDATE oa_report SET report_sql = REPLACE(report_sql, 'man_icon', 'icon')";
         $log_details->message = $sql;
         stdlog($log_details);
         $query = $this->db->query($sql);
         $sql = "UPDATE oa_report_column SET column_variable = 'icon' WHERE column_variable = 'man_icon'";
         $log_details->message = $sql;
         stdlog($log_details);
         $query = $this->db->query($sql);
         # have to re-run this as we left it in the original SQL script.
         $sql = "UPDATE oa_group SET group_category = 'org' WHERE group_category = 'owner'";
         $log_details->message = $sql;
         stdlog($log_details);
         $query = $this->db->query($sql);
         $sql = "ALTER TABLE oa_group CHANGE group_category group_category enum('application','device','general','location','network','org','os') NOT NULL DEFAULT 'general'";
         $log_details->message = $sql;
         stdlog($log_details);
         $query = $this->db->query($sql);
         foreach ($this->m_oa_config->get_server_subnets() as $subnet) {
             $this->m_oa_config->update_blessed($subnet, 0);
         }
         $log_details->message = 'Upgrade database to 1.12.6 completed';
         stdlog($log_details);
         unset($log_details);
     }
     if ($db_internal_version < '20160620' and $this->db->platform() == 'mysql') {
         # upgrade for 1.12.8
         $log_details = new stdClass();
         $log_details->file = 'system';
         $log_details->message = 'Upgrade database to 1.12.8 commenced';
         stdlog($log_details);
         # initialise our $sql array
         unset($sql);
         $sql = array();
         $sql_indexes = "SELECT TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = '" . $this->db->database . "' AND  REFERENCED_TABLE_NAME = 'system' and REFERENCED_COLUMN_NAME = 'system_id'";
         $query = $this->db->query($sql_indexes);
         $result = $query->result();
         foreach ($result as $item) {
             $sql[] = "ALTER TABLE `" . $item->TABLE_NAME . "` DROP FOREIGN KEY " . $item->CONSTRAINT_NAME;
         }
         unset($sql_indexes);
         $sql[] = "ALTER TABLE system DROP KEY id";
         $sql[] = "ALTER TABLE system DROP KEY id2";
         $sql[] = "ALTER TABLE system DROP KEY id3";
         $sql[] = "ALTER TABLE system DROP KEY hostname";
         $sql[] = "ALTER TABLE system DROP KEY linked_sys";
         $sql[] = "ALTER TABLE system DROP KEY system_key";
         $sql[] = "ALTER TABLE system CHANGE system_id system_id int(10) unsigned NOT NULL";
         $sql[] = "ALTER TABLE system DROP PRIMARY KEY";
         $sql[] = "ALTER TABLE system DROP KEY system_id";
         $sql[] = "ALTER TABLE system CHANGE system_id id int(10) unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT FIRST";
         $sql[] = "ALTER TABLE system DROP system_key";
         $sql[] = "ALTER TABLE system DROP system_key_type";
         $sql[] = "ALTER TABLE system CHANGE uuid uuid varchar(100) NOT NULL DEFAULT '' AFTER id";
         $sql[] = "ALTER TABLE system CHANGE hostname name varchar(100) NOT NULL DEFAULT '' AFTER uuid";
         $sql[] = "ALTER TABLE system CHANGE man_ip_address ip varchar(45) NOT NULL DEFAULT '' AFTER name";
         $sql[] = "ALTER TABLE system ADD hostname varchar(100) NOT NULL default '' AFTER ip";
         $sql[] = "ALTER TABLE system ADD dns_hostname varchar(100) NOT NULL default '' AFTER hostname";
         $sql[] = "ALTER TABLE system DROP domain";
         $sql[] = "ALTER TABLE system CHANGE man_domain domain varchar(100) NOT NULL DEFAULT '' AFTER dns_hostname";
         $sql[] = "ALTER TABLE system ADD dns_domain varchar(100) NOT NULL default '' AFTER domain";
         $sql[] = "ALTER TABLE system DROP description";
         $sql[] = "ALTER TABLE system CHANGE man_description description text NOT NULL AFTER fqdn";
         $sql[] = "ALTER TABLE system DROP type";
         $sql[] = "ALTER TABLE system CHANGE man_type type varchar(50) NOT NULL DEFAULT '' AFTER description";
         $sql[] = "ALTER TABLE system DROP os_group";
         $sql[] = "ALTER TABLE system CHANGE man_os_group os_group varchar(50) NOT NULL DEFAULT '' AFTER icon";
         $sql[] = "ALTER TABLE system DROP os_family";
         $sql[] = "ALTER TABLE system CHANGE man_os_family os_family varchar(50) NOT NULL DEFAULT '' AFTER os_group";
         $sql[] = "ALTER TABLE system DROP os_name";
         $sql[] = "ALTER TABLE system CHANGE man_os_name os_name varchar(100) NOT NULL DEFAULT '' AFTER os_family";
         $sql[] = "ALTER TABLE system CHANGE linked_sys attached_system_id int(10) DEFAULT NULL";
         $sql[] = "ALTER TABLE system DROP manufacturer";
         $sql[] = "ALTER TABLE system CHANGE man_manufacturer manufacturer varchar(100) NOT NULL DEFAULT '' AFTER attached_system_id";
         $sql[] = "ALTER TABLE system DROP model";
         $sql[] = "ALTER TABLE system CHANGE man_model model varchar(200) NOT NULL DEFAULT '' AFTER manufacturer";
         $sql[] = "ALTER TABLE system DROP `serial`";
         $sql[] = "ALTER TABLE system CHANGE man_serial `serial` varchar(200) NOT NULL DEFAULT '' AFTER model";
         $sql[] = "ALTER TABLE system DROP form_factor";
         $sql[] = "ALTER TABLE system CHANGE man_form_factor form_factor varchar(50) NOT NULL DEFAULT '' AFTER uptime";
         $sql[] = "ALTER TABLE system CHANGE pc_os_bit os_bit tinyint unsigned NOT NULL DEFAULT '0'";
         $sql[] = "ALTER TABLE system CHANGE pc_memory memory_count int unsigned NOT NULL DEFAULT '0'";
         $sql[] = "ALTER TABLE system CHANGE pc_num_processor processor_count tinyint unsigned NOT NULL DEFAULT '0'";
         $sql[] = "ALTER TABLE system CHANGE pc_date_os_installation os_installation_date date NOT NULL DEFAULT '0000-00-00'";
         $sql[] = "UPDATE system SET printer_color = 'y' WHERE LOWER(printer_color) ='true' OR LOWER(printer_color) = 't'";
         $sql[] = "UPDATE system SET printer_color = 'n' WHERE LOWER(printer_color) ='false' OR LOWER(printer_color) = 'f'";
         $sql[] = "ALTER TABLE system CHANGE printer_color printer_color enum('y','n','') NOT NULL DEFAULT ''";
         $sql[] = "UPDATE system SET printer_duplex = 'y' WHERE LOWER(printer_duplex) ='true' OR LOWER(printer_duplex) = 't'";
         $sql[] = "UPDATE system SET printer_duplex = 'n' WHERE LOWER(printer_duplex) ='false' OR LOWER(printer_duplex) = 'f'";
         $sql[] = "ALTER TABLE system CHANGE printer_duplex printer_duplex enum('y','n','') NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE system CHANGE man_status status enum('production','deleted','lost','maintenance','retired','unallocated') NOT NULL DEFAULT 'production'";
         $sql[] = "ALTER TABLE system CHANGE man_environment environment enum('production','dev','dr','eval','pre-prod','test','train','uat') NOT NULL DEFAULT 'production'";
         $sql[] = "ALTER TABLE system CHANGE man_class class enum('desktop','laptop','tablet','workstation','server','virtual server','virtual desktop','hypervisor','') NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE system CHANGE man_function function varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE system CHANGE man_owner owner varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE system CHANGE man_org_id org_id int(10) unsigned NOT NULL DEFAULT '0'";
         $sql[] = "ALTER TABLE system DROP man_criticality";
         $sql[] = "ALTER TABLE system CHANGE man_location_id location_id int(10) unsigned NOT NULL DEFAULT '0'";
         $sql[] = "ALTER TABLE system CHANGE man_location_level location_level varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE system CHANGE man_location_suite location_suite varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE system CHANGE man_location_room location_room varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE system CHANGE man_location_rack location_rack varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE system CHANGE man_location_rack_position location_rack_position varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE system CHANGE man_location_rack_size location_rack_size int(10) unsigned NOT NULL DEFAULT '0'";
         $sql[] = "ALTER TABLE system CHANGE man_location_latitude location_latitude float(10,6) NOT NULL";
         $sql[] = "ALTER TABLE system CHANGE man_location_longitude location_longitude float(10,6) NOT NULL";
         $sql[] = "ALTER TABLE system CHANGE man_asset_number asset_number varchar(50) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE system CHANGE man_vm_server_name vm_server_name varchar(150) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE system CHANGE man_vm_system_id vm_system_id int(10) unsigned DEFAULT NULL";
         $sql[] = "ALTER TABLE system CHANGE man_vm_group vm_group varchar(150) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE system CHANGE man_cluster_name cluster_name varchar(150) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE system ADD cluster_type varchar(150) NOT NULL DEFAULT '' AFTER cluster_name";
         $sql[] = "ALTER TABLE system CHANGE invoice_id invoice_id int(10) unsigned DEFAULT NULL";
         $sql[] = "ALTER TABLE system CHANGE man_purchase_invoice purchase_invoice varchar(50) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE system CHANGE man_purchase_order_number purchase_order_number varchar(50) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE system CHANGE man_purchase_cost_center purchase_cost_center varchar(50) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE system CHANGE man_purchase_vendor purchase_vendor varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE system CHANGE man_purchase_date purchase_date date NOT NULL DEFAULT '0000-00-00'";
         $sql[] = "ALTER TABLE system CHANGE man_purchase_service_contract_number purchase_service_contract_number varchar(255) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE system CHANGE man_lease_expiry_date lease_expiry_date date NOT NULL DEFAULT '0000-00-00'";
         $sql[] = "ALTER TABLE system CHANGE man_purchase_amount purchase_amount varchar(50) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE system CHANGE man_warranty_duration warranty_duration int(5) unsigned NOT NULL DEFAULT '0'";
         $sql[] = "ALTER TABLE system CHANGE man_warranty_expires warranty_expires date NOT NULL DEFAULT '0000-00-00'";
         $sql[] = "ALTER TABLE system CHANGE man_warranty_type warranty_type enum('','24x7x365','9x5x5','Next Business Day') NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE system DROP man_terminal_number";
         $sql[] = "ALTER TABLE system DROP nmap_type";
         $sql[] = "ALTER TABLE system DROP contact_id";
         $sql[] = "ALTER TABLE system CHANGE man_switch_id switch_system_id int(10) DEFAULT NULL";
         $sql[] = "ALTER TABLE system CHANGE man_switch_port switch_port int unsigned NOT NULL DEFAULT '0'";
         $sql[] = "ALTER TABLE system CHANGE man_patch_panel patch_panel varchar(45) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE system CHANGE man_patch_panel_port patch_panel_port_new int unsigned NOT NULL DEFAULT '0'";
         $sql[] = "ALTER TABLE system CHANGE patch_panel_port_new patch_panel_port int unsigned NOT NULL DEFAULT '0'";
         $sql[] = "ALTER TABLE system CHANGE man_wall_port wall_port varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE system DROP man_picture";
         $sql[] = "ALTER TABLE system CHANGE man_service_number service_number varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE system CHANGE man_service_provider service_provider varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE system CHANGE man_service_type service_type varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE system CHANGE man_service_plan service_plan varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE system CHANGE man_service_network service_network varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE system CHANGE man_unlock_pin unlock_pin varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE system CHANGE man_serial_imei serial_imei varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE system CHANGE man_serial_sim serial_sim varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE system CHANGE nmis_export nmis_export enum('true','false','y','n') NOT NULL DEFAULT 'false'";
         $sql[] = "UPDATE system SET nmis_export = 'n' WHERE LOWER(nmis_export) ='false'";
         $sql[] = "UPDATE system SET nmis_export = 'y' WHERE LOWER(nmis_export) ='true'";
         $sql[] = "ALTER TABLE system CHANGE nmis_export nmis_export enum('y','n') NOT NULL DEFAULT 'n'";
         $sql[] = "ALTER TABLE system CHANGE man_oae_manage oae_manage enum('y','n') NOT NULL DEFAULT 'y' AFTER nmis_export";
         $sql[] = "ALTER TABLE system CHANGE snmp_oid snmp_oid text NOT NULL AFTER oae_manage";
         $sql[] = "ALTER TABLE system DROP last_seen";
         $sql[] = "ALTER TABLE system CHANGE first_timestamp first_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER sysLocation";
         $sql[] = "ALTER TABLE system CHANGE timestamp last_seen datetime NOT NULL DEFAULT '0000-00-00 00:00:00' AFTER first_seen";
         $sql[] = "ALTER TABLE system CHANGE last_seen_by last_seen_by varchar(150) NOT NULL DEFAULT '' AFTER last_seen";
         $sql[] = "ALTER TABLE system CHANGE last_user last_user varchar(150) NOT NULL DEFAULT '' AFTER last_seen_by";
         $sql[] = "ALTER TABLE system ADD KEY ip (`ip`)";
         $sql[] = "ALTER TABLE system ADD KEY name (`name`)";
         # recreate the indexes
         $sql[] = "ALTER TABLE audit_log ADD CONSTRAINT audit_log_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE bios ADD CONSTRAINT bios_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE change_log ADD CONSTRAINT change_log_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE disk ADD CONSTRAINT disk_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE dns ADD CONSTRAINT dns_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE graph ADD CONSTRAINT graph_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE ip ADD CONSTRAINT ip_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE log ADD CONSTRAINT log_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE memory ADD CONSTRAINT memory_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE module ADD CONSTRAINT module_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE monitor ADD CONSTRAINT monitor_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE motherboard ADD CONSTRAINT motherboard_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE netstat ADD CONSTRAINT netstat_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE network ADD CONSTRAINT network_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE oa_group_sys ADD CONSTRAINT oa_group_sys_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE optical ADD CONSTRAINT optical_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE pagefile ADD CONSTRAINT pagefile_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE `partition` ADD CONSTRAINT partition_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE print_queue ADD CONSTRAINT print_queue_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE processor ADD CONSTRAINT processor_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE route ADD CONSTRAINT route_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE san ADD CONSTRAINT san_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE scsi ADD CONSTRAINT scsi_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE server ADD CONSTRAINT server_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE server_item ADD CONSTRAINT server_item_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE service ADD CONSTRAINT service_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE share ADD CONSTRAINT share_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE software ADD CONSTRAINT software_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE software_key ADD CONSTRAINT software_key_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE sound ADD CONSTRAINT sound_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE sys_man_additional_fields_data ADD CONSTRAINT additional_field_item_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE sys_man_attachment ADD CONSTRAINT attachment_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE sys_man_notes ADD CONSTRAINT notes_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE task ADD CONSTRAINT task_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE user ADD CONSTRAINT user_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE user_group ADD CONSTRAINT user_group_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE variable ADD CONSTRAINT variable_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE video ADD CONSTRAINT video_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE vm ADD CONSTRAINT vm_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE warranty ADD CONSTRAINT warranty_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE windows ADD CONSTRAINT windows_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "RENAME TABLE sys_man_attachment TO `attachment`";
         $sql[] = "ALTER TABLE `attachment` CHANGE att_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE `attachment` CHANGE `att_title` `title` varchar(200) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE `attachment` CHANGE `att_filename` `filename` text NOT NULL";
         $sql[] = "ALTER TABLE `change_log` CHANGE `details` `details` text NOT NULL";
         $sql[] = "RENAME TABLE sys_man_invoice TO `invoice`";
         $sql[] = "ALTER TABLE `invoice` CHANGE invoice_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE `invoice` CHANGE `org_id` `org_id` int(10) unsigned NOT NULL DEFAULT '0'";
         $sql[] = "RENAME TABLE sys_man_invoice_line TO `invoice_item`";
         $sql[] = "ALTER TABLE `invoice_item` CHANGE line_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE `invoice_item` CHANGE `system_id` `system_id` int(10) unsigned DEFAULT NULL AFTER id";
         $sql[] = "ALTER TABLE `invoice_item` CHANGE `man_serial` `serial` varchar(200) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE `invoice_item` CHANGE `man_asset_number` `asset_number` varchar(200) NOT NULL DEFAULT ''";
         $sql[] = "RENAME TABLE sys_man_notes TO `notes`";
         $sql[] = "ALTER TABLE `notes` CHANGE notes_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE `notes` CHANGE `notes_title` `title` varchar(200) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE `notes` CHANGE `notes_text` `comment` text NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE `notes` DROP FOREIGN KEY sys_man_notes_user_id";
         $sql[] = "RENAME TABLE `sys_man_additional_fields_data` TO `additional_field_item`";
         $sql[] = "ALTER TABLE `additional_field_item` DROP FOREIGN KEY sys_man_additional_fields_data_field_id";
         $sql[] = "ALTER TABLE `additional_field_item` DROP KEY         sys_man_additional_fields_data_field_id";
         $sql[] = "ALTER TABLE `additional_field_item` DROP field_int";
         $sql[] = "ALTER TABLE `additional_field_item` DROP field_memo";
         $sql[] = "ALTER TABLE `additional_field_item` CHANGE field_details_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE `additional_field_item` CHANGE `field_id` `additional_field_id` int(10) unsigned NOT NULL DEFAULT '0'";
         $sql[] = "ALTER TABLE `additional_field_item` CHANGE `field_datetime` `timestamp` datetime NOT NULL DEFAULT '2000-01-01 00:00:00'";
         $sql[] = "ALTER TABLE `additional_field_item` CHANGE `field_varchar` `value` text NOT NULL DEFAULT ''";
         $sql[] = "RENAME TABLE `sys_man_additional_fields` TO `additional_field`";
         $sql[] = "ALTER TABLE `additional_field` CHANGE field_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE `additional_field` DROP field_sys_type";
         $sql[] = "ALTER TABLE `additional_field` DROP field_derived_type";
         $sql[] = "ALTER TABLE `additional_field` DROP field_derived_sql";
         $sql[] = "ALTER TABLE `additional_field` CHANGE `field_name` `name` varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE `additional_field` CHANGE `field_type` `type` enum('varchar','bool','int','memo','list','datetime','timestamp') NOT NULL DEFAULT 'varchar'";
         $sql[] = "ALTER TABLE `additional_field` CHANGE `field_values` `values` varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE `additional_field` CHANGE `field_placement` `placement` varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE `network` DROP KEY timestamp";
         $sql[] = "ALTER TABLE `edit_log` DROP FOREIGN KEY edit_log_user_id";
         $sql[] = "ALTER TABLE `edit_log` DROP KEY user_id";
         $sql[] = "ALTER TABLE `edit_log` ADD KEY system_id (system_id)";
         $sql[] = "ALTER TABLE `edit_log` ADD CONSTRAINT edit_log_system_id FOREIGN KEY (system_id) REFERENCES system (id) ON DELETE CASCADE";
         $sql[] = "ALTER TABLE `edit_log` DROP KEY edit_log_system_id";
         $sql[] = "ALTER TABLE `notes` DROP KEY user_id";
         $sql[] = "ALTER TABLE `oa_connection` CHANGE connection_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE `oa_group_column` CHANGE column_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE `oa_group_sys` CHANGE group_sys_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE `oa_group_user` CHANGE group_user_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE `oa_report_column` CHANGE column_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE `service` DROP KEY description";
         $sql[] = "ALTER TABLE `oa_change` DROP FOREIGN KEY oa_change_user_id";
         $sql[] = "ALTER TABLE `oa_change` DROP KEY oa_change_user_id";
         $sql[] = "ALTER TABLE `oa_change` CHANGE change_id id int(10) unsigned NOT NULL AUTO_INCREMENT";
         $sql[] = "ALTER TABLE `oa_change` CHANGE `change_short_desc` `title` varchar(200) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE `oa_change` CHANGE `change_reason` `reason` text NOT NULL";
         $sql[] = "ALTER TABLE `oa_change` CHANGE `change_planned_date` `planned_date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00'";
         $sql[] = "ALTER TABLE `oa_change` CHANGE `change_implemented_date` `implemented_date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00'";
         $sql[] = "ALTER TABLE `oa_change` CHANGE `change_external_id` `external_id` varchar(200) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE `oa_change` CHANGE `change_external_link` `external_link` varchar(200) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE `oa_change` CHANGE `change_authorising_person` `authorized_by` varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE `oa_change` CHANGE `change_performing_person` `performed_by` varchar(100) NOT NULL DEFAULT ''";
         $sql[] = "ALTER TABLE `oa_change` CHANGE `change_detailed_desc` `details` text NOT NULL";
         $sql[] = "ALTER TABLE `oa_change` CHANGE `change_potential_issues` `potential_issues` text NOT NULL";
         $sql[] = "ALTER TABLE `oa_change` CHANGE `change_backout_plan` `backout_plan` text NOT NULL";
         $sql[] = "DROP TABLE IF EXISTS cluster";
         $sql[] = "CREATE TABLE `cluster` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(200) NOT NULL DEFAULT '', `description` text NOT NULL, `org_id` int(10) unsigned NOT NULL DEFAULT '0', `type` enum('high availability', 'load balancing', 'perforance', 'storage', 'other'), `purpose` enum('application', 'database', 'file', 'virtualisation', 'web', 'other'), `edited_by` varchar(200) NOT NULL DEFAULT '', `edited_date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
         $sql[] = "UPDATE system SET hostname = name";
         $sql[] = "UPDATE system SET dns_hostname = name";
         $sql[] = "UPDATE system SET dns_domain = domain";
         $sql[] = "DROP FUNCTION IF EXISTS cidr_to_mask";
         $sql[] = "CREATE FUNCTION cidr_to_mask (cidr INT(2)) RETURNS CHAR(15) DETERMINISTIC RETURN INET_NTOA(CONV(CONCAT(REPEAT(1,cidr),REPEAT(0,32-cidr)),2,10))";
         $sql[] = "DROP TABLE IF EXISTS `files`";
         $sql[] = "CREATE TABLE `files` (`id` int(10) unsigned NOT NULL AUTO_INCREMENT, `org_id` int(10) unsigned NOT NULL DEFAULT '0', `path` varchar(45) NOT NULL DEFAULT '', `description` varchar(200) NOT NULL DEFAULT '', `edited_by` varchar(200) NOT NULL DEFAULT '', `edited_date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
         $sql[] = "DROP TABLE IF EXISTS `file`";
         $sql[] = "CREATE TABLE `file` (`id` int(10) unsigned NOT NULL AUTO_INCREMENT, `system_id` int(10) unsigned DEFAULT NULL, `current` enum('y','n') NOT NULL DEFAULT 'y', `first_seen` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', `last_seen` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', `files_id` int(10) unsigned DEFAULT NULL, `name` varchar(250) NOT NULL DEFAULT '', `full_name` text NOT NULL DEFAULT '', `size` int(10) unsigned NOT NULL DEFAULT '0', `directory` text NOT NULL DEFAULT '', `hash` varchar(250) NOT NULL DEFAULT '', `last_changed` varchar(100) NOT NULL DEFAULT '', `meta_last_changed` varchar(100) NOT NULL DEFAULT '', `permission` varchar(250) NOT NULL DEFAULT '', `owner` varchar(100) NOT NULL DEFAULT '', `group` varchar(100) NOT NULL DEFAULT '', `type` varchar(100) NOT NULL DEFAULT '', `version` varchar(100) NOT NULL DEFAULT '', `inode` bigint unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`id`), KEY `system_id` (`system_id`), CONSTRAINT `file_system_id` FOREIGN KEY (`system_id`) REFERENCES `system` (`id`) ON DELETE CASCADE) ENGINE=InnoDB DEFAULT CHARSET=utf8";
         # fix a previous missed item
         $sql[] = "ALTER TABLE `partition` CHANGE `type` `type` varchar(100) NOT NULL DEFAULT 'local' AFTER bootable";
         $sql[] = "DROP TABLE IF EXISTS `scripts`";
         $sql[] = "CREATE TABLE `scripts` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(250) NOT NULL DEFAULT '', `options` text NOT NULL DEFAULT '', `description` varchar(200) NOT NULL DEFAULT '', `based_on` varchar(200) NOT NULL DEFAULT '', `hash` varchar(250) NOT NULL DEFAULT '', `edited_by` varchar(200) NOT NULL DEFAULT '', `edited_date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
         $options = array();
         $options['submit_online'] = 'y';
         $options['create_file'] = 'n';
         if ($this->config->item('default_network_address') != '') {
             $options['url'] = 'http://' . $this->config->item('default_network_address') . '/open-audit/index.php/system/add_system';
         } else {
             $options['url'] = 'http://localhost/open-audit/index.php/system/add_system';
         }
         $options['debugging'] = 1;
         $options = json_encode($options);
         $sql[] = "INSERT INTO `scripts` VALUES (NULL, 'audit_aix.sh', '" . $options . "', 'The default audit AIX config.', 'audit_aix.sh', '', 'system', '2016-06-01 00:00:00')";
         $sql[] = "INSERT INTO `scripts` VALUES (NULL, 'audit_esx.sh', '" . $options . "', 'The default audit ESX config.', 'audit_esx.sh', '', 'system', '2016-06-01 00:00:00')";
         $sql[] = "INSERT INTO `scripts` VALUES (NULL, 'audit_linux.sh', '" . $options . "', 'The default audit Linux config.', 'audit_linux.sh', '', 'system', '2016-06-01 00:00:00')";
         $sql[] = "INSERT INTO `scripts` VALUES (NULL, 'audit_osx.sh', '" . $options . "', 'The default audit OSX config.', 'audit_osx.sh', '', 'system', '2016-06-01 00:00:00')";
         $sql[] = "INSERT INTO `scripts` VALUES (NULL, 'audit_windows.vbs', '" . $options . "', 'The default audit Windows config.', 'audit_windows.vbs', '', 'system', '2016-06-01 00:00:00')";
         $sql[] = "UPDATE additional_field SET placement = 'custom' WHERE placement = 'view_summary_custom'";
         $sql[] = "UPDATE additional_field SET placement = 'location' WHERE placement = 'view_summary_location'";
         $sql[] = "UPDATE additional_field SET placement = 'network' WHERE placement = 'view_summary_network'";
         $sql[] = "UPDATE additional_field SET placement = 'purchase' WHERE placement = 'view_summary_purchase'";
         $sql[] = "UPDATE additional_field SET placement = 'san' WHERE placement = 'view_hardware_san'";
         $sql[] = "UPDATE additional_field SET placement = 'san_disk' WHERE placement = 'view_hardware_san_disk'";
         $sql[] = "UPDATE additional_field SET placement = 'system' WHERE placement = 'system_details'";
         $sql[] = "UPDATE additional_field SET placement = 'windows' WHERE placement = 'view_summary_windows'";
         $sql[] = "DROP TABLE IF EXISTS `credential`";
         $sql[] = "CREATE TABLE `credential` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `system_id` int(10) unsigned DEFAULT NULL, `current` enum('y','n') NOT NULL DEFAULT 'y', `name` varchar(200) NOT NULL DEFAULT '', `description` text NOT NULL, `type` enum('aws','basic_auth','cim','ipmi','mysql','netapp','other','snmp','snmp_v3','sql_server','ssh','ssh_key','vmware','web','windows') NOT NULL DEFAULT 'other', `credentials` text NOT NULL, `edited_by` varchar(200) NOT NULL DEFAULT '', `edited_date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), KEY `system_id` (`system_id`), CONSTRAINT `credential_system_id` FOREIGN KEY (`system_id`) REFERENCES `system` (`id`) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8";
         $sql[] = "DROP TABLE IF EXISTS `credentials`";
         $sql[] = "CREATE TABLE `credentials` (  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,  `name` varchar(200) NOT NULL DEFAULT '',  `description` text NOT NULL,  `type` enum('aws','basic_auth','cim','impi','mysql','netapp','other','snmp','snmp_v3','sql_server','ssh','ssh_key','vmware','web','windows') NOT NULL DEFAULT 'other',  `credentials` text NOT NULL, `org_id` int(10) unsigned NOT NULL DEFAULT '0', `edited_by` varchar(200) NOT NULL DEFAULT '',  `edited_date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',  PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8";
         $sql[] = "ALTER TABLE `oa_user_org` CHANGE `org_id` `org_id` int(10) unsigned NOT NULL DEFAULT '0'";
         // update any leftover group definitions by changing man_icon to icon
         $sql[] = "UPDATE oa_group SET group_display_sql = REPLACE(group_display_sql, 'system.man_', 'system.')";
         $sql[] = "UPDATE oa_group SET group_display_sql = REPLACE(group_display_sql, 'man_', 'system.')";
         $sql[] = "UPDATE oa_group SET group_display_sql = REPLACE(group_display_sql, 'system.ip_address', 'system.ip')";
         $sql[] = "UPDATE oa_group SET group_display_sql = REPLACE(group_display_sql, 'system.system_id', 'system.id')";
         $sql[] = "UPDATE oa_group SET group_display_sql = REPLACE(group_display_sql, 'system.timestamp', 'system.last_seen')";
         $sql[] = "UPDATE oa_group SET group_dynamic_select = REPLACE(group_dynamic_select, 'system.man_', 'system.')";
         $sql[] = "UPDATE oa_group SET group_dynamic_select = REPLACE(group_dynamic_select, 'man_', 'system.')";
         $sql[] = "UPDATE oa_group SET group_dynamic_select = REPLACE(group_dynamic_select, 'system.ip_address', 'system.ip')";
         $sql[] = "UPDATE oa_group SET group_dynamic_select = REPLACE(group_dynamic_select, 'system.system_id', 'system.id')";
         $sql[] = "UPDATE oa_group SET group_dynamic_select = REPLACE(group_dynamic_select, 'system.timestamp', 'system.last_seen')";
         $sql[] = "DROP TABLE IF EXISTS `nmap`";
         $sql[] = "CREATE TABLE `nmap` (`id` int(10) unsigned NOT NULL AUTO_INCREMENT, `system_id` int(10) unsigned DEFAULT NULL,`current` enum('y','n') NOT NULL DEFAULT 'y', `first_seen` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', `last_seen` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', `protocol` enum('tcp','udp','tcp6','udp6','tcp4','udp4','') NOT NULL DEFAULT '', `ip` varchar(45) NOT NULL DEFAULT '', `port` int(5) NOT NULL DEFAULT '0', `program` varchar(250) NOT NULL DEFAULT '', PRIMARY KEY (`id`), KEY `system_id` (`system_id`),CONSTRAINT `nmap_system_id` FOREIGN KEY (`system_id`) REFERENCES `system` (`id`) ON DELETE CASCADE) ENGINE=InnoDB DEFAULT CHARSET=utf8";
         # set our versions
         $sql[] = "DELETE FROM `oa_config` WHERE config_name = 'discovery_use_dns'";
         $sql[] = "INSERT INTO `oa_config` VALUES ('discovery_use_dns','y','y','0000-00-00 00:00:00',0,'Should we use DNS for looking up the hostname and domain.')";
         $sql[] = "INSERT INTO `oa_config` VALUES ('maps_api_key','AIzaSyAhAUqssRASeC0Pfyx1TW1DXRmboG5bdG0','y','0000-00-00 00:00:00',0,'The API key for Google Maps.')";
         $sql[] = "UPDATE oa_config SET config_value = '20160620' WHERE config_name = 'internal_version'";
         $sql[] = "UPDATE oa_config SET config_value = '1.12.8' WHERE config_name = 'display_version'";
         foreach ($sql as $this_query) {
             $log_details->message = $this_query;
             stdlog($log_details);
             $this->data['output'] .= $this_query . "<br /><br />\n";
             $query = $this->db->query($this_query);
         }
         # Move of default config values for credentials into credential sets
         $this->load->model('m_oa_config');
         $this->m_oa_config->load_config();
         $this->load->model('m_credentials');
         $this->load->library('encrypt');
         $this->response = new stdClass();
         $this->response->meta = new stdClass();
         $this->response->meta->received_data = new stdClass();
         $this->response->meta->received_data->attributes = new stdClass();
         if (!empty($this->config->config['default_snmp_community'])) {
             unset($this->response->meta->received_data->attributes->credentials);
             $this->response->meta->received_data->attributes->credentials = new stdClass();
             $this->response->meta->received_data->attributes->name = 'Default SNMP';
             $this->response->meta->received_data->attributes->description = 'Migrated from configuration.';
             $this->response->meta->received_data->attributes->type = 'snmp';
             $this->response->meta->received_data->attributes->credentials = new stdClass();
             $this->response->meta->received_data->attributes->credentials->community = $this->config->config['default_snmp_community'];
             if ($id = $this->m_credentials->create()) {
                 $this->data['output'] .= "Default SNMP community migrated into credentials.<br /><br />\n";
             } else {
                 $this->data['output'] .= "Could not migrate default SNMP community into credentials. Please add this to the credential sets.<br /><br />\n";
             }
         }
         if (!empty($this->config->config['default_ssh_username']) and !empty($this->config->config['default_ssh_password'])) {
             unset($this->response->meta->received_data->attributes->credentials);
             $this->response->meta->received_data->attributes->credentials = new stdClass();
             $this->response->meta->received_data->attributes->name = 'Default SSH';
             $this->response->meta->received_data->attributes->description = 'Migrated from configuration.';
             $this->response->meta->received_data->attributes->type = 'ssh';
             $this->response->meta->received_data->attributes->credentials->username = $this->config->config['default_ssh_username'];
             $this->response->meta->received_data->attributes->credentials->password = $this->config->config['default_ssh_password'];
             if ($id = $this->m_credentials->create()) {
                 $this->data['output'] .= "Default SSH username and password migrated into credentials.<br /><br />\n";
             } else {
                 $this->data['output'] .= "Could not migrate default SSH username and password into credentials. Please add this to the credential sets.<br /><br />\n";
             }
         }
         if (!empty($this->config->config['default_windows_username']) and !empty($this->config->config['default_windows_password'])) {
             unset($this->response->meta->received_data->attributes->credentials);
             $this->response->meta->received_data->attributes->credentials = new stdClass();
             $this->response->meta->received_data->attributes->name = 'Default Windows';
             $this->response->meta->received_data->attributes->description = 'Migrated from configuration.';
             $this->response->meta->received_data->attributes->type = 'windows';
             $this->response->meta->received_data->attributes->credentials->username = $this->config->config['default_windows_username'] . '@' . $this->config->config['default_windows_domain'];
             $this->response->meta->received_data->attributes->credentials->password = $this->config->config['default_windows_password'];
             if ($id = $this->m_credentials->create()) {
                 $this->data['output'] .= "Default Windows username and password migrated into credentials.<br /><br />\n";
             } else {
                 $this->data['output'] .= "Could not migrate default Windows username and password into credentials. Please add this to the credential sets.<br /><br />\n";
             }
         }
         if (!empty($this->config->config['default_ipmi_username']) and !empty($this->config->config['default_ipmi_password'])) {
             unset($this->response->meta->received_data->attributes->credentials);
             $this->response->meta->received_data->attributes->credentials = new stdClass();
             $this->response->meta->received_data->attributes->name = 'Default IPMI';
             $this->response->meta->received_data->attributes->description = 'Migrated from configuration.';
             $this->response->meta->received_data->attributes->type = 'ipmi';
             $this->response->meta->received_data->attributes->credentials->username = $this->config->config['default_ipmi_username'];
             $this->response->meta->received_data->attributes->credentials->password = $this->config->config['default_ipmi_password'];
             if ($id = $this->m_credentials->create()) {
                 $this->data['output'] .= "Default IPMI username and password migrated into credentials.<br /><br />\n";
             } else {
                 $this->data['output'] .= "Could not migrate default IPMI username and password into credentials. Please add this to the credential sets.<br /><br />\n";
             }
         }
         $this_query = "DELETE FROM oa_config WHERE config_name IN ('default_ipmi_password', 'default_ipmi_username', 'default_snmp_community', 'default_ssh_password', 'default_ssh_username', 'default_windows_username', 'default_windows_domain', 'default_windows_password')";
         $log_details->message = $this_query;
         stdlog($log_details);
         $this->data['output'] .= $this_query . "<br /><br />\n";
         $query = $this->db->query($this_query);
         # populate our new credential table with the system.access_details columns
         $sql = "SELECT NOW() as `timestamp`";
         $log_details->message = $sql;
         stdlog($log_details);
         $query = $this->db->query($sql);
         $result = $query->result();
         $timestamp = $result[0]->timestamp;
         $sql = "DELETE FROM `credential`";
         $log_details->message = $sql;
         stdlog($log_details);
         $query = $this->db->query($sql);
         $sql = "SELECT id, access_details FROM system WHERE access_details != ''";
         $log_details->message = $sql;
         stdlog($log_details);
         $query = $this->db->query($sql);
         $result = $query->result();
         foreach ($result as $device) {
             $creds = $this->encrypt->decode($device->access_details);
             $creds = json_decode($creds);
             $newcreds = array();
             if (!empty($creds->snmp_community)) {
                 $cred = new stdClass();
                 $cred->community = $creds->snmp_community;
                 $credentials = (string) $this->encrypt->encode(json_encode($cred));
                 $sql = "INSERT INTO credential VALUES (NULL, ?, 'y', 'Device SNMP credentials.', 'Migrated from device upon upgrade.', 'snmp', ?, 'system', ?)";
                 $log_details->message = $sql;
                 stdlog($log_details);
                 $data = array(intval($device->id), (string) $credentials, "{$timestamp}");
                 $query = $this->db->query($sql, $data);
                 unset($cred);
                 unset($credentials);
             }
             if (!empty($creds->windows_username)) {
                 $cred = new stdClass();
                 $cred->username = $creds->windows_username . '@' . $creds->windows_domain;
                 $cred->password = $creds->windows_password;
                 $credentials = (string) $this->encrypt->encode(json_encode($cred));
                 $sql = "INSERT INTO credential VALUES (NULL, ?, 'y', 'Device Windows credentials.', 'Migrated from device upon upgrade.', 'windows', ?, 'system', ?)";
                 $log_details->message = $sql;
                 stdlog($log_details);
                 $data = array(intval($device->id), (string) $credentials, "{$timestamp}");
                 $query = $this->db->query($sql, $data);
                 unset($cred);
                 unset($credentials);
             }
             if (!empty($creds->ssh_username)) {
                 $cred = new stdClass();
                 $cred->username = $creds->ssh_username;
                 $cred->password = $creds->ssh_password;
                 $credentials = (string) $this->encrypt->encode(json_encode($cred));
                 $sql = "INSERT INTO credential VALUES (NULL, ?, 'y', 'Device SSH credentials.', 'Migrated from device upon upgrade.', 'ssh', ?, 'system', ?)";
                 $log_details->message = $sql;
                 stdlog($log_details);
                 $data = array(intval($device->id), (string) $credentials, "{$timestamp}");
                 $query = $this->db->query($sql, $data);
                 unset($cred);
                 unset($credentials);
             }
         }
         $sql = "ALTER TABLE `system` DROP access_details";
         $log_details->message = $sql;
         stdlog($log_details);
         $query = $this->db->query($sql);
         # reinitialise our $sql array
         unset($sql);
         $sql = array();
         $log_details->message = 'Upgrade database to 1.12.8 completed';
         stdlog($log_details);
         unset($log_details);
     }
     if ($db_internal_version < '20160810' and $this->db->platform() == 'mysql') {
         # upgrade for 1.12.8.1
         $log_details = new stdClass();
         $log_details->file = 'system';
         $log_details->message = 'Upgrade database to 1.12.8.1 commenced';
         stdlog($log_details);
         # initialise our $sql array
         unset($sql);
         $sql = array();
         $fields = $this->db->list_fields('system');
         $fields = implode($fields, "','");
         $fields = "'" . $fields . "'";
         $sql[] = "UPDATE additional_field SET name = CONCAT(`name`, '_1') WHERE name in (" . $fields . ")";
         unset($fields);
         $sql[] = "ALTER TABLE system ADD omk_uuid text NOT NULL AFTER last_user";
         $sql[] = "INSERT INTO `oa_config` VALUES ('delete_noncurrent','n','y','0000-00-00 00:00:00',0,'Should we delete any attributes that are not present when we audit a device.')";
         $sql[] = "UPDATE oa_config SET config_value = '20160810' WHERE config_name = 'internal_version'";
         $sql[] = "UPDATE oa_config SET config_value = '1.12.8.1' WHERE config_name = 'display_version'";
         foreach ($sql as $this_query) {
             $log_details->message = $this_query;
             stdlog($log_details);
             $this->data['output'] .= $this_query . "<br /><br />\n";
             $query = $this->db->query($this_query);
         }
         $log_details->message = 'Upgrade database to 1.12.8.1 completed';
         stdlog($log_details);
         unset($log_details);
     }
     # refresh the icons
     $this->load->model('m_system');
     $this->m_system->reset_icons();
     # refresh the reports
     $this->load->helper('report_helper');
     refresh_report_definitions();
     # refresh the groups
     $this->load->helper('group_helper');
     refresh_group_definitions();
     #refresh the scripts
     // $this->load->helper('script_helper');
     // refresh_script_definitions();
     $this->m_oa_config->load_config();
     $this->data['message'] .= "New (now current) database version: " . $this->config->item('display_version') . " (" . $this->config->item('internal_version') . ")<br />Don't forget to use the new audit scripts!<br/>\n";
     $this->data['include'] = 'v_upgrade';
     $this->data['heading'] = 'Upgrade';
     $this->load->view('v_template', $this->data);
 }
Beispiel #25
0
 function dns_validate($details, $display = 'n')
 {
     if (!isset($details)) {
         # no object passed
         return;
     }
     #$this->load->helper('log_helper');
     $log_details = new stdClass();
     $log_details->message = 'Start DNS checking for ' . @$details->ip;
     $log_details->severity = 7;
     $log_details->file = 'system';
     if ($display != 'y') {
         $display = 'n';
     }
     $log_details->display = $display;
     unset($display);
     stdlog($log_details);
     if (!isset($details->ip)) {
         $details->ip = '';
         $log_details->message = 'No ip set for ' . @$details->hostname;
         stdlog($log_details);
     } else {
         if (!filter_var($details->ip, FILTER_VALIDATE_IP)) {
             # we have something in the ip address that is not an ip
             $log_details->message = 'Invalid entry in ip is ' . @$details->ip;
             stdlog($log_details);
             if (empty($details->hostname)) {
                 $log_details->message = 'Hostname is empty so filling with ip for ' . @$details->ip;
                 stdlog($log_details);
                 $details->hostname = $details->ip;
                 $details->ip = '';
             }
         }
     }
     if (!isset($details->hostname)) {
         $details->hostname = '';
         $log_details->message = 'No hostname set for ' . @$details->ip;
         stdlog($log_details);
     } else {
         if (filter_var($details->hostname, FILTER_VALIDATE_IP)) {
             # we have an ip in the hostname field
             $log_details->message = 'Hostname contains an ip ' . @$details->hostname;
             stdlog($log_details);
             if ($details->ip == '') {
                 # ip is empty, set it to the ip address from the hostname
                 $log_details->message = 'IP is empty so filling with hostname for ' . @$details->hostname;
                 stdlog($log_details);
                 $details->ip = $details->hostname;
             }
             $details->hostname = '';
         } elseif (strpos($details->hostname, '.') !== false) {
             # we have a FQDN in the hostname field
             $log_details->message = 'Hostname is actually a FQDN ' . @$details->hostname;
             stdlog($log_details);
             if (empty($details->fqdn)) {
                 $log_details->message = 'FQDN is empty so filling with hostname for ' . @$details->hostname;
                 stdlog($log_details);
                 $details->fqdn = strtolower($details->hostname);
             }
             $i = explode(".", $details->hostname);
             $details->hostname = $i[0];
             $log_details->message = 'Setting hostname to ' . @$details->hostname;
             stdlog($log_details);
             unset($i[0]);
             if (empty($details->domain)) {
                 $details->domain = implode(".", $i);
                 $log_details->message = 'Setting domain to ' . @$details->domain;
                 stdlog($log_details);
             }
             unset($i);
         }
     }
     if (!isset($details->domain)) {
         $details->domain = '';
         $log_details->message = 'No domain set for ' . @$details->ip;
         stdlog($log_details);
     } else {
         if (filter_var($details->domain, FILTER_VALIDATE_IP)) {
             # we have an ip in the domain field
             $log_details->message = 'Domain contains an ip ' . @$details->domain;
             stdlog($log_details);
             if (empty($details->ip)) {
                 # ip is empty, set it to the ip address from the domain
                 $details->ip = $details->domain;
                 $log_details->message = 'IP is empty so filling with hostname for ' . @$details->hostname;
                 stdlog($log_details);
             }
             $details->domain = '';
         }
     }
     if (!isset($details->fqdn)) {
         $details->fqdn = '';
         $log_details->message = 'No FQDN set for ' . @$details->ip;
         stdlog($log_details);
     } else {
         if (filter_var($details->fqdn, FILTER_VALIDATE_IP)) {
             # we have an ip in the fqdn field
             $log_details->message = 'FQDN contains an ip ' . @$details->fqdn;
             stdlog($log_details);
             if (empty($details->ip)) {
                 # ip is empty, set it to the ip address from the fqdn
                 $details->ip = $details->fqdn;
                 $log_details->message = 'IP is empty so filling with fqdn for ' . @$details->fqdn;
                 stdlog($log_details);
             }
             $details->fqdn = '';
         }
         if (strpos($details->fqdn, '.') === false) {
             # if it is a real FQDN, there should be at least one .
             $details->fqdn = '';
             $log_details->message = 'FQDN does not contain a . so removing ' . @$details->fqdn;
             stdlog($log_details);
         }
     }
     if ($details->hostname == '' and filter_var($details->ip, FILTER_VALIDATE_IP)) {
         # we have nothing for a hostname and a valid ip
         # try getting the dns hostname
         $log_details->message = 'Using gethostbyaddr because no hostname set but IP is set for ' . @$details->ip;
         stdlog($log_details);
         $details->hostname = strtolower(gethostbyaddr($details->ip));
         # make sure we use the hostname and not a fqdn if returned
         if (strpos($details->hostname, ".") !== false) {
             if (!filter_var($details->hostname, FILTER_VALIDATE_IP)) {
                 # we got a FQDN back from DNS - split it up
                 $log_details->message = 'Received a FQDN back from gethostbyaddr for ' . @$details->ip;
                 stdlog($log_details);
                 $details->fqdn = strtolower($details->hostname);
                 $i = explode(".", $details->hostname);
                 $details->hostname = $i[0];
                 unset($i[0]);
                 $log_details->message = 'Split FQDN and set hostname to ' . @$details->hostname;
                 stdlog($log_details);
                 $details->domain = implode(".", $i);
                 unset($i);
                 $log_details->message = 'Split FQDN and set domain to ' . @$details->domain;
                 stdlog($log_details);
             } else {
                 # we got an ip address back from DNS, remove it
                 $details->hostname = '';
             }
         }
     }
     if (!filter_var($details->ip, FILTER_VALIDATE_IP) and $details->hostname != '') {
         $details->ip = gethostbyname($details->hostname);
         $log_details->message = 'Using gethostbyname because no valid ip address, but valid hostname ' . @$details->sysName;
         stdlog($log_details);
     }
     if (empty($details->hostname) and !empty($details->sysName)) {
         # we have nothing in hostname, but something in sysName, use that
         $details->hostname = $details->sysName;
         $log_details->message = 'Setting hostname to sysName because no entry for hostname, but valid sysName ' . @$details->sysName;
         stdlog($log_details);
     }
     if (empty($details->dns_hostname) and !empty($details->hostname)) {
         $details->dns_hostname = $details->hostname;
     }
     if (empty($details->dns_domain) and !empty($details->domain)) {
         $details->dns_domain = $details->domain;
     }
     $log_details->message = 'Finish DNS checking for ' . @$details->ip;
     stdlog($log_details);
     return $details;
 }
Beispiel #26
0
 function add_san()
 {
     if (isset($_POST['input']) and $_POST['input'] != '') {
         $this->benchmark->mark('code_start');
         $log_details = new stdClass();
         $log_details->severity = 7;
         $log_details->file = 'system';
         $log_details->message = 'Start processing audit result for a san';
         stdlog($log_details);
         $this->load->model('m_devices_components');
         $this->load->model('m_system');
         $this->load->model('m_oa_group');
         $this->load->model('m_audit_log');
         $this->load->helper('url');
         $input = explode(PHP_EOL, $_POST['input']);
         // echo "FILE: " . $input[0] . "\n";
         echo "<pre>\n";
         // print_r($input);
         $details = new stdClass();
         $details->hostname = '';
         $details->type = 'san';
         $san = array();
         $disk = array();
         $network = array();
         $ip = array();
         foreach ($input as $key => $value) {
             $value = trim($value);
             if (stripos($value, 'Feature pack:') === 0 and (!isset($details->description) or $details->description == '')) {
                 $details->description = trim(str_replace('Feature pack:', '', $value));
             }
             if (stripos($value, 'Chassis name:') === 0 and (!isset($details->description) or $details->description == '')) {
                 $details->description = trim(str_replace('Chassis name:', '', $value));
             }
             if (stripos($value, 'Storage Subsystem world-wide identifier (ID):') === 0 and (!isset($details->serial) or $details->serial == '')) {
                 $details->serial = str_replace('Storage Subsystem world-wide identifier (ID):', '', $value);
             }
             if (stripos($value, 'Storage Subsystem worldwide name (ID):') === 0 and (!isset($details->serial) or $details->serial == '')) {
                 $details->serial = str_replace('Storage Subsystem worldwide name (ID):', '', $value);
             }
             if (stripos($value, 'Storage array world-wide identifier (ID):') === 0 and (!isset($details->serial) or $details->serial == '')) {
                 $details->serial = str_replace('Storage array world-wide identifier (ID):', '', $value);
             }
             if (stripos($value, 'Controller DNS/Network name:') === 0 and $details->hostname == '') {
                 $details->hostname = trim(str_replace('Controller DNS/Network name:', '', $value));
             }
             if (stripos($value, 'Controller host name:') === 0 and $details->hostname == '') {
                 $details->hostname = trim(str_replace('Controller host name:', '', $value));
             }
             if (stripos($value, 'RAID Controller Module host name:') === 0 and $details->hostname == '') {
                 $details->hostname = trim(str_replace('RAID Controller Module host name:', '', $value));
             }
             if (stripos($value, 'Controller in Enclosure') === 0 or stripos($value, 'RAID Controller Module in Enclosure') === 0) {
                 $item = new stdClass();
                 $item->type = 'controller';
                 # get the parent
                 $item->attached_to = '';
                 $item->location = $value;
                 #
                 #$item->attached_to = substr($item->location, 0, $i);
                 $i = explode(' ', $item->location);
                 unset($i[0]);
                 unset($i[1]);
                 $item->attached_to = implode(' ', $i);
                 unset($i);
                 $i = stripos($item->attached_to, ',');
                 $item->attached_to = substr($item->attached_to, 0, $i);
                 # get the details
                 for ($i = $key; $i < $key + 40; $i++) {
                     $input[$i] = trim($input[$i]);
                     if (stripos(trim($input[$i]), 'Status:') === 0 and (!isset($item->status) or $item->status == '')) {
                         $item->status = trim(str_ireplace('Status:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Firmware version:') === 0 and trim(str_ireplace('Firmware version:', '', $input[$i])) != '' and !isset($item->firmware_version)) {
                         $item->firmware_version = trim(str_ireplace('Firmware version:', '', $input[$i]));
                         if (isset($item->notes) and $item->notes != '') {
                             $item->notes .= ', Firmware Version: ' . trim(str_ireplace('Firmware version:', '', $input[$i]));
                         } else {
                             $item->notes = 'Firmware Version: ' . trim(str_ireplace('Firmware version:', '', $input[$i]));
                         }
                     }
                     if (stripos(trim($input[$i]), 'Replacement part number:') === 0 and trim(str_ireplace('Replacement part number:', '', $input[$i])) != '' and !isset($item->replacement_part_number)) {
                         $item->replacement_part_number = trim(str_ireplace('Replacement part number:', '', $input[$i]));
                         if (isset($item->notes) and $item->notes != '') {
                             $item->notes .= ', Replacement part number: ' . trim(str_ireplace('Replacement part number:', '', $input[$i]));
                         } else {
                             $item->notes = 'Replacement part number: ' . trim(str_ireplace('Replacement part number:', '', $input[$i]));
                         }
                     }
                     if (stripos(trim($input[$i]), 'Model name:') === 0 and trim(str_ireplace('Model name:', '', $input[$i])) != '' and !isset($item->model_name)) {
                         $item->model_name = trim(str_ireplace('Model name:', '', $input[$i]));
                         if (isset($item->notes) and $item->notes != '') {
                             $item->notes .= ', Model Name: ' . trim(str_ireplace('Model name:', '', $input[$i]));
                         } else {
                             $item->notes = 'Model Name: ' . trim(str_ireplace('Model Name:', '', $input[$i]));
                         }
                     }
                     if (stripos(trim($input[$i]), 'Board ID:') === 0 and trim(str_ireplace('Board ID:', '', $input[$i])) != '' and !isset($item->board_id)) {
                         $item->board_id = trim(str_ireplace('Board ID:', '', $input[$i]));
                         if (isset($item->notes) and $item->notes != '') {
                             $item->notes .= ', Board ID: ' . trim(str_ireplace('Board ID:', '', $input[$i]));
                         } else {
                             $item->notes = 'Board ID: ' . trim(str_ireplace('Board ID:', '', $input[$i]));
                         }
                     }
                     if (stripos(trim($input[$i]), 'Submodel ID:') === 0 and trim(str_ireplace('Submodel ID:', '', $input[$i])) != '' and !isset($item->submodel_id)) {
                         $item->submodel_id = trim(str_ireplace('Submodel ID:', '', $input[$i]));
                         if (isset($item->notes) and $item->notes != '') {
                             $item->notes .= ', Submodel ID: ' . trim(str_ireplace('Submodel ID:', '', $input[$i]));
                         } else {
                             $item->notes = 'Submodel ID: ' . trim(str_ireplace('Submodel ID:', '', $input[$i]));
                         }
                     }
                     if (stripos(trim($input[$i]), 'Product ID:') === 0 and trim(str_ireplace('Product ID:', '', $input[$i])) != '' and !isset($item->product_id)) {
                         $item->product_id = trim(str_ireplace('Product ID:', '', $input[$i]));
                         if (isset($item->notes) and $item->notes != '') {
                             $item->notes .= ', Product ID: ' . trim(str_ireplace('Product ID:', '', $input[$i]));
                         } else {
                             $item->notes = 'Product ID: ' . trim(str_ireplace('Product ID:', '', $input[$i]));
                         }
                     }
                     if (stripos(trim($input[$i]), 'Revision:') === 0 and trim(str_ireplace('Revision:', '', $input[$i])) != '' and !isset($item->revision)) {
                         $item->revision = trim(str_ireplace('Revision:', '', $input[$i]));
                         if (isset($item->notes) and $item->notes != '') {
                             $item->notes .= ', Revision: ' . trim(str_ireplace('Revision:', '', $input[$i]));
                         } else {
                             $item->notes = 'Revision: ' . trim(str_ireplace('Revision:', '', $input[$i]));
                         }
                     }
                     if (stripos(trim($input[$i]), 'Part number:') === 0 and (!isset($item->part_number) or $item->part_number == '')) {
                         $item->part_number = trim(str_ireplace('Part number:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Serial number:') === 0 and (!isset($item->serial) or $item->serial == '')) {
                         $item->serial = trim(str_ireplace('Serial number:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Vendor:') === 0 and (!isset($item->manufacturer) or $item->manufacturer == '')) {
                         $item->manufacturer = trim(str_ireplace('Vendor:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Date of manufacture:') === 0 and (!isset($item->date_of_manufacture) or $item->date_of_manufacture == '')) {
                         $item->date_of_manufacture = trim(str_ireplace('Date of manufacture:', '', $input[$i]));
                     }
                 }
                 $san[] = $item;
                 unset($item);
             }
             if (stripos($value, 'Data Cache Module') === 0 or stripos($value, 'Cache Backup Device') === 0 or stripos($value, 'Host Interface Board') === 0) {
                 $item = new stdClass();
                 $item->type = strtolower($value);
                 # get the parent
                 for ($i = $key; $i >= 1; $i--) {
                     if (stripos(trim($input[$i]), 'Controller in Enclosure') !== false) {
                         $item->attached_to = trim($input[$i]);
                         break;
                     }
                 }
                 # get the details
                 for ($i = $key + 1; $i < $key + 15; $i++) {
                     if (trim($input[$i]) == 'Data Cache Module' or trim($input[$i]) == 'Cache Backup Device' or trim($input[$i]) == 'Host Interface Board') {
                         # we hit the next module, break, break from this loop
                         break;
                     }
                     if (stripos(trim($input[$i]), 'Status:') === 0 and (!isset($item->status) or $item->status == '')) {
                         $item->status = trim(str_ireplace('Status:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Location:') === 0 and (!isset($item->location) or $item->location == '')) {
                         $item->location = trim(str_ireplace('Location:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Capacity:') === 0 and trim(str_ireplace('Capacity:', '', $input[$i])) != '' and !isset($item->capacity)) {
                         $item->capacity = trim(str_ireplace('Capacity:', '', $input[$i]));
                         if (isset($item->notes) and $item->notes != '') {
                             $item->notes .= ', Capacity: ' . str_replace(',', '', trim(str_ireplace('Capacity:', '', $input[$i])));
                         } else {
                             $item->notes = 'Capacity: ' . str_replace(',', '', trim(str_ireplace('Capacity:', '', $input[$i])));
                         }
                     }
                     if (stripos(trim($input[$i]), 'Replacement part number:') === 0 and trim(str_ireplace('Replacement part number:', '', $input[$i])) != '' and !isset($item->replacement_part_number)) {
                         $item->replacement_part_number = trim(str_ireplace('Replacement part number:', '', $input[$i]));
                         if (isset($item->notes) and $item->notes != '') {
                             $item->notes .= ', Replacement part number: ' . trim(str_ireplace('Replacement part number:', '', $input[$i]));
                         } else {
                             $item->notes = 'Replacement part number: ' . trim(str_ireplace('Replacement part number:', '', $input[$i]));
                         }
                     }
                     if (stripos(trim($input[$i]), 'Manufacturer part number:') === 0 and (!isset($item->part_number) or $item->part_number == '')) {
                         $item->part_number = trim(str_ireplace('Manufacturer part number:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Part number:') === 0 and (!isset($item->part_number) or $item->part_number == '')) {
                         $item->part_number = trim(str_ireplace('Part number:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Serial number:') === 0 and (!isset($item->serial) or $item->serial == '')) {
                         $item->serial = trim(str_ireplace('Serial number:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Manufacturer:') === 0 and (!isset($item->manufacturer) or $item->manufacturer == '')) {
                         $item->manufacturer = trim(str_ireplace('Manufacturer:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Date of manufacture:') === 0 and (!isset($item->date_of_manufacture) or $item->date_of_manufacture == '')) {
                         $item->date_of_manufacture = trim(str_ireplace('Date of manufacture:', '', $input[$i]));
                     }
                 }
                 if ($item->serial != '' and $item->serial != 'Not Available') {
                     $san[] = $item;
                 }
                 unset($item);
             }
             if (stripos($value, 'Enclosure audible alarm:') === 0) {
                 $item = new stdClass();
                 $item->type = 'enclosure';
                 # as this IS a parent, get the name by reverse loop
                 for ($i = $key; $i >= 1; $i--) {
                     if (stripos(trim($input[$i]), 'Overall Component Information') !== false) {
                         $item->description = trim(str_ireplace(' Overall Component Information', '', $input[$i]));
                         $j = explode(' ', $item->description);
                         $item->type = strtolower($j[0] . ' ' . $j[1]);
                         $item->location = trim(@$j[1] . ' ' . @$j[2]);
                         unset($j);
                         unset($item->description);
                         break;
                     }
                 }
                 if ($item->location == 'Enclosure') {
                     $item->location = 'Enclosure 0';
                 }
                 # get the details
                 for ($i = $key; $i < $key + 10; $i++) {
                     if (trim($input[$i]) == '') {
                         # we hit an empty line, break from this loop
                         break;
                     }
                     if (stripos(trim($input[$i]), 'Serial number:') === 0) {
                         #and (!isset($item->serial) or $item->serial == '')) {
                         $item->serial = trim(str_ireplace('Serial number:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Part number:') === 0 and (!isset($item->part_number) or $item->part_number == '')) {
                         $item->part_number = trim(str_ireplace('Part number:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Vendor:') === 0 and (!isset($item->manufacturer) or $item->manufacturer == '')) {
                         $item->manufacturer = trim(str_ireplace('Vendor:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Date of manufacture:') === 0 and (!isset($item->date_of_manufacture) or $item->date_of_manufacture == '')) {
                         $item->date_of_manufacture = trim(str_ireplace('Date of manufacture:', '', $input[$i]));
                     }
                 }
                 $san[] = $item;
                 unset($item);
             }
             if (stripos($value, 'ESM card status:') === 0) {
                 $item = new stdClass();
                 $item->type = 'esm canister';
                 # get the parent
                 for ($i = $key; $i >= 1; $i--) {
                     if (stripos(trim($input[$i]), 'Overall Component Information') !== false) {
                         $i = explode(' ', trim(str_ireplace(' Overall Component Information', '', $input[$i])));
                         $item->attached_to = trim(@$i[1] . ' ' . @$i[2]);
                         break;
                     }
                 }
                 # get the details
                 for ($i = $key; $i < $key + 20; $i++) {
                     if (trim($input[$i]) == '') {
                         # we hit an empty line, break from this loop
                         break;
                     }
                     if (stripos(trim($input[$i]), 'Serial number:') === 0 and (!isset($item->serial) or $item->serial == '')) {
                         $item->serial = trim(str_ireplace('Serial number:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Part number:') === 0 and (!isset($item->part_number) or $item->part_number == '')) {
                         $item->part_number = trim(str_ireplace('Part number:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Vendor:') === 0 and (!isset($item->manufacturer) or $item->manufacturer == '')) {
                         $item->manufacturer = trim(str_ireplace('Vendor:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Date of manufacture:') === 0 and (!isset($item->date_of_manufacture) or $item->date_of_manufacture == '')) {
                         $item->date_of_manufacture = trim(str_ireplace('Date of manufacture:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Location:') === 0 and (!isset($item->location) or $item->location == '')) {
                         $item->location = 'ESM Canister ' . trim(str_ireplace('Location:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Product ID:') === 0 and trim(str_ireplace('Product ID:', '', $input[$i])) != '' and !isset($item->product_id)) {
                         $item->product_id = trim(str_ireplace('Product ID:', '', $input[$i]));
                         if (isset($item->notes) and $item->notes != '') {
                             $item->notes .= ', Product ID: ' . trim(str_ireplace('Product ID:', '', $input[$i]));
                         } else {
                             $item->notes = 'Product ID: ' . trim(str_ireplace('Product ID:', '', $input[$i]));
                         }
                     }
                 }
                 $san[] = $item;
                 unset($item);
             }
             if (stripos($value, 'SFP status:') === 0) {
                 $item = new stdClass();
                 $item->type = 'sfp';
                 # get the parent
                 for ($i = $key; $i >= 1; $i--) {
                     if (stripos(trim($input[$i]), 'Overall Component Information') !== false) {
                         $i = explode(' ', trim(str_ireplace(' Overall Component Information', '', $input[$i])));
                         $item->attached_to = trim(@$i[1] . ' ' . @$i[2]);
                         break;
                     }
                 }
                 # get the details
                 for ($i = $key; $i < $key + 20; $i++) {
                     if (trim($input[$i]) == '') {
                         # we hit an empty line, break from this loop
                         break;
                     }
                     if (stripos(trim($input[$i]), 'Attached to:') === 0 and (!isset($item->attached_to_location) or $item->attached_to_location == '')) {
                         $item->attached_to_location = trim(str_ireplace('Attached to:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'SFP status:') === 0 and (!isset($item->status) or $item->status == '')) {
                         $item->status = trim(str_ireplace('SFP status:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Revision:') === 0 and trim(str_ireplace('Revision:', '', $input[$i])) != '' and !isset($item->revision)) {
                         $item->revision = trim(str_ireplace('Revision:', '', $input[$i]));
                         if (isset($item->notes) and $item->notes != '') {
                             $item->notes .= ', Revision: ' . trim(str_ireplace('Revision:', '', $input[$i]));
                         } else {
                             $item->notes = 'Revision: ' . trim(str_ireplace('Revision:', '', $input[$i]));
                         }
                     }
                     if (stripos(trim($input[$i]), 'Serial number:') === 0 and (!isset($item->serial) or $item->serial == '')) {
                         $item->serial = trim(str_ireplace('Serial number:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Part number:') === 0 and (!isset($item->part_number) or $item->part_number == '')) {
                         $item->part_number = trim(str_ireplace('Part number:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Vendor:') === 0 and (!isset($item->manufacturer) or $item->manufacturer == '')) {
                         $item->manufacturer = trim(str_ireplace('Vendor:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Date of manufacture:') === 0 and (!isset($item->date_of_manufacture) or $item->date_of_manufacture == '')) {
                         $item->date_of_manufacture = trim(str_ireplace('Date of manufacture:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Location:') === 0 and (!isset($item->location) or $item->location == '')) {
                         $item->location = trim(str_ireplace('Location:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Product ID:') === 0 and trim(str_ireplace('Product ID:', '', $input[$i])) != '' and !isset($item->product_id)) {
                         $item->product_id = trim(str_ireplace('Product ID:', '', $input[$i]));
                         if (isset($item->notes) and $item->notes != '') {
                             $item->notes .= ', Product ID: ' . trim(str_ireplace('Product ID:', '', $input[$i]));
                         } else {
                             $item->notes = 'Product ID: ' . trim(str_ireplace('Product ID:', '', $input[$i]));
                         }
                     }
                 }
                 if (stripos($item->attached_to_location, 'ESM Canister') !== false) {
                     $item->attached_to = $item->attached_to_location;
                 } elseif (stripos($item->attached_to_location, 'controller') !== false) {
                     $j = substr($item->attached_to_location, strpos($item->attached_to_location, ',') - 1, 1);
                     $item->attached_to = 'Controller in ' . $item->attached_to . ', Slot ' . $j;
                     unset($j);
                     $j = explode(' ', $item->attached_to_location);
                     $item->location = $j[0] . ', ' . $item->location;
                 }
                 $san[] = $item;
                 unset($item);
             }
             if (stripos($value, 'Power-fan canister') === 0 and stripos($value, 'status:') !== false) {
                 $item = new stdClass();
                 $item->type = 'power fan cannister';
                 # get the parent
                 for ($i = $key; $i >= 1; $i--) {
                     if (stripos(trim($input[$i]), 'Overall Component Information') !== false) {
                         $i = explode(' ', trim(str_ireplace(' Overall Component Information', '', $input[$i])));
                         $item->attached_to = trim(@$i[1] . ' ' . @$i[2]);
                         break;
                     }
                 }
                 # get the details
                 for ($i = $key; $i < $key + 10; $i++) {
                     if (trim($input[$i]) == '') {
                         # we hit an empty line, break from this loop
                         break;
                     }
                     if (stripos(trim($input[$i]), 'Power-fan canister') === 0 and stripos($input[$i], 'status:') !== false and (!isset($item->status) or $item->status == '')) {
                         $item->status = trim(str_ireplace('Power-fan canister (Left) status:', '', $input[$i]));
                         $item->status = trim(str_ireplace('Power-fan canister (Right) status:', '', $item->status));
                         if (stripos($input[$i], 'Power-fan canister (Left) status:') !== false) {
                             #$item->description = 'Power-fan canister (Left)';
                             $item->location = 'Power-fan canister (Left)';
                         }
                         if (stripos($input[$i], 'Power-fan canister (Right) status:') !== false) {
                             #$item->description = 'Power-fan canister (Right)';
                             $item->location = 'Power-fan canister (Right)';
                         }
                     }
                     if (stripos(trim($input[$i]), 'Serial number:') === 0) {
                         #and (!isset($item->serial) or $item->serial == '')) {
                         $item->serial = trim(str_ireplace('Serial number:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Part number:') === 0 and (!isset($item->part_number) or $item->part_number == '')) {
                         $item->part_number = trim(str_ireplace('Part number:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Vendor:') === 0 and (!isset($item->manufacturer) or $item->manufacturer == '')) {
                         $item->manufacturer = trim(str_ireplace('Vendor:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Date of manufacture:') === 0 and (!isset($item->date_of_manufacture) or $item->date_of_manufacture == '')) {
                         $item->date_of_manufacture = trim(str_ireplace('Date of manufacture:', '', $input[$i]));
                     }
                 }
                 $san[] = $item;
                 unset($item);
             }
             if (stripos($value, 'Drive at Enclosure') === 0) {
                 $item = new stdClass();
                 $item->type = 'disk';
                 $item->caption = trim($value);
                 $item->device = trim($value);
                 $item->hard_drive_index = trim($value);
                 $item->location = trim(str_ireplace('Drive at ', '', $value));
                 $item->attached_to = '';
                 $i = stripos($item->location, ',');
                 $item->attached_to = substr($item->location, 0, $i);
                 $item->size = '';
                 # get the details
                 for ($i = $key + 1; $i < $key + 50; $i++) {
                     if (stripos(trim($input[$i]), 'Drive at Enclosure') === 0) {
                         # we hit the next drive, break from this loop
                         break;
                     }
                     if (stripos(trim($input[$i]), 'Status:') === 0 and (!isset($item->status) or $item->status == '')) {
                         $item->status = trim(str_ireplace('Status:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Usable capacity:') === 0 and $item->size == '') {
                         $item->size = $this->get_size(trim(str_replace('Usable capacity:', '', $input[$i])));
                     }
                     if (stripos(trim($input[$i]), 'Interface type:') === 0 and (!isset($item->interface_type) or $item->interface_type == '')) {
                         $item->interface_type = trim(str_replace('Interface type:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Drive type:') === 0 and (!isset($item->interface_type) or $item->interface_type == '')) {
                         $item->interface_type = trim(str_replace('Drive type:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Product ID:') === 0 and (!isset($item->model) or $item->model == '')) {
                         $item->model = trim(str_replace('Product ID:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Firmware version:') === 0 and (!isset($item->firmware) or $item->firmware == '')) {
                         $item->firmware = trim(str_ireplace('Firmware version:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Serial number:') === 0 and (!isset($item->serial) or $item->serial == '')) {
                         $item->serial = trim(str_ireplace('Serial number:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Vendor:') === 0 and (!isset($item->manufacturer) or $item->manufacturer == '')) {
                         $item->manufacturer = trim(str_ireplace('Vendor:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Date of manufacture:') === 0 and (!isset($item->date_of_manufacture) or $item->date_of_manufacture == '')) {
                         $item->date_of_manufacture = trim(str_ireplace('Date of manufacture:', '', $input[$i]));
                     }
                 }
                 if ($item->size != '') {
                     $disk[] = $item;
                 }
                 unset($item);
             }
             if (stripos($value, 'Ethernet port:') === 0) {
                 $item = new stdClass();
                 $item->attached_to = '';
                 $item_ip = new stdClass();
                 # get the parent
                 for ($i = $key; $i >= 1; $i--) {
                     if (stripos(trim($input[$i]), 'Controller in Enclosure') !== false) {
                         $item->attached_to = trim($input[$i]);
                         break;
                     }
                 }
                 $item->description = 'Ethernet port ' . trim(str_replace('Ethernet port:', '', $value)) . ' on ' . $item->attached_to;
                 # get the details
                 for ($i = $key + 1; $i < $key + 15; $i++) {
                     if (stripos(trim($input[$i]), 'Ethernet port:') === 0) {
                         # we hit the next module, break, break from this loop
                         break;
                     }
                     if (stripos(trim($input[$i]), 'Link status:') === 0 and (!isset($item->ip_enabled) or $item->ip_enabled == '')) {
                         $item->ip_enabled = trim(str_ireplace('Status:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Network configuration:') === 0 and (!isset($item->dhcp_enabled) or $item->dhcp_enabled == '')) {
                         $item->dhcp_enabled = trim(str_ireplace('Network configuration:', '', $input[$i]));
                         if ($item->dhcp_enabled == 'Static') {
                             $item->dhcp_enabled = 'False';
                         } else {
                             $item->dhcp_enabled = 'True';
                         }
                     }
                     if (stripos(trim($input[$i]), 'MAC address:') === 0 and (!isset($item->mac) or $item->mac == '')) {
                         $item->mac = strtolower(trim(str_ireplace('MAC address:', '', $input[$i])));
                         $item_ip->mac = $item->mac;
                     }
                     if (stripos(trim($input[$i]), 'Port speed:') === 0 and (!isset($item->speed) or $item->speed == '')) {
                         $item->speed = $this->get_speed(trim(str_replace('Port speed:', '', $input[$i])));
                     }
                     if (stripos(trim($input[$i]), 'IP address:') === 0 and (!isset($item_ip->ip) or $item_ip->ip == '')) {
                         $item_ip->ip = trim(str_ireplace('IP address:', '', $input[$i]));
                         if (!filter_var($item_ip->ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) {
                             $item_ip->version = 4;
                         }
                         if (!filter_var($item_ip->ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false) {
                             $item_ip->version = 6;
                         }
                     }
                     if (stripos(trim($input[$i]), 'Subnet mask:') === 0 and (!isset($item_ip->subnet) or $item_ip->subnet == '')) {
                         $item_ip->subnet = trim(str_ireplace('Subnet mask:', '', $input[$i]));
                     }
                     if (stripos(trim($input[$i]), 'Host name:') === 0 and (!isset($details->hostname) or $details->hostname == '')) {
                         $details->hostname = trim(str_ireplace('Host name:', '', $input[$i]));
                     }
                 }
                 if (isset($item_ip->ip) and (!isset($item->ip_enabled) or $item->ip_enabled == '')) {
                     $item->ip_enabled = 'Link Up';
                 }
                 if (isset($item->ip_enabled) and stripos($item->ip_enabled, 'up') and !isset($details->ip) and isset($item_ip->ip) and $item_ip->ip != '') {
                     $details->ip = $item_ip->ip;
                 }
                 foreach ($san as $each) {
                     if ($each->location == $item->attached_to) {
                         $item->manufacturer = @$each->manufacturer;
                     }
                 }
                 $network[] = $item;
                 $ip[] = $item_ip;
                 unset($item);
                 unset($item_ip);
             }
         }
         foreach ($san as $key => $value) {
             $class_vars = get_object_vars($value);
             foreach ($class_vars as $name => $item_value) {
                 if (stripos($san[$key]->{$name}, 'Not Available') !== false or stripos($san[$key]->{$name}, 'Unknown') !== false) {
                     $san[$key]->{$name} = '';
                 }
             }
         }
         $xml = new SimpleXMLElement('<root/>');
         foreach ($san as $key => $value) {
             $item = $xml->addChild('item');
             $class_vars = get_object_vars($value);
             foreach ($class_vars as $name => $item_value) {
                 $item->{$name} = $item_value;
             }
         }
         unset($san);
         $san = $xml;
         unset($xml);
         $xml = new SimpleXMLElement('<root/>');
         foreach ($network as $key => $value) {
             $item = $xml->addChild('item');
             $class_vars = get_object_vars($value);
             foreach ($class_vars as $name => $item_value) {
                 $item->{$name} = $item_value;
             }
         }
         unset($network);
         $network = $xml;
         unset($xml);
         $xml = new SimpleXMLElement('<root/>');
         foreach ($disk as $key => $value) {
             $item = $xml->addChild('item');
             $class_vars = get_object_vars($value);
             foreach ($class_vars as $name => $item_value) {
                 $item->{$name} = $item_value;
             }
         }
         unset($disk);
         $disk = $xml;
         unset($xml);
         $xml = new SimpleXMLElement('<root/>');
         foreach ($ip as $key => $value) {
             $item = $xml->addChild('item');
             $class_vars = get_object_vars($value);
             foreach ($class_vars as $name => $item_value) {
                 $item->{$name} = $item_value;
             }
         }
         unset($ip);
         $ip = $xml;
         unset($xml);
         if ($details->hostname == 'target') {
             $details->hostname .= '-' . str_replace('.', '', $details->ip);
         }
         $details->name = $details->hostname;
         if (!empty($details->description)) {
             if ($details->description == 'DS5100') {
                 $details->model = $details->description;
             }
             if (stripos($details->description, 'DS5020') !== false) {
                 $details->model = 'DS5020';
             }
         }
         $log_details->message = 'Processing audit result for san at ' . $details->ip;
         stdlog($log_details);
         $details->last_seen = $this->config->config['timestamp'];
         $details->id = intval($this->m_system->find_system($details, 'y'));
         $details->last_seen_by = 'audit';
         $details->audits_ip = @ip_address_to_db($_SERVER['REMOTE_ADDR']);
         print_r($details);
         // // print_r($network);
         print_r($disk);
         // exit();
         if ($details->id == '') {
             // insert a new system
             $details->first_seen = $details->last_seen;
             $details->id = $this->m_system->insert_system($details);
             $log_details = new stdClass();
             $log_details->severity = 7;
             $log_details->file = 'system';
             $log_details->message = 'Inserting result for ' . $details->hostname . ' (System ID ' . $details->id . ')';
             stdlog($log_details);
             unset($log_details);
             $details->original_last_seen = "";
             echo "SystemID (new): <a href='" . base_url() . "index.php/main/system_display/" . $details->id . "'>" . $details->id . "</a>.<br />\n";
         } else {
             // update an existing system
             $log_details = new stdClass();
             $log_details->severity = 7;
             $log_details->file = 'system';
             $log_details->message = 'Updating result for ' . $details->hostname . ' (System ID ' . $details->id . ')';
             stdlog($log_details);
             unset($log_details);
             $details->original_last_seen_by = $this->m_devices_components->read($details->id, 'y', 'system', '', 'last_seen_by');
             $details->original_last_seen = $this->m_devices_components->read($details->id, 'y', 'system', '', 'last_seen');
             $this->m_system->update_system($details);
             echo "SystemID (updated): <a href='" . base_url() . "index.php/main/system_display/" . $details->id . "'>" . $details->id . "</a>.<br />\n";
         }
         $details->first_seen = $this->m_devices_components->read($details->id, 'y', 'system', '', 'first_seen');
         $temp_user = '';
         if (isset($this->user->full_name)) {
             $temp_user = $this->user->full_name;
         }
         $this->m_audit_log->create($details->id, $temp_user, $details->last_seen_by, $details->audits_ip, '', '', $details->last_seen);
         unset($temp_user);
         $this->m_audit_log->update('debug', 'san', $details->id, $details->last_seen);
         $this->m_devices_components->process_component('san', $details, $san);
         $this->m_audit_log->update('debug', 'network', $details->id, $details->last_seen);
         $this->m_devices_components->process_component('network', $details, $network);
         $this->m_audit_log->update('debug', 'disk', $details->id, $details->last_seen);
         $this->m_devices_components->process_component('disk', $details, $disk);
         $this->m_audit_log->update('debug', 'ip address', $details->id, $details->last_seen);
         $this->m_devices_components->process_component('ip', $details, $ip);
         // Finally, update any groups for this system if config item is set
         $discovery_update_groups = @$this->m_oa_config->get_config_item('discovery_update_groups');
         if (!isset($discovery_update_groups) or $discovery_update_groups == 'n') {
             # don't run the update group routine
         } else {
             $this->m_audit_log->update('debug', 'system groups', $details->id, $details->last_seen);
             $this->m_oa_group->update_system_groups($details);
         }
         $this->m_audit_log->update('debug', '', $details->id, $details->last_seen);
         $this->benchmark->mark('code_end');
         #$log_details->message = 'Processing completed for ' . $details->ip . ' (System ID ' . $details->id . '), took ' . $this->benchmark->elapsed_time('code_start', 'code_end') . ' seconds';
         #stdlog($log_details);
         unset($log_details);
     } else {
         # nothing sent, sending the form html input page
         $this->load->view('v_san_add');
     }
 }
Beispiel #27
0
 function ipmi_audit($ip, $credentials, $display)
 {
     error_reporting(E_ALL);
     $CI =& get_instance();
     $details = new stdClass();
     $log = new stdClass();
     $log->file = 'system';
     $log->severity = 7;
     if ($display == 'y') {
         $log->display = 'y';
     } else {
         $log->display = 'n';
     }
     # Detect Linux (only supported platform for IPMI)
     if (php_uname('s') != 'Linux') {
         $log->message = 'IPMI defined as useable in config, but not running Linux. IPMI not supported on other platforms';
         stdlog($log);
         return;
     }
     # detect IPMItool
     $command_string = 'which ipmitool 2>&1';
     exec($command_string, $output, $return_var);
     if ($display == 'y') {
         echo 'DEBUG - Command Executed: ' . $command_string . "\n";
         echo 'DEBUG - Return Value: ' . $return_var . "\n";
         echo "DEBUG - Command Output:\n";
         print_r($output);
     }
     if ($return_var != '0') {
         $impi_installed = 'n';
         $log->message = 'IPMI defined as useable in config, but ipmitools not detected when discovering ' . $ip;
         stdlog($log);
         return;
     } else {
         $log->message = 'IPMI detected and used (as per config) when discovering ' . $ip;
         stdlog($log);
         $impi_installed = 'y';
     }
     $command_string = null;
     $output = null;
     $return_var = null;
     // MAC Address
     $command_string = 'ipmitool -H ' . $ip . ' -U ' . $credentials->credentials->username . ' -P ' . escapeshellarg($credentials->credentials->password) . ' lan print 2>/dev/null | grep "^MAC Address" | cut -d":" -f2- | cut -d" " -f2';
     exec($command_string, $output, $return_var);
     if ($display == 'y') {
         $command_string = str_replace(escapeshellarg($credentials->credentials->password), '******', $command_string);
         echo 'DEBUG - Command Executed: ' . $command_string . "\n";
         echo 'DEBUG - Return Value: ' . $return_var . "\n";
         echo "DEBUG - Command Output:\n";
         print_r($output);
     }
     if ($return_var == '0') {
         $details->type = 'remote access controller';
         $details->last_seen_by = 'ipmi';
         $details->description = '';
         if ($details->mac_address == '') {
             $details->mac_address = strtolower($output[0]);
         }
     }
     $command_string = null;
     $output = null;
     $return_var = null;
     // Subnet Mask
     $command_string = 'ipmitool -H ' . $ip . ' -U ' . $credentials->credentials->username . ' -P ' . escapeshellarg($credentials->credentials->password) . ' lan print 2>/dev/null | grep "Subnet Mask" | cut -d":" -f2 ';
     exec($command_string, $output, $return_var);
     if ($display == 'y') {
         $command_string = str_replace(escapeshellarg($credentials->credentials->password), '******', $command_string);
         echo 'DEBUG - Command Executed: ' . $command_string . "\n";
         echo 'DEBUG - Return Value: ' . $return_var . "\n";
         echo "DEBUG - Command Output:\n";
         print_r($output);
     }
     if (isset($output[0]) and trim($output[0]) != '') {
         $details->subnet = trim($output[0]);
     }
     $command_string = null;
     $output = null;
     $return_var = null;
     // Manufacturer
     $command_string = 'ipmitool -H ' . $ip . ' -U ' . $credentials->credentials->username . ' -P ' . escapeshellarg($credentials->credentials->password) . ' fru list 2>/dev/null | grep "Product Manufacturer" | cut -d":" -f2 ';
     exec($command_string, $output, $return_var);
     if ($display == 'y') {
         $command_string = str_replace(escapeshellarg($credentials->credentials->password), '******', $command_string);
         echo 'DEBUG - Command Executed: ' . $command_string . "\n";
         echo 'DEBUG - Return Value: ' . $return_var . "\n";
         echo "DEBUG - Command Output:\n";
         print_r($output);
     }
     if (isset($output[0]) and trim($output[0]) != '') {
         $details->manufacturer = trim($output[0]);
     }
     $command_string = null;
     $output = null;
     $return_var = null;
     // Model
     $command_string = 'ipmitool -H ' . $ip . ' -U ' . $credentials->credentials->username . ' -P ' . escapeshellarg($credentials->credentials->password) . ' fru list 2>/dev/null | grep "Product Name" | cut -d":" -f2 ';
     exec($command_string, $output, $return_var);
     if ($display == 'y') {
         $command_string = str_replace(escapeshellarg($credentials->credentials->password), '******', $command_string);
         echo 'DEBUG - Command Executed: ' . $command_string . "\n";
         echo 'DEBUG - Return Value: ' . $return_var . "\n";
         echo "DEBUG - Command Output:\n";
         print_r($output);
     }
     if (isset($output[0]) and trim($output[0]) != '') {
         $details->model = trim($output[0]);
     }
     $command_string = null;
     $output = null;
     $return_var = null;
     // Serial
     $command_string = 'ipmitool -H ' . $ip . ' -U ' . $credentials->credentials->username . ' -P ' . escapeshellarg($credentials->credentials->password) . ' fru list 2>/dev/null | grep "Product Serial" | cut -d":" -f2 ';
     exec($command_string, $output, $return_var);
     if ($display == 'y') {
         $command_string = str_replace(escapeshellarg($credentials->credentials->password), '******', $command_string);
         echo 'DEBUG - Command Executed: ' . $command_string . "\n";
         echo 'DEBUG - Return Value: ' . $return_var . "\n";
         echo "DEBUG - Command Output:\n";
         print_r($output);
     }
     if (isset($output[0]) and trim($output[0]) != '') {
         $details->serial = trim($output[0]);
     }
     $command_string = null;
     $output = null;
     $return_var = null;
     # return the $details
     return $details;
 }
Beispiel #28
0
    public function create()
    {
        $CI = & get_instance();
        $log = new stdClass();
        $log->severity = 7;
        $log->file = 'system';

        if (!empty($CI->response->meta->received_data->attributes->type)) {
            $type = $CI->response->meta->received_data->attributes->type;
            $log->message = "Using type from received_data.";
            stdlog($log);
        } else {
            $type = $CI->response->meta->collection;
            $log->message = "Using type from collection.";
            stdlog($log);
        }

        # Required
        if (!empty($CI->response->meta->received_data->attributes->credentials)) {
            $credentials = (string)$this->encrypt->encode(json_encode($CI->response->meta->received_data->attributes->credentials));
            $log->message = "Using credentials from received_data.";
            stdlog($log);
        } else {
            $log->message = "Credentials not supplied - exiting." . json_encode($CI->response->meta);
            stdlog($log);
            return false;
        }

        # Required
        if (!empty($CI->response->meta->received_data->attributes->name)) {
            $name = (string)$CI->response->meta->received_data->attributes->name;
            $log->message = "Using name from received_data.";
            stdlog($log);
        } else {
            $log->message = "Name not supplied - exiting.";
            stdlog($log);
            return false;
        }

        # Optional
        if (!empty($CI->response->meta->received_data->attributes->description)) {
            $description = (string)$CI->response->meta->received_data->attributes->description;
            $log->message = "Using description from received_data.";
            stdlog($log);
        } else {
            $description = '';
        }

        # check to see if we already have a set of credentials with the same name
        $sql = "SELECT COUNT(id) AS count FROM `credentials` WHERE `name` = ?";
        $data = array($name);
        $result = $this->run_sql($sql, $data);
        if (intval($result[0]->count) != 0) {
            $log->message = "Duplicate name found - exiting.";
            stdlog($log);
            log_error('ERR-0010', 'm_credentials::create');
            return false;
        }

        # Insert the new item
        $sql = "INSERT INTO `credentials` (id, name, description, type, credentials, org_id, edited_by, edited_date) VALUES (NULL, ?, ?, ?, ?, ?, ?, NOW())";
        $data = array($name, $description, $type, $credentials, "0", $CI->user->full_name);
        $this->run_sql($sql, $data);
        $id = @$this->db->insert_id();
        if (!empty($id)) {
            $log->message = "Credentials created.";
            stdlog($log);
            return $id;
        } else {
            $log->message = "Credentials NOT created.";
            stdlog($log);
            return false;
        }
    }
Beispiel #29
0
 function update_blessed($network = '') {
     if (isset($this->config->config['blessed_subnets_use']) and trim(strtolower($this->config->config['blessed_subnets_use'])) != 'y') {
         return true;
     }
     if (empty($network)) {
         return false;
     }
     if (!$this->db->table_exists('networks')) {
         return true;
     }
     # ensure we remove and spaces - '192.168.1.0 / 24' becomes '192.168.1.0/24'
     $network = str_replace(' ', '', $network);
     # test that we have a valid subnet
     $this->load->helper('network_helper');
     $this->load->helper('log_helper');
     $test = network_details($network);
     if (!empty($test->error)) {
         return false;
     }
     # test to see if this subnet exists already in the netwokrs table
     $sql = "/* m_oa_config::update_blessed */ SELECT name FROM networks WHERE name = ?";
     $data = array("$network");
     $query = $this->db->query($sql, $data);
     if ($query->num_rows() == 0) {
         # the subnet does not exist. Log it and insert it
         $trace = debug_backtrace();
         $caller = $trace[1];
         $log_details = new stdClass();
         $log_details->severity = 7;
         $log_details->file = 'system';
         $log_details->message = "Inserting " . $network . ' into blessed subnet list.';
         stdlog($log_details);
         unset($log);
         $sql = "/* m_oa_config::update_blessed */ INSERT INTO `networks` VALUES(NULL, ?, '', ?, NOW())";
         $data = array("$network", 'auto-generated by '.@$caller['function']);
         $query = $this->db->query($sql, $data);
         return true;
     } else {
         return false;
     }
 }
Beispiel #30
0
    public function update_system($details, $display = 'n')
    {
        if (!isset($details->id) or $details->id == '') {
            # this is an update - we need a system.id
            return;
        }

        # nasty hack because when a simplexmlobject is sent (ie, from audit_windows.vbs)
        # the foreach iterators below don't work.
        # if we cast it to an "object", it stays as a SimpleXMLObject and doesn't work
        # because our XML is quite simple, we can cast it to an array and back to a 'normal'
        # object and the foreach below works.
        $details = (object) $details;
        $details = (array) $details;
        $details = (object) $details;

        if (isset($details->ip) and $details->ip != '') {
            $temp_ip = $details->ip.' ';
        } else {
            $temp_ip = '';
        }

        $log_details = new stdClass();
        $log_details->message = 'System update start for '.ip_address_from_db($temp_ip).'('.$details->hostname.') (System ID '.$details->id.')';
        $log_details->severity = 7;
        $log_details->file = 'system';
        if ($display != 'y') {
            $display = 'n';
        }
        $log_details->display = $display;
        unset($display);

        stdlog($log_details);

        unset($temp_ip);

        # If we have an ip address in the hostname field - see if we have other attributes available
        if (filter_var($details->hostname, FILTER_VALIDATE_IP)) {
            # try getting the dns hostname
            $details->hostname = strtolower(gethostbyaddr($details->ip));
            # make sure we use the hostname and not a fqdn if returned
            if (strpos($details->hostname, ".") != false) {
                if (!filter_var($details->hostname, FILTER_VALIDATE_IP)) {
                    # we got a FQDN back from DNS - split it up
                    $details->fqdn = strtolower($details->hostname);
                    $i = explode(".", $details->hostname);
                    $details->hostname = $i[0];
                    unset($i[0]);
                    $details->domain = implode(".", $i);
                    unset($i);
                } else {
                    # we got an ip address back from DNS which is now the hostname
                }
            } else {
                # we should have a real hostname if we get to here
            }
        }
        if (filter_var($details->hostname, FILTER_VALIDATE_IP) and isset($details->sysName) and $details->sysName != '') {
            # use the sysName from SNMP if set
            $details->hostname = $details->sysName;
        }

        $sql = "SELECT name FROM system WHERE id = ?";
        $sql = $this->clean_sql($sql);
        $data = array("$details->id");
        $query = $this->db->query($sql, $data);
        $result = $query->row();
        $db_name = $result->name;
        if (empty($db_name)) {
            if (!empty($details->hostname) != '' and empty($details->name)) {
                $details->name = $details->hostname;
            }
        }
        # if submitting an nmap scan, do not update the type or type
        if (isset($details->last_seen_by) and $details->last_seen_by == 'nmap') {
            unset($details->type);
        } else {
            if (!empty($details->type)) {
                $details->type = strtolower($details->type);
            }
        }

        # for removing existing symbols
        if (isset($details->os_name)) {
            $details->os_name = str_ireplace("(r)", "", $details->os_name);
            $details->os_name = str_ireplace("(tm)", "", $details->os_name);
        }

        # we check a few  items when we are submitting an audit script result
        # if they are blank (previously submitted info is incomplete) we over write them
        if (isset($details->last_seen_by) and ($details->last_seen_by == 'audit' or $details->last_seen_by == 'snmp' or $details->last_seen_by == 'ipmi')) {
            $sql = "SELECT * FROM system WHERE id = ? LIMIT 1";
            $sql = $this->clean_sql($sql);
            $data = array("$details->id");
            $query = $this->db->query($sql, $data);
            $row = $query->row();

            if (count($row) > 0) {
                if (strlen($row->hostname) > 15 and isset($details->hostname) and strlen($details->hostname) == 15) {
                    unset($details->hostname);
                }

                if (isset($details->manufacturer) and (
                    (strripos($details->manufacturer, "vmware") !== false) or
                    (strripos($details->manufacturer, "parallels") !== false) or
                    (strripos($details->manufacturer, "virtual") !== false))) {
                    $details->form_factor = 'Virtual';
                }

                if ($row->icon != '') {
                    if (isset($details->icon)) {
                        unset($details->icon);
                    }
                } else {
                    if (!isset($details->icon) or $details->icon == '') {
                        $details->icon = $details->type;
                    }
                }
            } // end of row count > 0
        }

        if (!isset($details->timestamp) or $details->timestamp == '') {
            $details->timestamp = $this->config->config['timestamp'];
        }

        if (!isset($details->original_timestamp) or $details->original_timestamp == '') {
            $sql = "SELECT last_seen FROM system WHERE id = ?";
            $sql = $this->clean_sql($sql);
            $data = array("$details->id");
            $query = $this->db->query($sql, $data);
            $row = $query->row();
            $details->original_timestamp = $row->last_seen;
        }

        if (isset($details->ip)) {
            $details->ip = ip_address_to_db($details->ip);
        }

        # if we don't have a real ip address, remove it
        if ((isset($details->ip)) and
            ($details->ip == '' or
            $details->ip == '0.0.0.0' or
            $details->ip == '000.000.000.000')) {
            unset($details->ip);
        }

        $fields = implode(' ', $this->db->list_fields('system'));
        foreach ($details as $key => $value) {
            if (($key != '') and ($value != '')) {
                # need to iterate through available columns and only insert where $key == valid column name
                if ($key != 'id' and stripos($fields, ' '.$key.' ') !== false) {
                    // OK, we have a valid attribute name ($key)
                    // get the current value
                    $sql = "SELECT `$key` AS `$key` FROM `system` WHERE `id` = ?";
                    $data = array(intval($details->id));
                    $query = $this->db->query($sql, $data);
                    $result = $query->result();
                    $previous_value = $result[0]->{$key};
                    # get the current entry in the edit_log
                    $sql = "SELECT * FROM `edit_log` WHERE `system_id` = ? AND `db_table` = 'system' AND `db_column` = ? ORDER BY `timestamp` DESC LIMIT 1";
                    $data = array(intval($details->id), "$key");
                    $query = $this->db->query($sql, $data);
                    $result = $query->result();
                    if (!empty($result[0]->weight)) {
                        $previous_weight = intval($result[0]->weight);
                    } else {
                        $previous_weight = 10000;
                    }
                    // calculate the weight
                    $weight = intval($this->weight($details->last_seen_by));
                    if ($weight <= $previous_weight and $value != $previous_value) {
                         if ($key != 'id' and $key != 'last_seen' and $key != 'last_seen_by' and $key != 'first_seen') {
                            // update the system table
                            $sql = "UPDATE `system` SET `" . $key . "` = ? WHERE id = ?";
                            $data = array((string)$value, intval($details->id));
                            $query = $this->db->query($sql, $data);
                            // insert an entry into the edit table
                            $columns_that_dont_get_edit_log = ' id sysUpTime uptime ';
                            if (stripos($columns_that_dont_get_edit_log, $key) === false) {
                                $sql = "INSERT INTO edit_log VALUES (NULL, ?, ?, 'Data was changed', ?, ?, 'system', ?, NOW(), ?, ?)";
                                $data = array(0, intval($details->id), (string)$details->last_seen_by, intval($weight), (string)$key, (string)$value, (string)$previous_value);;
                                $query = $this->db->query($sql, $data);
                            }
                        }
                    } else {
                        # We have an existing edit_log entry with a more important change - don't touch the `system`.`$key` value
                    }
                }

            }
        }

        if (!empty($details->last_seen_by)) {
            $last_seen_by = $details->last_seen_by;
        } else {
            $last_seen_by = '';
        }
        if (!empty($details->last_seen)) {
            $last_seen = $details->last_seen;
        } else {
            $last_seen = '';
        }
        $sql = "UPDATE system SET `last_seen_by` = ?, `last_seen` = ? WHERE id = ?";
        $query = $this->db->query($sql, array((string)$last_seen_by, (string)$last_seen, intval($details->id)));


        # finally, update the device icon
        $this->m_system->reset_icons($details->id);

        if (isset($details->mac_address) and $details->mac_address != '' and
            isset($details->ip) and $details->ip != '' and
            isset($details->subnet) and $details->subnet != '') {
            # we need to check if we have an entry in `network`
            # if we do not, but we have details (ex- an nmap device that previously existed but did not have a MAC, but now does)
            # we need to insert it.
            # ideally this would have already been done when the device was initially discovered, but we cannot count on that.
            # need to check if an entry in `network` exists and if it does not AND we have details, insert something

            # search for any entries in `ip`
            $sql = "SELECT * FROM ip WHERE system_id = ? AND mac = ? AND current = 'y' AND ip = ?";
            $sql = $this->clean_sql($sql);
            $data = array("$details->id", "$details->mac_address", "$details->ip");
            $query = $this->db->query($sql, $data);
            $result = $query->result();
            if (count($result) == 0) {
                # no match - insert
                $sql = "INSERT INTO ip (id, system_id, current, first_seen, last_seen, mac, net_index, ip, netmask, version, network, set_by) VALUES(NULL, ?, 'y', ?, ?, ?, '', ?, ?, '', '', '')";
                $sql = $this->clean_sql($sql);
                $data = array("$details->id", "$details->timestamp", "$details->timestamp", "$details->mac_address", "$details->ip", "$details->subnet");
                $query = $this->db->query($sql, $data);
            } else {
                # match - update timestamp only
                $sql = "UPDATE ip SET last_seen = ? WHERE system_id = ? AND mac = ? AND current = 'y' AND ip = ?";
                $sql = $this->clean_sql($sql);
                $data = array("$details->timestamp", "$details->id", "$details->mac_address", "$details->ip");
                $query = $this->db->query($sql, $data);
            }
        }

        if (isset($details->ip) and $details->ip != '') {
            $temp_ip = $details->ip.' ';
        } else {
            $temp_ip = '';
        }

        # check if we have a matching entry in the vm table and update it if required
        if (isset($details->uuid) and $details->uuid != '') {
            if (!empty($details->serial)) {
                # becauseWindows doesn't supply an identical UUID, but it does supply the required digits, make a UUID from the serial
                # which is taken from Win32_ComputerSystemProduct.IdentifyingNumber
                # Vmware supplies - 564d3739-b4cb-1a7e-fbb1-b10dcc0335e1
                # audit_windows supples - VMware-56 4d 37 39 b4 cb 1a 7e-fb b1 b1 0d cc 03 35 e1
                $windows_vm_uuid = str_ireplace('VMware-', '', $details->serial);
                $windows_vm_uuid = str_ireplace('-', ' ', $windows_vm_uuid);
                $windows_vm_uuid = strtolower($windows_vm_uuid);
                $windows_vm_uuid = str_ireplace(' ', '', $windows_vm_uuid);
                $windows_vm_uuid = substr($windows_vm_uuid, 0, 8) . '-'. substr($windows_vm_uuid, 8, 4) . '-' . substr($windows_vm_uuid, 12, 4) . '-' . substr($windows_vm_uuid, 16, 4) . '-' . substr($windows_vm_uuid, 20, 12);
            } else {
                $windows_vm_uuid = '';
            }
            $sql = "SELECT vm.id, vm.system_id AS 'vm_system_id', system.hostname AS 'vm_server_name' FROM vm, system WHERE LOWER(vm.uuid) = LOWER(?) OR LOWER(vm.uuid) = LOWER(?) AND vm.current = 'y' and vm.system_id = system.id and vm.uuid != ''";
            $sql = $this->clean_sql($sql);
            $data = array("$details->uuid", "$windows_vm_uuid");
            $query = $this->db->query($sql, $data);
            if ($query->num_rows() > 0) {
                $row = $query->row();
                $temp_vm_id = $row->id;
                $details->vm_system_id = $row->vm_system_id;
                $details->vm_server_name = $row->vm_server_name;
                $sql = "SELECT icon  FROM system WHERE system.id = ?";
                $sql = $this->clean_sql($sql);
                $data = array($details->id);
                $query = $this->db->query($sql, $data);
                $row = $query->row();
                $details->icon = $row->icon;
                $sql = "UPDATE vm SET guest_system_id = ?, icon = ? WHERE id = ?";
                $sql = $this->clean_sql($sql);
                $data = array($details->id, "$details->icon", "$temp_vm_id");
                $query = $this->db->query($sql, $data);
                $sql = "UPDATE system SET vm_system_id = ?, vm_server_name = ? WHERE id = ?";
                $sql = $this->clean_sql($sql);
                $data = array($details->vm_system_id, $details->vm_server_name, $details->id);
                $query = $this->db->query($sql, $data);
            }
        }

        if (empty($details->org_id)) {
            $sql = "SELECT org_id FROM system WHERE id = ?";
            $sql = $this->clean_sql($sql);
            $data = array($details->id);
            $query = $this->db->query($sql, $data);
            $row = $query->row();
            $details->org_id = $row->org_id;
        }

        # add a count to our chart table
        $sql = "INSERT INTO chart (`when`, `what`, `org_id`, `count`) VALUES (DATE(NOW()), '" . $details->last_seen_by . "', " . $details->org_id . ", 1) ON DUPLICATE KEY UPDATE `count` = `count` + 1";
        $sql = $this->clean_sql($sql);
        $query = $this->db->query($sql);

        $log_details->message = 'System update end for '.ip_address_from_db($temp_ip).'('.$details->hostname.') (System ID '.$details->id.')';
        stdlog($log_details);
        unset($log_details);
        unset($temp_ip);
    }