/**
  * Import data
  *
  * @param $p_DEVICEID XML code to import
  * @param $p_CONTENT XML code to import
  * @param $p_xml value XML code to import
  *
  * @return "" (import ok) / error string (import ko)
  *
  **/
 function import($p_DEVICEID, $a_CONTENT, $arrayinventory)
 {
     $pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
     $pfAgent = new PluginFusioninventoryAgent();
     PluginFusioninventoryCommunication::addLog('Function PluginFusioninventoryCommunicationNetworkDiscovery->import().');
     $errors = '';
     $a_agent = $pfAgent->InfosByKey($p_DEVICEID);
     if (isset($a_CONTENT['PROCESSNUMBER'])) {
         $_SESSION['glpi_plugin_fusioninventory_processnumber'] = $a_CONTENT['PROCESSNUMBER'];
         if ($pfTaskjobstate->getFromDB($a_CONTENT['PROCESSNUMBER'])) {
             if ($pfTaskjobstate->fields['state'] != "3") {
                 $pfTaskjobstate->changeStatus($a_CONTENT['PROCESSNUMBER'], 2);
                 if (!isset($a_CONTENT['AGENT']['START']) and !isset($a_CONTENT['AGENT']['END'])) {
                     $nb_devices = 0;
                     if (isset($a_CONTENT['DEVICE'])) {
                         if (is_int(key($a_CONTENT['DEVICE']))) {
                             $nb_devices = count($a_CONTENT['DEVICE']);
                         } else {
                             $nb_devices = 1;
                         }
                     }
                     $_SESSION['plugin_fusinvsnmp_taskjoblog']['taskjobs_id'] = $a_CONTENT['PROCESSNUMBER'];
                     $_SESSION['plugin_fusinvsnmp_taskjoblog']['items_id'] = $a_agent['id'];
                     $_SESSION['plugin_fusinvsnmp_taskjoblog']['itemtype'] = 'PluginFusioninventoryAgent';
                     $_SESSION['plugin_fusinvsnmp_taskjoblog']['state'] = '6';
                     $_SESSION['plugin_fusinvsnmp_taskjoblog']['comment'] = $nb_devices . ' ==devicesfound==';
                     $this->addtaskjoblog();
                 }
             }
         }
     }
     if ($pfTaskjobstate->getFromDB($a_CONTENT['PROCESSNUMBER'])) {
         if ($pfTaskjobstate->fields['state'] != "3") {
             $pfImportExport = new PluginFusioninventorySnmpmodelImportExport();
             $errors .= $pfImportExport->import_netdiscovery($a_CONTENT, $p_DEVICEID);
             if (isset($a_CONTENT['AGENT']['END'])) {
                 if (isset($a_CONTENT['DICO']) and $a_CONTENT['DICO'] == "REQUEST") {
                     $pfAgent->getFromDB($pfTaskjobstate->fields["plugin_fusioninventory_agents_id"]);
                     $input = array();
                     $input['id'] = $pfAgent->fields['id'];
                     $input["senddico"] = "1";
                     $pfAgent->update($input);
                     $pfTaskjobstate->changeStatusFinish($a_CONTENT['PROCESSNUMBER'], $a_agent['id'], 'PluginFusioninventoryAgent', '1', '==diconotuptodate==');
                 } else {
                     $messages = array('Total Found' => 0, 'Created' => 0, 'Updated' => 0);
                     $messages['Updated'] = countElementsInTable('glpi_plugin_fusioninventory_taskjoblogs', "`plugin_fusioninventory_taskjobstates_id`='" . $a_CONTENT['PROCESSNUMBER'] . "' " . " AND `comment` LIKE '%==updatetheitem==%'");
                     $messages['Created'] = countElementsInTable('glpi_plugin_fusioninventory_taskjoblogs', "`plugin_fusioninventory_taskjobstates_id`='" . $a_CONTENT['PROCESSNUMBER'] . "' " . " AND `comment` LIKE '%==addtheitem==%'");
                     $messages['Total Found'] = $messages['Updated'] + $messages['Created'];
                     $message = 'Total Found:' . $messages['Total Found'] . ' Created:' . $messages['Created'] . ' Updated:' . $messages['Updated'];
                     $pfTaskjobstate->changeStatusFinish($a_CONTENT['PROCESSNUMBER'], $a_agent['id'], 'PluginFusioninventoryAgent', '0', $message);
                 }
             }
         }
     }
     return $errors;
 }
  ------------------------------------------------------------------------
