/**
  * @param $params array
  *
  * @return array
  * @return array
  */
 static function getOcsComputerInfos($params = array())
 {
     PluginOcsinventoryngOcsServer::checkOCSconnection($params['plugin_ocsinventoryng_ocsservers_id']);
     $ocsClient = PluginOcsinventoryngOcsServer::getDBocs($params['plugin_ocsinventoryng_ocsservers_id']);
     $options = array("DISPLAY" => array("CHECKSUM" => PluginOcsinventoryngOcsClient::CHECKSUM_BIOS));
     $computer = $ocsClient->getComputer($params['ocsid'], $options);
     $changes = array();
     if ($computer) {
         $ocs_serial = $computer["BIOS"]["SSN"];
         if ($ocs_serial != $params['serial']) {
             $ocsClient->updateBios($params['serial'], $params['ocsid']);
             $changes[] = 'serial';
         }
         $ocs_tag = $computer["META"]["TAG"];
         if ($ocs_tag != $params['tag']) {
             $ocsClient->updateBios($params['tag'], $params['ocsid']);
             $changes[] = 'tag';
         }
     }
     return $changes;
 }
Esempio n. 2
0
 static function OcsTableExists($ocs_server_id, $tablename)
 {
     $DBocs = PluginOcsinventoryngOcsServer::getDBocs($ocs_server_id)->getDB();
     // Get a list of tables contained within the database.
     $result = $DBocs->list_tables("%" . $tablename . "%");
     if ($rcount = $DBocs->numrows($result)) {
         while ($data = $DBocs->fetch_row($result)) {
             if ($data[0] === $tablename) {
                 return true;
             }
         }
     }
     $DBocs->free_result($result);
     return false;
 }
Esempio n. 3
0
 /**
  * @param CommonGLPI $item
  * @param int $withtemplate
  * @return array|string
  */
 function getTabNameForItem(CommonGLPI $item, $withtemplate = 0)
 {
     global $CFG_GLPI;
     switch ($item->getType()) {
         case __CLASS__:
             $ocsServers = getAllDatasFromTable('glpi_plugin_ocsinventoryng_ocsservers', "`is_active`='1'");
             if (!empty($ocsServers)) {
                 $ong[0] = __('Server Setup', 'ocsinventoryng');
                 $ong[1] = __('Inventory Import', 'ocsinventoryng');
                 $ong[2] = __('IPDiscover Import', 'ocsinventoryng');
                 if (isset($_POST["plugin_ocsinventoryng_ocsservers_id"])) {
                     $_SESSION["plugin_ocsinventoryng_ocsservers_id"] = $_POST["plugin_ocsinventoryng_ocsservers_id"];
                 } else {
                     $_SESSION["plugin_ocsinventoryng_ocsservers_id"] = PluginOcsinventoryngOcsServer::getFirstServer();
                 }
                 if (isset($_SESSION["plugin_ocsinventoryng_ocsservers_id"]) && $_SESSION["plugin_ocsinventoryng_ocsservers_id"] > 0) {
                     if (PluginOcsinventoryngOcsServer::checkOCSconnection($_SESSION["plugin_ocsinventoryng_ocsservers_id"])) {
                         $ocsClient = new PluginOcsinventoryngOcsServer();
                         $client = $ocsClient->getDBocs($_SESSION["plugin_ocsinventoryng_ocsservers_id"]);
                         $version = $client->getTextConfig('GUI_VERSION');
                         $snmp = $client->getIntConfig('SNMP');
                         if ($version > $ocsClient::OCS2_1_VERSION_LIMIT && $snmp) {
                             $ong[3] = __('SNMP Import', 'ocsinventoryng');
                         }
                     }
                 }
             } else {
                 $ong = array();
                 echo "<div align='center'>";
                 echo Html::image($CFG_GLPI["root_doc"] . "/pics/warning.png", array('alt' => __('Warning')));
                 echo "<br>";
                 echo "<div class='red b'>";
                 _e('No OCSNG server defined', 'ocsinventoryng');
                 echo "<br>";
                 _e('You must to configure a OCSNG server', 'ocsinventoryng');
                 echo " : <a href='" . $CFG_GLPI["root_doc"] . "/plugins/ocsinventoryng/front/ocsserver.form.php'>";
                 _e('Add a OCSNG server', 'ocsinventoryng');
                 echo "</a>";
                 echo "</div></div>";
             }
             return $ong;
         default:
             return '';
     }
 }
