You should have received a copy of the GNU General Public License
along with ocsinventoryng. If not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------
*/
include '../../../inc/includes.php';
Session::checkRight("plugin_ocsinventoryng", UPDATE);
Html::header('OCS Inventory NG', '', "tools", "pluginocsinventoryngmenu", "sync");
$display_list = true;
if (isset($_SESSION["ocs_update"]['computers'])) {
    if ($count = count($_SESSION["ocs_update"]['computers'])) {
        $percent = min(100, round(100 * ($_SESSION["ocs_update_count"] - $count) / $_SESSION["ocs_update_count"], 0));
        $key = array_pop($_SESSION["ocs_update"]['computers']);
        $cfg_ocs = PluginOcsinventoryngOcsServer::getConfig($_SESSION["plugin_ocsinventoryng_ocsservers_id"]);
        $dohistory = isset($cfg_ocs['dohistory']) ? $cfg_ocs['dohistory'] : false;
        $action = PluginOcsinventoryngOcsServer::updateComputer($key, $_SESSION["plugin_ocsinventoryng_ocsservers_id"], $dohistory);
        PluginOcsinventoryngOcsServer::manageImportStatistics($_SESSION["ocs_update"]['statistics'], $action['status']);
        PluginOcsinventoryngOcsServer::showStatistics($_SESSION["ocs_update"]['statistics']);
        Html::displayProgressBar(400, $percent);
        Html::redirect($_SERVER['PHP_SELF']);
    } else {
        if (isset($_SESSION["ocs_update"]['statistics'])) {
            PluginOcsinventoryngOcsServer::showStatistics($_SESSION["ocs_update"]['statistics'], true);
        } else {
            echo "<div class='center b red'>";
            _e('No synchronization: the plugin will not synchronize these elements', 'ocsinventoryng');
            echo "</div>";
        }
        unset($_SESSION["ocs_update"]);
        $display_list = false;
        echo "<div class='center b'><br>";
        echo "<a href='" . $_SERVER['PHP_SELF'] . "'>" . __('Back') . "</a></div>";
/**
 * @param $threads_id
 * @param $cfg_ocs
 * @param $server
 * @param $thread_nbr
 * @param $threadid
 * @param $fields
 * @param $config
**/
function plugin_ocsinventoryng_importFromOcsServer($threads_id, $cfg_ocs, $server, $thread_nbr, $threadid, $fields, $config)
{
    global $PluginOcsinventoryngDBocs;
    echo "\tThread #" . $threadid . ": import computers from server: '" . $cfg_ocs["name"] . "'\n";
    $where_multi_thread = '';
    $limit = "";
    if ($thread_nbr != -1 && $threadid != -1 && $thread_nbr > 1) {
        $where_multi_thread = " AND `ID` % {$thread_nbr} = " . ($threadid - 1);
    }
    if ($config->fields["import_limit"] > 0) {
        $limit = " LIMIT " . $config->fields["import_limit"];
    }
    $query_ocs = "SELECT `ID`\n                 FROM `hardware`\n                 INNER JOIN `accountinfo` ON (`hardware`.`ID` = `accountinfo`.`HARDWARE_ID`)\n                 WHERE ((CHECKSUM&" . intval($cfg_ocs["checksum"]) . ") > 0\n                        OR `LASTDATE` > '" . $server->fields["max_glpidate"] . "')\n                       AND TIMESTAMP(`LASTDATE`) < (NOW()-180)\n                       AND `ID` <= " . intval($server->fields["max_ocsid"]);
    if (!empty($cfg_ocs["tag_limit"])) {
        $splitter = explode("\$", $cfg_ocs["tag_limit"]);
        if (count($splitter)) {
            $query_ocs .= " AND `accountinfo`.`TAG` IN ('" . $splitter[0] . "'";
            for ($i = 1; $i < count($splitter); $i++) {
                $query_ocs .= ",'" . $splitter[$i] . "'";
            }
            $query_ocs .= ")";
        }
    }
    $query_ocs .= "{$where_multi_thread}\n                  {$limit}";
    $result_ocs = $PluginOcsinventoryngDBocs->query($query_ocs);
    $nb = $PluginOcsinventoryngDBocs->numrows($result_ocs);
    echo "\tThread #{$threadid}: {$nb} computer(s)\n";
    $fields["total_number_machines"] += $nb;
    $thread = new PluginOcsinventoryngThread();
    $notimport = new PluginOcsinventoryngNotimportedcomputer();
    for ($i = 0; $data = $PluginOcsinventoryngDBocs->fetch_array($result_ocs); $i++) {
        if ($i == $config->fields["thread_log_frequency"]) {
            $fields["status"] = PLUGIN_OCSINVENTORYNG_STATE_RUNNING;
            $thread->update($fields);
            $i = 0;
        }
        echo ".";
        $entities_id = 0;
        $action = PluginOcsinventoryngOcsServer::processComputer($data["ID"], $cfg_ocs["id"], 1);
        PluginOcsinventoryngOcsServer::manageImportStatistics($fields, $action['status']);
        switch ($action['status']) {
            case PluginOcsinventoryngOcsServer::COMPUTER_NOT_UNIQUE:
            case PluginOcsinventoryngOcsServer::COMPUTER_FAILED_IMPORT:
            case PluginOcsinventoryngOcsServer::COMPUTER_LINK_REFUSED:
                $notimport->logNotImported($cfg_ocs["id"], $data["ID"], $action);
                break;
            default:
                $notimport->cleanNotImported($cfg_ocs["id"], $data["ID"]);
                //Log detail
                $detail = new PluginOcsinventoryngDetail();
                $detail->logProcessedComputer($data["ID"], $cfg_ocs["id"], $action, $threadid, $threads_id);
                break;
        }
    }
    return $fields;
}
         $action = $ip->processIpDiscover($ipObject, $_SESSION["plugin_ocsinventoryng_ocsservers_id"], $_POST["subnet"]);
         PluginOcsinventoryngOcsServer::manageImportStatistics($_SESSION["ocs_importipdiscover"]['statistics'], $action['status'], false, true);
         PluginOcsinventoryngOcsServer::showStatistics($_SESSION["ocs_importipdiscover"]['statistics'], false, false, true);
         Html::displayProgressBar(400, $percent);
         $_SESSION["ocs_importipdiscover"]["datas"]["ipObjects"] = $ipObjects;
         $_SESSION["ocs_importipdiscover"]["datas"]["b"] = $_GET["b"];
         $_SESSION["ocs_importipdiscover"]["datas"]["macAdresses"] = $macAdresses;
         Html::redirect($_SERVER['PHP_SELF']);
     }
 } else {
     if (isset($_SESSION["ocs_importipdiscover"]["datas"])) {
         $action = null;
         while ($ipObject = array_pop($_SESSION["ocs_importipdiscover"]["datas"]["ipObjects"])) {
             $percent = min(100, round(100 * (sizeof($_SESSION["ocs_importipdiscover"]["datas"]["macAdresses"]) - sizeof($_SESSION["ocs_importipdiscover"]["datas"]["ipObjects"])) / sizeof($_SESSION["ocs_importipdiscover"]["datas"]["macAdresses"]), 0));
             $action = $ip->processIpDiscover($ipObject, $_SESSION["plugin_ocsinventoryng_ocsservers_id"], $_POST["subnet"]);
             PluginOcsinventoryngOcsServer::manageImportStatistics($_SESSION["ocs_importipdiscover"]['statistics'], $action['status'], false, true);
             PluginOcsinventoryngOcsServer::showStatistics($_SESSION["ocs_importipdiscover"]['statistics'], false, false, true);
             Html::displayProgressBar(400, $percent);
             Html::redirect($_SERVER['PHP_SELF']);
         }
         PluginOcsinventoryngOcsServer::showStatistics($_SESSION["ocs_importipdiscover"]['statistics'], false, false, true);
         if (isset($_GET["b"])) {
             $b = $_GET["b"];
             $ipAdress = $b[0];
             $status = $b[1];
             echo "<div class='center b'><br>";
             echo "<a href='" . $_SERVER['PHP_SELF'] . "?ip={$ipAdress}&status={$status}'>" . __('Back') . "</a></div>";
         }
         if (isset($_SESSION["ocs_importipdiscover"]["datas"]["b"])) {
             $b = $_SESSION["ocs_importipdiscover"]["datas"]["b"];
             $ipAdress = $b[0];
/**
 * @param $threads_id
 * @param $cfg_ocs
 * @param $server
 * @param $thread_nbr
 * @param $threadid
 * @param $fields
 * @param $config
**/
function plugin_ocsinventoryng_importFromOcsServer($threads_id, $cfg_ocs, $server, $thread_nbr, $threadid, $fields, $config)
{
    echo "\tThread #" . $threadid . ": import computers from server: '" . $cfg_ocs["name"] . "'\n";
    $multiThread = false;
    if ($threadid != -1 && $thread_nbr > 1) {
        $multiThread = true;
    }
    $ocsServerId = $cfg_ocs['id'];
    $ocsClient = PluginOcsinventoryngOcsServer::getDBocs($ocsServerId);
    $ocsComputers = array();
    // Build common options
    $inventoriedBefore = new DateTime('@' . (time() - 180));
    $computerOptions = array('FILTER' => array('INVENTORIED_BEFORE' => $inventoriedBefore->format('Y-m-d H:i:s')));
    // Limit the number of imported records according to config
    if ($config->fields["import_limit"] > 0) {
        $computerOptions['MAX_RECORDS'] = $config->fields["import_limit"];
    }
    // Filter tags according to config
    if ($cfg_ocs["tag_limit"] and $tag_limit = explode("\$", trim($cfg_ocs["tag_limit"]))) {
        $computerOptions['FILTER']['TAGS'] = $tag_limit;
    }
    if ($cfg_ocs["tag_limit"] and $tag_exclude = explode("\$", trim($cfg_ocs["tag_exclude"]))) {
        $computerOptions['FILTER']['EXCLUDE_TAGS'] = $tag_exclude;
    }
    // Get newly inventoried computers
    $firstQueryOptions = $computerOptions;
    if ($server->fields["max_glpidate"] != '0000-00-00 00:00:00') {
        $firstQueryOptions['FILTER']['INVENTORIED_SINCE'] = $server->fields["max_glpidate"];
    }
    $ocsResult = $ocsClient->getComputers($firstQueryOptions);
    // Filter only useful computers
    // Some conditions can't be sent to OCS, so we have to do this in a loop
    // Maybe add this to SOAP ?
    $excludeIds = array();
    foreach ($ocsResult['COMPUTERS'] as $ID => $computer) {
        if ($ID <= intval($server->fields["max_ocsid"]) and (!$multiThread or $ID % $thread_nbr == $threadid - 1)) {
            $ocsComputers[$ID] = $computer;
        }
        $excludeIds[] = $ID;
    }
    // Get computers for which checksum has changed
    $secondQueryOptions = $computerOptions;
    $secondQueryOptions['FILTER']['EXLUDE_IDS'] = $excludeIds;
    $secondQueryOptions['FILTER']['CHECKSUM'] = intval($cfg_ocs["checksum"]);
    $ocsResult = $ocsClient->getComputers($secondQueryOptions);
    // Filter only useful computers
    // Some conditions can't be sent to OCS, so we have to do this in a loop
    // Maybe add this to SOAP ?
    if (isset($ocsResult['COMPUTERS'])) {
        foreach ($ocsResult['COMPUTERS'] as $ID => $computer) {
            if ($ID <= intval($server->fields["max_ocsid"]) and (!$multiThread or $ID % $thread_nbr == $threadid - 1)) {
                $ocsComputers[$ID] = $computer;
            }
        }
    }
    // Limit the number of imported records according to config
    if ($config->fields["import_limit"] > 0 and count($ocsComputers) > $config->fields["import_limit"]) {
        $ocsComputers = array_splice($ocsComputers, $config->fields["import_limit"]);
    }
    $nb = count($ocsComputers);
    echo "\tThread #{$threadid}: {$nb} computer(s)\n";
    $fields["total_number_machines"] += $nb;
    $thread = new PluginOcsinventoryngThread();
    $notimport = new PluginOcsinventoryngNotimportedcomputer();
    $i = 0;
    foreach ($ocsComputers as $ID => $ocsComputer) {
        if ($i == $config->fields["thread_log_frequency"]) {
            $fields["status"] = PLUGIN_OCSINVENTORYNG_STATE_RUNNING;
            $thread->update($fields);
            $i = 0;
        } else {
            $i++;
        }
        echo ".";
        $entities_id = 0;
        $action = PluginOcsinventoryngOcsServer::processComputer($ID, $ocsServerId, 1);
        PluginOcsinventoryngOcsServer::manageImportStatistics($fields, $action['status']);
        switch ($action['status']) {
            case PluginOcsinventoryngOcsServer::COMPUTER_NOT_UNIQUE:
            case PluginOcsinventoryngOcsServer::COMPUTER_FAILED_IMPORT:
            case PluginOcsinventoryngOcsServer::COMPUTER_LINK_REFUSED:
                $notimport->logNotImported($ocsServerId, $ID, $action);
                break;
            default:
                $notimport->cleanNotImported($ocsServerId, $ID);
                //Log detail
                $detail = new PluginOcsinventoryngDetail();
                $detail->logProcessedComputer($ID, $ocsServerId, $action, $threadid, $threads_id);
                break;
        }
    }
    return $fields;
}
/**
 * @param $threads_id
 * @param $cfg_ocs
 * @param $server
 * @param $thread_nbr
 * @param $threadid
 * @param $fields
 * @param $config
 *
 * @return mixed
 */
function importSNMPFromOcsServer($threads_id, $cfg_ocs, $server, $thread_nbr, $threadid, $fields, $config)
{
    global $DB;
    echo "\tThread #" . $threadid . ": synchronize SNMP objects from server: '" . $cfg_ocs["name"] . "'\n";
    $multiThread = false;
    if ($threadid != -1 && $thread_nbr > 1) {
        $multiThread = true;
    }
    $ocsServerId = $cfg_ocs['id'];
    $ocsClient = PluginOcsinventoryngOcsServer::getDBocs($ocsServerId);
    $already_linked_query = "SELECT `glpi_plugin_ocsinventoryng_snmpocslinks`.`ocs_id`,`glpi_plugin_ocsinventoryng_snmpocslinks`.`id`\n                               FROM `glpi_plugin_ocsinventoryng_snmpocslinks`\n                               WHERE `glpi_plugin_ocsinventoryng_snmpocslinks`.`plugin_ocsinventoryng_ocsservers_id`\n                                            = '{$ocsServerId}'";
    $already_linked_result = $DB->query($already_linked_query);
    $already_linked_ids = array();
    if ($DB->numrows($already_linked_result) > 0) {
        while ($data = $DB->fetch_assoc($already_linked_result)) {
            $already_linked_ocs_ids[] = $data['ocs_id'];
            //         $already_linked_ids [] = $data['id'];
        }
    }
    $ocsResult = $ocsClient->getSnmp(array('ORDER' => 'LASTDATE', 'COMPLETE' => '0', 'FILTER' => array('IDS' => $already_linked_ocs_ids)));
    //Unset SNMP objects not updated by OCS
    foreach ($ocsResult['SNMP'] as $ID => $snmpids) {
        $last_update = date('Y-m-d H:m:s');
        //Compute lastest synchronization date
        $query = "SELECT `last_update`\n                FROM `glpi_plugin_ocsinventoryng_snmpocslinks`\n                WHERE `ocs_id` = '{$ID}'";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                if ($DB->result($result, 0, 0) != '') {
                    $last_update = $DB->result($result, 0, 0);
                }
            }
        }
        if ($snmpids['META']['LASTDATE'] < $last_update) {
            if (($key = array_search($ID, $already_linked_ocs_ids)) !== false) {
                unset($already_linked_ocs_ids[$key]);
            }
        }
    }
    $already_linked_ids = array();
    //List definitive SNMP objects to update
    if (count($already_linked_ocs_ids) > 0) {
        $query = "SELECT `glpi_plugin_ocsinventoryng_snmpocslinks`.`id`\n                                  FROM `glpi_plugin_ocsinventoryng_snmpocslinks`\n                                  WHERE `ocs_id` IN (" . implode(",", $already_linked_ocs_ids) . ")";
        $result = $DB->query($query);
        if ($DB->numrows($result) > 0) {
            while ($data = $DB->fetch_assoc($result)) {
                $already_linked_ids[] = $data['id'];
            }
        }
    }
    $nb = count($already_linked_ids);
    echo "\tThread #{$threadid}: {$nb} object(s)\n";
    $fields["total_number_machines"] += $nb;
    //   $thread = new PluginOcsinventoryngThread();
    //   $notimport = new PluginOcsinventoryngNotimportedcomputer();
    //   $i = 0;
    foreach ($already_linked_ids as $ID) {
        /* TODO create thread & update it ?
            * if ($i == $config->fields["thread_log_frequency"]) {
              $fields["status"] = PLUGIN_OCSINVENTORYNG_STATE_RUNNING;
              $thread->update($fields);
              $i = 0;
           } else {
              $i++;
           }*/
        echo ".";
        $action = PluginOcsinventoryngSnmpOcslink::updateSnmp($ID, $ocsServerId);
        PluginOcsinventoryngOcsServer::manageImportStatistics($fields, $action['status']);
        /* TODO log it ?
              /*switch ($action['status']) {
                 case PluginOcsinventoryngOcsServer::SNMP_FAILED_IMPORT:
                    $notimport->logNotImported($ocsServerId, $ID, $action);
                    break;
        
                 default:
                    $notimport->cleanNotImported($ocsServerId, $ID);
                    //Log detail
                    $detail = new PluginOcsinventoryngDetail();
                    $detail->logProcessedComputer($ID, $ocsServerId, $action, $threadid, $threads_id);
                    break;
              }*/
    }
    return $fields;
}
 if ($count = count($_SESSION["ocs_importsnmp"]["id"])) {
     $percent = min(100, round(100 * ($_SESSION["ocs_importsnmp_count"] - $count) / $_SESSION["ocs_importsnmp_count"], 0));
     $key = array_pop($_SESSION["ocs_importsnmp"]["id"]);
     if (isset($_SESSION["ocs_importsnmp"]["entities_id"][$key])) {
         $params['entity'] = $_SESSION["ocs_importsnmp"]["entities_id"][$key];
     } else {
         $params['entity'] = -1;
     }
     if (isset($_SESSION["ocs_importsnmp"]["itemtype"][$key])) {
         $params['itemtype'] = $_SESSION["ocs_importsnmp"]["itemtype"][$key];
     } else {
         $params['itemtype'] = -1;
     }
     $conf = PluginOcsinventoryngOcsServer::getConfig($_SESSION["plugin_ocsinventoryng_ocsservers_id"]);
     $action = PluginOcsinventoryngSnmpOcslink::processSnmp($key, $_SESSION["plugin_ocsinventoryng_ocsservers_id"], 0, $params);
     PluginOcsinventoryngOcsServer::manageImportStatistics($_SESSION["ocs_importsnmp"]['statistics'], $action['status'], true);
     PluginOcsinventoryngOcsServer::showStatistics($_SESSION["ocs_importsnmp"]['statistics'], false, true);
     Html::displayProgressBar(400, $percent);
     Html::redirect($_SERVER['PHP_SELF']);
 } else {
     //displayProgressBar(400, 100);
     if (isset($_SESSION["ocs_importsnmp"]['statistics'])) {
         PluginOcsinventoryngOcsServer::showStatistics($_SESSION["ocs_importsnmp"]['statistics'], false, true);
     } else {
         echo "<div class='center b red'>";
         _e('No import: the plugin will not import these elements', 'ocsinventoryng');
         echo "</div>";
     }
     unset($_SESSION["ocs_importsnmp"]);
     echo "<div class='center b'><br>";
     echo "<a href='" . $_SERVER['PHP_SELF'] . "'>" . __('Back') . "</a></div>";