*/
ob_start();
include "../../../../inc/includes.php";
ob_end_clean();
$response = array();
//Agent communication using REST protocol
if (isset($_GET['action'])) {
    switch ($_GET['action']) {
        case 'getJobs':
            if (isset($_GET['machineid'])) {
                $pfAgent = new PluginFusioninventoryAgent();
                $pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
                $pfTaskjoblog = new PluginFusioninventoryTaskjoblog();
                $a_agent = $pfAgent->InfosByKey(Toolbox::addslashes_deep($_GET['machineid']));
                if (isset($a_agent['id'])) {
                    $moduleRun = $pfTaskjobstate->getTaskjobsAgent($a_agent['id']);
                    foreach ($moduleRun as $className => $array) {
                        if (class_exists($className)) {
                            if ($className == "PluginFusioninventoryCollect") {
                                $class = new PluginFusioninventoryCollect();
                                foreach ($array as $data) {
                                    $out = $class->run($data, $a_agent);
                                    if (count($out) > 0) {
                                        $response[] = $out;
                                    }
                                    $pfTaskjobstate->changeStatus($data['id'], PluginFusioninventoryTaskjobstate::SERVER_HAS_SENT_DATA);
                                    $a_input = array();
                                    $a_input['plugin_fusioninventory_taskjobstates_id'] = $data['id'];
                                    $a_input['items_id'] = $a_agent['id'];
 function import_netdiscovery($arrayinventory, $agentKey)
 {
     PluginFusioninventoryCommunication::addLog('Function PluginFusioninventorySnmpmodelImportExport->import_netdiscovery().');
     $ptap = new PluginFusioninventoryStateDiscovery();
     $pta = new PluginFusioninventoryAgent();
     $agent = $pta->InfosByKey($agentKey);
     if (isset($arrayinventory['AGENT']['START'])) {
         $ptap->updateState($arrayinventory['PROCESSNUMBER'], array('start_time' => date("Y-m-d H:i:s")), $agent['id']);
     } else {
         if (isset($arrayinventory['AGENT']['END'])) {
             $ptap->updateState($arrayinventory['PROCESSNUMBER'], array('end_time' => date("Y-m-d H:i:s")), $agent['id']);
         } else {
             if (isset($arrayinventory['AGENT']['EXIT'])) {
                 $ptap->endState($arrayinventory['PROCESSNUMBER'], date("Y-m-d H:i:s"), $agent['id']);
             } else {
                 if (isset($arrayinventory['AGENT']['NBIP'])) {
                     $ptap->updateState($arrayinventory['PROCESSNUMBER'], array('nb_ip' => $arrayinventory['AGENT']['NBIP']), $agent['id']);
                 }
             }
         }
     }
     if (isset($arrayinventory['AGENT']['AGENTVERSION'])) {
         $agent['last_contact'] = date("Y-m-d H:i:s");
         $pta->update($agent);
     }
     $_SESSION['glpi_plugin_fusioninventory_agentid'] = $agent['id'];
     $count_discovery_devices = 0;
     if (isset($arrayinventory['DEVICE'])) {
         if (is_int(key($arrayinventory['DEVICE']))) {
             $count_discovery_devices = count($arrayinventory['DEVICE']);
         } else {
             $count_discovery_devices = 1;
         }
     }
     if ($count_discovery_devices != "0") {
         $ptap->updateState($_SESSION['glpi_plugin_fusioninventory_processnumber'], array('nb_found' => $count_discovery_devices), $agent['id']);
         if (is_int(key($arrayinventory['DEVICE']))) {
             foreach ($arrayinventory['DEVICE'] as $discovery) {
                 if (count($discovery) > 0) {
                     $pfCommunicationNetworkDiscovery = new PluginFusioninventoryCommunicationNetworkDiscovery();
                     $pfCommunicationNetworkDiscovery->sendCriteria($discovery);
                 }
             }
         } else {
             $pfCommunicationNetworkDiscovery = new PluginFusioninventoryCommunicationNetworkDiscovery();
             $pfCommunicationNetworkDiscovery->sendCriteria($arrayinventory['DEVICE']);
         }
     }
 }
 /**
  * Import the content (where have all devices)
  *@param $p_content CONTENT code to import
  *
  *@return errors string to be alimented if import ko / '' if ok
  **/
 function importContent($arrayinventory)
 {
     PluginFusioninventoryCommunication::addLog('Function PluginFusioninventoryCommunicationNetworkInventory->importContent().');
     $pfAgent = new PluginFusioninventoryAgent();
     $errors = '';
     $nbDevices = 0;
     foreach ($arrayinventory as $childname => $child) {
         PluginFusioninventoryCommunication::addLog($childname);
         switch ($childname) {
             case 'DEVICE':
                 $a_devices = array();
                 if (is_int(key($child))) {
                     $a_devices = $child;
                 } else {
                     $a_devices[] = $child;
                 }
                 $xml_num = 0;
                 foreach ($a_devices as $dchild) {
                     $_SESSION['plugin_fusioninventory_xmlnum'] = $xml_num;
                     $a_inventory = array();
                     if (isset($dchild['INFO'])) {
                         if ($dchild['INFO']['TYPE'] == "NETWORKING") {
                             $a_inventory = PluginFusioninventoryFormatconvert::networkequipmentInventoryTransformation($dchild);
                         } else {
                             if ($dchild['INFO']['TYPE'] == "PRINTER") {
                                 $a_inventory = PluginFusioninventoryFormatconvert::printerInventoryTransformation($dchild);
                             }
                         }
                     }
                     if (isset($dchild['ERROR'])) {
                         $itemtype = "";
                         if ($dchild['ERROR']['TYPE'] == "NETWORKING") {
                             $itemtype = "NetworkEquipment";
                         } else {
                             if ($dchild['ERROR']['TYPE'] == "PRINTER") {
                                 $itemtype = "Printer";
                             }
                         }
                         $_SESSION['plugin_fusinvsnmp_taskjoblog']['comment'] = '[==detail==] ' . $dchild['ERROR']['MESSAGE'] . ' [[' . $itemtype . '::' . $dchild['ERROR']['ID'] . ']]';
                         $this->addtaskjoblog();
                     } else {
                         if ($a_inventory['PluginFusioninventory' . $a_inventory['itemtype']]['sysdescr'] == '' && $a_inventory[$a_inventory['itemtype']]['name'] == '' && $a_inventory[$a_inventory['itemtype']]['serial'] == '') {
                             $_SESSION['plugin_fusinvsnmp_taskjoblog']['comment'] = '[==detail==] No informations [[' . $a_inventory['itemtype'] . '::' . $dchild['INFO']['ID'] . ']]';
                             $this->addtaskjoblog();
                         } else {
                             if (count($a_inventory) > 0) {
                                 $errors .= $this->sendCriteria($a_inventory);
                                 $nbDevices++;
                             }
                         }
                     }
                     $xml_num++;
                 }
                 break;
             case 'AGENT':
                 if (isset($this->arrayinventory['CONTENT']['AGENT']['AGENTVERSION'])) {
                     $agent = $pfAgent->InfosByKey($this->arrayinventory['DEVICEID']);
                     $agent['fusioninventory_agent_version'] = $this->arrayinventory['CONTENT']['AGENT']['AGENTVERSION'];
                     $agent['last_agent_update'] = date("Y-m-d H:i:s");
                     $pfAgent->update($agent);
                 }
                 break;
             case 'PROCESSNUMBER':
                 break;
             case 'MODULEVERSION':
                 break;
             default:
                 $_SESSION['plugin_fusinvsnmp_taskjoblog']['comment'] = '[==detail==] ' . __('Unattended element in', 'fusioninventory') . ' CONTENT : ' . $childname;
                 $this->addtaskjoblog();
         }
     }
     return $errors;
 }
 /**
  * Manage communication with old protocol (XML over POST)
  *
  **/
 function handleOCSCommunication($rawdata, $xml = '', $output = 'ext')
 {
     // ***** For debug only ***** //
     //$rawdata = gzcompress('');
     // ********** End ********** //
     $config = new PluginFusioninventoryConfig();
     $user = new User();
     //      ob_start();
     if (!isset($_SESSION['glpiID'])) {
         $users_id = $config->getValue('users_id');
         $_SESSION['glpiID'] = $users_id;
         $user->getFromDB($users_id);
         Session::changeActiveEntities();
         $_SESSION["glpiname"] = $user->getField('name');
         $_SESSION['glpiactiveprofile'] = array();
         $_SESSION['glpiactiveprofile']['interface'] = 'central';
         $_SESSION['glpiactiveprofile']['internet'] = 'w';
         $_SESSION['glpiactiveprofile']['computer'] = 'w';
         $_SESSION['glpiactiveprofile']['monitor'] = 'w';
         $_SESSION['glpiactiveprofile']['printer'] = 'w';
         $_SESSION['glpiactiveprofile']['peripheral'] = 'w';
         $_SESSION['glpiactiveprofile']['networking'] = 'w';
         $_SESSION["glpi_plugin_fusioninventory_profile"]['unmanaged'] = 'w';
     }
     $communication = new PluginFusioninventoryCommunication();
     $pfToolbox = new PluginFusioninventoryToolbox();
     // identify message compression algorithm
     $agent = new PluginFusioninventoryAgent();
     $agent->disableDebug();
     $compressmode = '';
     if (!empty($xml)) {
         $compressmode = 'none';
     } else {
         if ($_SERVER['CONTENT_TYPE'] == "application/x-compress-zlib") {
             $xml = gzuncompress($rawdata);
             $compressmode = "zlib";
         } else {
             if ($_SERVER['CONTENT_TYPE'] == "application/x-compress-gzip") {
                 $xml = $pfToolbox->gzdecode($rawdata);
                 $compressmode = "gzip";
             } else {
                 if ($_SERVER['CONTENT_TYPE'] == "application/xml") {
                     $xml = $rawdata;
                     $compressmode = 'none';
                 } else {
                     # try each algorithm successively
                     if ($xml = gzuncompress($rawdata)) {
                         $compressmode = "zlib";
                     } else {
                         if ($xml = $pfToolbox->gzdecode($rawdata)) {
                             $compressmode = "gzip";
                         } else {
                             if ($xml = gzinflate(substr($rawdata, 2))) {
                                 // accept deflate for OCS agent 2.0 compatibility,
                                 // but use zlib for answer
                                 if (strstr($xml, "<QUERY>PROLOG</QUERY>") and !strstr($xml, "<TOKEN>")) {
                                     $compressmode = "zlib";
                                 } else {
                                     $compressmode = "deflate";
                                 }
                             } else {
                                 $xml = $rawdata;
                                 $compressmode = 'none';
                             }
                         }
                     }
                 }
             }
         }
     }
     $agent->restoreDebug();
     // check if we are in ssl only mode
     $ssl = $config->getValue('ssl_only');
     if ($ssl == "1" and (!isset($_SERVER["HTTPS"]) or $_SERVER["HTTPS"] != "on")) {
         if ($output == 'glpi') {
             Session::addMessageAfterRedirect('SSL REQUIRED BY SERVER', false, ERROR);
         } else {
             $communication->setMessage("<?xml version='1.0' encoding='UTF-8'?>\n<REPLY>\n   <ERROR>SSL REQUIRED BY SERVER</ERROR>\n</REPLY>");
             $communication->sendMessage($compressmode);
         }
         return;
     }
     PluginFusioninventoryConfig::logIfExtradebug('pluginFusioninventory-dial' . uniqid(), $xml);
     // Check XML integrity
     $pxml = '';
     if ($pxml = @simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)) {
     } else {
         if ($pxml = @simplexml_load_string(utf8_encode($xml), 'SimpleXMLElement', LIBXML_NOCDATA)) {
             $xml = utf8_encode($xml);
         } else {
             $xml = preg_replace('/<FOLDER>.*?<\\/SOURCE>/', '', $xml);
             $pxml = @simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
             if (!$pxml) {
                 if ($output == 'glpi') {
                     Session::addMessageAfterRedirect('XML not well formed!', false, ERROR);
                 } else {
                     $communication->setMessage("<?xml version='1.0' encoding='UTF-8'?>\n<REPLY>\n   <ERROR>XML not well formed!</ERROR>\n</REPLY>");
                     $communication->sendMessage($compressmode);
                 }
                 return;
             }
         }
     }
     $_SESSION['plugin_fusioninventory_compressmode'] = $compressmode;
     // Convert XML into PHP array
     $arrayinventory = PluginFusioninventoryFormatconvert::XMLtoArray($pxml);
     unset($pxml);
     $deviceid = '';
     if (isset($arrayinventory['DEVICEID'])) {
         $deviceid = $arrayinventory['DEVICEID'];
     }
     $agent = new PluginFusioninventoryAgent();
     $agents_id = $agent->importToken($arrayinventory);
     $_SESSION['plugin_fusioninventory_agents_id'] = $agents_id;
     if (!$communication->import($arrayinventory)) {
         if ($deviceid != '') {
             $communication->setMessage("<?xml version='1.0' encoding='UTF-8'?>\n<REPLY>\n</REPLY>");
             $a_agent = $agent->InfosByKey($deviceid);
             // Get taskjob in waiting
             $communication->getTaskAgent($a_agent['id']);
             // ******** Send XML
             $communication->addInventory($a_agent['id']);
             $communication->addProlog();
             $communication->sendMessage($compressmode);
         }
     } else {
         if ($output == 'glpi') {
             Session::addMessageAfterRedirect('XML has been imported succesfully!');
         } else {
             $communication->setMessage("<?xml version='1.0' encoding='UTF-8'?>\n<REPLY>\n</REPLY>");
             $communication->sendMessage($compressmode);
         }
     }
 }