Esempio n. 4
0
         while ($data = $DB->fetch_array($result)) {
             $nbchk++;
             printf("%12d : %s\n", $data['id'], $data['ocs_deviceid']);
             if (isset($_GET['clean'])) {
                 $query2 = "DELETE\n                          FROM `glpi_plugin_ocsinventoryng_ocslinks`\n                          WHERE `id` = '" . $data['id'] . "'";
                 if ($DB->query($query2)) {
                     $nbdel++;
                 }
             } else {
                 $nbtodo++;
             }
         }
     }
 }
 if (isset($_GET['ocs'])) {
     $DBocs = PluginOcsinventoryngOcsServer::getDBocs($ocsservers_id);
     $res[] = $DBocs->getOCSComputers();
     $hardware = array();
     $nb = 0;
     $i = 0;
     if (count($res) > 0) {
         foreach ($res as $k => $data) {
             if (count($data) > 0) {
                 $i++;
                 $nb = count($data);
                 $data = Toolbox::clean_cross_side_scripting_deep(Toolbox::addslashes_deep($data));
                 $hardware[$data["ID"]] = $data["DEVICEID"];
                 echo "{$i}/{$nb}\r";
             }
         }
         echo "  {$nb} computers in OCS\n";
(at your option) any later version.

ocsinventoryng is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

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('OCSInventory NG', '', "tools", "pluginocsinventoryngmenu", "deleted_equiv");
echo "<div class='center'>";
$ocsClient = PluginOcsinventoryngOcsServer::getDBocs($_SESSION["plugin_ocsinventoryng_ocsservers_id"]);
if ($ocsClient->getConnectionType() == "PluginOcsinventoryngOcsSoapClient") {
    PluginOcsinventoryngOcsServer::manageDeleted($_SESSION["plugin_ocsinventoryng_ocsservers_id"]);
    if ($_SESSION["ocs_deleted_equiv"]['computers_to_del']) {
        echo "<div class='center b'>" . $_SESSION["ocs_deleted_equiv"]['computers_deleted'] . " " . __('Pc deleted', 'ocsinventoryng');
        Html::redirect($_SERVER['PHP_SELF']);
    } else {
        if ($_SESSION["ocs_deleted_equiv"]['computers_deleted'] === 0) {
            echo "<div class='center b'>" . __('No new computers to delete', 'ocsinventoryng') . ".</div>";
        } else {
            echo "<div class='center b'>";
            echo "<table class='tab_cadre_fixe'>";
            echo "<th colspan='2'>" . __('Clean OCSNG deleted computers', 'ocsinventoryng');
            echo "</th>";
            echo "<tr class='tab_bg_1'><td>" . __('Pc deleted', 'ocsinventoryng') . "</td><td>" . $_SESSION["ocs_deleted_equiv"]['computers_deleted'] . "</td></tr>";
            echo "</table></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)
{
    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 $ocsid
  * @param $plugin_ocsinventoryng_ocsservers_id
  * @param $params
  * @return array|bool
  * @internal param $computers_id
  *
  */
 static function linkSnmpDevice($ocsid, $plugin_ocsinventoryng_ocsservers_id, $params)
 {
     PluginOcsinventoryngOcsServer::checkOCSconnection($plugin_ocsinventoryng_ocsservers_id);
     $ocsClient = PluginOcsinventoryngOcsServer::getDBocs($plugin_ocsinventoryng_ocsservers_id);
     //TODOSNMP entites_id ?
     $p['itemtype'] = -1;
     $p['items_id'] = -1;
     foreach ($params as $key => $val) {
         $p[$key] = $val;
     }
     $ocs_id_change = true;
     /* $query = "SELECT *
             FROM `glpi_plugin_ocsinventoryng_snmpocslinks`
             WHERE `ocs_id` = '$ocs_id'";
     
             $result           = $DB->query($query);
             $ocs_id_change    = false;
             $ocs_link_exists  = false;
             $numrows          = $DB->numrows($result);
     
             // Already link - check if the OCS computer already exists
             if ($numrows > 0) {
             $ocs_link_exists = true;
             $data            = $DB->fetch_assoc($result);
     
             $ocsComputer = $ocsClient->getComputer($data['ocsid']);
     
             // Not found
             if (is_null($ocsComputer)) {
             $idlink = $data["id"];
             $query  = "UPDATE `glpi_plugin_ocsinventoryng_ocslinks`
             SET `ocsid` = '$ocsid'
             WHERE `id` = '" . $data["id"] . "'";
     
             if ($DB->query($query)) {
             $ocs_id_change = true;
             //Add history to indicates that the ocsid changed
             $changes[0] = '0';
             //Old ocsid
             $changes[1] = $data["ocsid"];
             //New ocsid
             $changes[2] = $ocsid;
             PluginOcsinventoryngOcslink::history($computers_id, $changes,
             PluginOcsinventoryngOcslink::HISTORY_OCS_IDCHANGED);
             }
             }
             }
     
             // No ocs_link or ocs id change does not exists so can link
             if ($ocs_id_change || !$ocs_link_exists) {
             $ocsConfig = PluginOcsinventoryngOcsServer::getConfig($plugin_ocsinventoryng_ocsservers_id);
             // Set OCS checksum to max value
             $ocsClient->setChecksum(PluginOcsinventoryngOcsClient::CHECKSUM_ALL, $ocsid);
            */
     if ($p['itemtype'] != -1 && $p['items_id'] > 0 && ($idlink = self::ocsSnmpLink($ocsid, $plugin_ocsinventoryng_ocsservers_id, $p['items_id'], $p['itemtype']))) {
         /*
          // automatic transfer computer
          if (($CFG_GLPI['transfers_id_auto'] > 0)
          && Session::isMultiEntitiesMode()) {
         
          // Retrieve data from glpi_plugin_ocsinventoryng_ocslinks
          $ocsLink = new PluginOcsinventoryngOcslink();
          $ocsLink->getFromDB($idlink);
         
          if (count($ocsLink->fields)) {
          // Retrieve datas from OCS database
          $ocsComputer = $ocsClient->getComputer($ocsLink->fields['ocsid']);
         
          if (!is_null($ocsComputer)) {
          $ocsComputer = Toolbox::addslashes_deep($ocsComputer);
          PluginOcsinventoryngOcsServer::transferComputer($ocsLink->fields, $ocsComputer);
          }
          }
          }
          $comp = new Computer();
          $comp->getFromDB($computers_id);
          $input["id"]            = $computers_id;
          $input["entities_id"]   = $comp->fields['entities_id'];
          $input["is_dynamic"]    = 1;
          $input["_nolock"]       = true;
         
          // Not already import from OCS / mark default state
          if ((!$ocs_id_change && ($ocsConfig["states_id_default"] > 0))
          || (!$comp->fields['is_dynamic']
          && ($ocsConfig["states_id_default"] > 0))) {
          $input["states_id"] = $ocsConfig["states_id_default"];
          }
          $comp->update($input);
          // Auto restore if deleted
          if ($comp->fields['is_deleted']) {
          $comp->restore(array('id' => $computers_id));
          }
         
          // Reset only if not in ocs id change case
          if (!$ocs_id_change) {
          if ($ocsConfig["import_general_os"]) {
          PluginOcsinventoryngOcsServer::resetDropdown($computers_id, "operatingsystems_id", "glpi_operatingsystems");
          }
          if ($ocsConfig["import_device_processor"]) {
          PluginOcsinventoryngOcsServer::resetDevices($computers_id, 'DeviceProcessor');
          }
          if ($ocsConfig["import_device_iface"]) {
          PluginOcsinventoryngOcsServer::resetDevices($computers_id, 'DeviceNetworkCard');
          }
          if ($ocsConfig["import_device_memory"]) {
          PluginOcsinventoryngOcsServer::resetDevices($computers_id, 'DeviceMemory');
          }
          if ($ocsConfig["import_device_hdd"]) {
          PluginOcsinventoryngOcsServer::resetDevices($computers_id, 'DeviceHardDrive');
          }
          if ($ocsConfig["import_device_sound"]) {
          PluginOcsinventoryngOcsServer::resetDevices($computers_id, 'DeviceSoundCard');
          }
          if ($ocsConfig["import_device_gfxcard"]) {
          PluginOcsinventoryngOcsServer::resetDevices($computers_id, 'DeviceGraphicCard');
          }
          if ($ocsConfig["import_device_drive"]) {
          PluginOcsinventoryngOcsServer::resetDevices($computers_id, 'DeviceDrive');
          }
          if ($ocsConfig["import_device_modem"] || $ocsConfig["import_device_port"]) {
          PluginOcsinventoryngOcsServer::resetDevices($computers_id, 'DevicePci');
          }
          if ($ocsConfig["import_device_bios"]) {
          PluginOcsinventoryngOcsServer::resetDevices($computers_id, 'PluginOcsinventoryngDeviceBiosdata');
          }
          if ($ocsConfig["import_device_motherboard"]) {
          PluginOcsinventoryngOcsServer::resetDevices($computers_id, 'DeviceMotherboard');
          }
          if ($ocsConfig["import_software"]) {
          PluginOcsinventoryngOcsServer::resetSoftwares($computers_id);
          }
          if ($ocsConfig["import_disk"]) {
          PluginOcsinventoryngOcsServer::resetDisks($computers_id);
          }
          if ($ocsConfig["import_periph"]) {
          PluginOcsinventoryngOcsServer::resetPeripherals($computers_id);
          }
          if ($ocsConfig["import_monitor"]==1) { // Only reset monitor as global in unit management
          PluginOcsinventoryngOcsServer::resetMonitors($computers_id);    // try to link monitor with existing
          }
          if ($ocsConfig["import_printer"]) {
          PluginOcsinventoryngOcsServer::resetPrinters($computers_id);
          }
          if ($ocsConfig["import_registry"]) {
          PluginOcsinventoryngOcsServer::resetRegistry($computers_id);
          }
          $changes[0] = '0';
          $changes[1] = "";
          $changes[2] = $ocsid;
          PluginOcsinventoryngOcslink::history($computers_id, $changes,
          PluginOcsinventoryngOcslink::HISTORY_OCS_LINK);
          }
         */
         self::updateSnmp($idlink, $plugin_ocsinventoryng_ocsservers_id);
         return array('status' => PluginOcsinventoryngOcsServer::SNMP_LINKED);
     }
     /*
             } else {
             //TRANS: %s is the OCS id
             Session::addMessageAfterRedirect(sprintf(__('Unable to import, GLPI computer is already related to an element of OCSNG (%d)',
             'ocsinventoryng'), $ocsid),
             false, ERROR);
             } */
     return false;
 }
Esempio n. 8
0
/**
 * @see inc/RuleCollection::prepareInputDataForProcess()
 * @since 0.84
 * @param $params           input data
 * @return an array of criteria value to add for processing
 **/
function plugin_ocsinventoryng_ruleCollectionPrepareInputDataForProcess($params)
{
    switch ($params['rule_itemtype']) {
        case 'RuleImportEntity':
        case 'RuleImportComputer':
            if ($params['rule_itemtype'] == 'RuleImportEntity') {
                $ocsservers_id = $params['values']['input']['ocsservers_id'];
            } else {
                $ocsservers_id = $params['values']['params']['plugin_ocsinventoryng_ocsservers_id'];
            }
            $rule_parameters = array('ocsservers_id' => $ocsservers_id, 'OCS_SERVER' => $ocsservers_id);
            if (isset($params['values']['params']['ocsid'])) {
                $ocsid = $params['values']['params']['ocsid'];
            } else {
                if ($params['values']['input']['id']) {
                    $ocsid = $params['values']['input']['id'];
                }
            }
            $ocsClient = PluginOcsinventoryngOcsServer::getDBocs($ocsservers_id);
            $tables = array_keys(plugin_ocsinventoryng_getTablesForQuery($params['rule_itemtype']));
            $fields = plugin_ocsinventoryng_getFieldsForQuery($params['rule_itemtype']);
            $ocsComputer = $ocsClient->getOcsComputer($ocsid, $tables);
            if (!is_null($ocsComputer)) {
                if (isset($ocsComputer['NETWORKS'])) {
                    $networks = $ocsComputer['NETWORKS'];
                    $ipblacklist = Blacklist::getIPs();
                    $macblacklist = Blacklist::getMACs();
                    foreach ($networks as $data) {
                        if (isset($data['IPSUBNET'])) {
                            $rule_parameters['IPSUBNET'][] = $data['IPSUBNET'];
                        }
                        if (isset($data['MACADDR']) && !in_array($data['MACADDR'], $macblacklist)) {
                            $rule_parameters['MACADDRESS'][] = $data['MACADDR'];
                        }
                        if (isset($data['IPADDRESS']) && !in_array($data['IPADDRESS'], $ipblacklist)) {
                            $rule_parameters['IPADDRESS'][] = $data['IPADDRESS'];
                        }
                    }
                }
                $ocs_data = array();
                foreach ($fields as $field) {
                    // TODO cleaner way of getting fields
                    $field = explode('.', $field);
                    if (count($field) < 2) {
                        continue;
                    }
                    $table = strtoupper($field[0]);
                    $fieldSql = explode(' ', $field[1]);
                    $ocsField = $fieldSql[0];
                    $glpiField = $fieldSql[count($fieldSql) - 1];
                    $section = array();
                    if (isset($ocsComputer[$table])) {
                        $section = $ocsComputer[$table];
                    }
                    if (array_key_exists($ocsField, $section)) {
                        // Not multi
                        $ocs_data[$glpiField][] = $section[$ocsField];
                    } else {
                        foreach ($section as $sectionLine) {
                            $ocs_data[$glpiField][] = $sectionLine[$ocsField];
                        }
                    }
                }
                //This case should never happend but...
                //Sometimes OCS can't find network ports but fill the right ip in hardware table...
                //So let's use the ip to proceed rules (if IP is a criteria of course)
                if (in_array("IPADDRESS", $fields) && !isset($ocs_data['IPADDRESS'])) {
                    $ocs_data['IPADDRESS'] = PluginOcsinventoryngOcsServer::getGeneralIpAddress($ocsservers_id, $ocsid);
                }
                return array_merge($rule_parameters, $ocs_data);
            }
    }
    return array();
}
/**
 * @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;
}
Esempio n. 10
0
 /**
  * Show OcsLink of an item
  *
  * @param $item                   CommonDBTM object
  * @return nothing
  * @internal param int|string $withtemplate integer  withtemplate param (default '')
  */
 static function showForItem(CommonDBTM $item)
 {
     global $DB;
     $target = Toolbox::getItemTypeFormURL(__CLASS__);
     if (in_array($item->getType(), array('Computer'))) {
         $items_id = $item->getField('id');
         if (!empty($items_id) && $item->fields["is_dynamic"] && Session::haveRight("plugin_ocsinventoryng_view", READ)) {
             $query = "SELECT *\n                      FROM `glpi_plugin_ocsinventoryng_ocslinks`\n                      WHERE `computers_id` = '{$items_id}' " . getEntitiesRestrictRequest("AND", "glpi_plugin_ocsinventoryng_ocslinks");
             $result = $DB->query($query);
             if ($DB->numrows($result) > 0) {
                 $data = $DB->fetch_assoc($result);
                 $data = Toolbox::clean_cross_side_scripting_deep(Toolbox::addslashes_deep($data));
                 if (count($data)) {
                     echo "<div class='center'>";
                     echo "<form method='post' action=\"{$target}\">";
                     echo "<input type='hidden' name='id' value='{$items_id}'>";
                     echo "<table class='tab_cadre_fixe'>";
                     echo "<tr><th colspan = '4'>" . __('OCSNG link', 'ocsinventoryng') . "</th>";
                     echo "<tr class='tab_bg_1'>";
                     echo "<td class='left'>";
                     _e('OCSNG DEVICE ID', 'ocsinventoryng');
                     echo "</td>";
                     echo "<td class='left'>";
                     echo $data['ocs_deviceid'];
                     echo "</td>";
                     echo "<td class='left'>";
                     _e('OCSNG TAG', 'ocsinventoryng');
                     echo "</td>";
                     echo "<td class='left'>";
                     echo $data['tag'];
                     echo "</td>";
                     echo "<tr class='tab_bg_1'>";
                     echo "<td class='left'>" . __('Automatic update OCSNG', 'ocsinventoryng') . "</td>";
                     echo "<td class='left'>";
                     Dropdown::showYesNo("use_auto_update", $data["use_auto_update"]);
                     echo "</td>";
                     echo "<td class='left'>";
                     _e('Uptime', 'ocsinventoryng');
                     echo "</td>";
                     echo "<td class='left'>";
                     echo $data['uptime'];
                     echo "</td>";
                     echo "</tr>";
                     if (Session::haveRight("plugin_ocsinventoryng_sync", UPDATE)) {
                         echo "<tr class='tab_bg_1'>";
                         echo "<td class='center'>";
                         echo "<input type='hidden' name='link_id' value='" . $data["id"] . "'>";
                         echo "<input class=submit type='submit' name='update' value=\"" . _sx('button', 'Save') . "\">";
                         echo "</td>";
                         echo "<td class='center'>";
                         echo "<input type='hidden' name='resynch_id' value='" . $data["id"] . "'>";
                         echo "<input class=submit type='submit' name='force_ocs_resynch' value=\"" . _sx('button', 'Force synchronization', 'ocsinventoryng') . "\">";
                         echo "</td>";
                         echo "<td class='center'>";
                         echo "<input type='hidden' name='items_id' value='" . $items_id . "'>";
                         echo "<input class=submit type='submit' name='delete_link' value=\"" . _sx('button', 'Delete link', 'ocsinventoryng') . "\">";
                         echo "</td>";
                         echo "<td>";
                         echo "</td>";
                         echo "</tr>";
                     }
                     echo "</table>\n";
                     Html::closeForm();
                     echo "</div>";
                     if ($_SESSION['glpi_use_mode'] == Session::DEBUG_MODE) {
                         $ocsClient = PluginOcsinventoryngOcsServer::getDBocs($data["plugin_ocsinventoryng_ocsservers_id"]);
                         $options = array('DISPLAY' => array('CHECKSUM' => PluginOcsinventoryngOcsClient::CHECKSUM_HARDWARE, 'PLUGINS' => PluginOcsinventoryngOcsClient::PLUGINS_NONE), 'COMPLETE' => 0);
                         $computer = array();
                         $checksum_client = 0;
                         $computer = $ocsClient->getComputer($data["ocsid"], $options);
                         echo "<br><table class='tab_cadre_fixe'>";
                         echo "<tr>";
                         echo "<th colspan='2'>" . __('DEBUG') . " " . __('OCSNG', "ocsinventoryng") . "</th>";
                         echo "</tr>";
                         if (count($computer) > 0) {
                             foreach ($computer as $key => $val) {
                                 echo "<tr class='tab_bg_1'>";
                                 echo "<td>";
                                 print_r($key);
                                 echo "</td>";
                                 echo "<td>";
                                 foreach ($val as $name => $value) {
                                     if (is_array($value)) {
                                         echo "<table class='tab_cadre' width='100%' border='0'>";
                                         foreach ($value as $k => $v) {
                                             echo "<tr class='tab_bg_1'>";
                                             echo "<td>";
                                             printf(__('%1$s: %2$s'), $k, $v);
                                             echo "</td>";
                                             echo "</tr>";
                                         }
                                         echo "</table>";
                                     } else {
                                         printf(__('%1$s: %2$s'), $name, $value);
                                     }
                                     if ($name == "CHECKSUM") {
                                         $checksum_client = intval($value);
                                     }
                                     echo "</br>";
                                 }
                                 echo "</td>";
                                 echo "</tr>";
                             }
                         } else {
                             echo "<tr class='tab_bg_1'>";
                             echo "<td colspan='2' class='red'>";
                             _e('No computer found into OCSNG Database', 'ocsinventoryng');
                             echo "</td>";
                             echo "</tr>";
                         }
                         $server = new PluginOcsinventoryngOcsServer();
                         if ($server->getFromDB($data["plugin_ocsinventoryng_ocsservers_id"]) && $checksum_client > 0) {
                             echo "<tr class='tab_bg_1'>";
                             echo "<td>";
                             _e('Checksum test', 'ocsinventoryng');
                             echo "</td>";
                             echo "<td>";
                             $format = '(%1$2d = %1$04b) = (%2$2d = %2$04b)' . ' %3$s (%4$2d = %4$04b)' . "\n";
                             $checksum_server = intval($server->fields["checksum"]);
                             $result = $checksum_server & $checksum_client;
                             printf($format, $result, $checksum_server, '&', $checksum_client);
                             echo "</td>";
                             echo "</tr>";
                         }
                         echo "</table>";
                     }
                 } else {
                     echo "<div class='center'>";
                     echo "<table class='tab_cadre_fixe'>";
                     echo "<tr><th colspan = '2'>" . __('OCSNG link', 'ocsinventoryng') . "</th>";
                     echo "<tr class='tab_bg_1'>";
                     echo "<td colspan='2' >";
                     _e('No computer found into OCSNG Database', 'ocsinventoryng');
                     echo "</td>";
                     echo "</tr>";
                     echo "</table>";
                     echo "</div>";
                 }
             } else {
                 echo "<div class='center'>";
                 echo "<table class='tab_cadre_fixe'>";
                 echo "<tr><th colspan = '2'>" . __('OCSNG link', 'ocsinventoryng') . "</th>";
                 echo "<tr class='tab_bg_1'>";
                 echo "<td colspan='2' '>";
                 _e('No computer found into OCSNG Database', 'ocsinventoryng');
                 echo "</td>";
                 echo "</tr>";
                 echo "</table>";
                 echo "</div>";
             }
         } else {
             echo "<div class='center'>";
             echo "<table class='tab_cadre_fixe'>";
             echo "<tr><th colspan = '2'>" . __('OCSNG link', 'ocsinventoryng') . "</th>";
             echo "<tr class='tab_bg_1'>";
             echo "<td colspan='2' '>";
             _e('No computer found into OCSNG Database', 'ocsinventoryng');
             echo "</td>";
             echo "</tr>";
             echo "</table>";
             echo "</div>";
         }
     }
 }
 /**
  * link ipdiscover object
  * @param type $plugin_ocsinventoryng_ocsservers_id integer
  * @param $itemtypes
  * @param $items_id
  * @param $macAdresses
  * @param $ocsItemstypes
  * @param $itemsDescription
  * @param $subnet
  * @param int $identify
  * @return type array
  * @internal param type $ipDiscoveryObject array
  */
 static function linkIpDiscover($plugin_ocsinventoryng_ocsservers_id, $itemtypes, $items_id, $macAdresses, $ocsItemstypes, $itemsDescription, $subnet, $identify = 0)
 {
     global $DB;
     /*$id         = null;
           $identify   = false;
           
           if (isset($ipDiscoveryObject["ocsItemType"]) 
                 && $ipDiscoveryObject["ocsItemType"] == Dropdown::EMPTY_VALUE) {
              return array('status' => PluginOcsinventoryngOcsServer::IPDISCOVER_FAILED_IMPORT);
           }
           if ($ipDiscoveryObject["itemDescription"] == '') {
              return array('status' => PluginOcsinventoryngOcsServer::IPDISCOVER_FAILED_IMPORT);
           }
     
           if ($ipDiscoveryObject["itemName"] == "") {
              $ipDiscoveryObject["itemName"] = $ipDiscoveryObject["itemDescription"];
           }
     
           switch ($ipDiscoveryObject["glpiItemType"]) {
              //empty dropdown value
              case '0' :
                 return array('status' => PluginOcsinventoryngOcsServer::IPDISCOVER_FAILED_IMPORT);
           }
     
           if (isset($ipDiscoveryObject["ocsItemType"])) {
              $identify = true;
           }*/
     //ipdiscover link
     $objs = array();
     $macs = self::getMacAdressKeyVal($macAdresses);
     foreach ($itemtypes as $key => $type) {
         $objs[$items_id[$key]] = array("itemtype" => $type, "mac" => $macs[$key], "description" => isset($itemsDescription[$key]) ? $itemsDescription[$key] : 0, "ocsType" => isset($ocsItemstypes[$key]) ? $ocsItemstypes[$key] : 0);
     }
     foreach ($objs as $id => $tab) {
         $date = date("Y-m-d H:i:s");
         $glpiQuery = "INSERT INTO `glpi_plugin_ocsinventoryng_ipdiscoverocslinks`\n                       (`items_id`,`itemtype`,`macaddress`,`last_update`,`subnet`,`plugin_ocsinventoryng_ocsservers_id`)\n                       VALUES('{$id}','" . $tab["itemtype"] . "','" . $tab["mac"] . "','{$date}','{$subnet}','{$plugin_ocsinventoryng_ocsservers_id}')";
         $DB->query($glpiQuery);
         $input = array('is_dynamic' => 1, 'id' => $id);
         $device = new $tab["itemtype"]();
         $device->update($input);
         if ($identify) {
             //identify object
             //WAS IS DAS ? CHMA
             $userId = Session::getLoginUserID();
             $query = "SELECT `glpi_users`.`name` \n                         FROM `glpi_users`\n                         WHERE glpi_users.id like '{$userId}'";
             $queryResult = $DB->query($query);
             $userAssoc = $DB->fetch_assoc($queryResult);
             if ($userAssoc) {
                 $ocsClient = new PluginOcsinventoryngOcsServer();
                 $DBOCS = $ocsClient->getDBocs($plugin_ocsinventoryng_ocsservers_id)->getDB();
                 $ocsType = $tab["ocsType"];
                 $description = $tab["description"];
                 $user = $userAssoc["name"];
                 $ocsQuery = "INSERT INTO `network_devices` (`description`,`type`,`macaddr`,`user`)\n                            VALUES('{$description}','{$ocsType}','" . $tab["mac"] . "','{$user}')";
                 $DBOCS->query($ocsQuery);
             }
         }
     }
     /*if ($id) {
          return array('status' => PluginOcsinventoryngOcsServer::IPDISCOVER_IMPORTED);
       } else {
          Session::addMessageAfterRedirect($mac." : ".__('Unable to add. an object with same MAC address already exists.', 'ocsinventoryng'), false, ERROR);
          return array('status' => PluginOcsinventoryngOcsServer::IPDISCOVER_FAILED_IMPORT);
       }*/
 }