/**
  * @param $computers_id
  * @param $date
  * @param $computer_updates
  * @return array
  */
 static function addInfocomsForComputer($computers_id, $date, $computer_updates)
 {
     global $DB;
     $infocom = new Infocom();
     $use_date = substr($date, 0, 10);
     if ($infocom->getFromDBByQuery("WHERE `items_id` = {$computers_id} AND `itemtype` = 'Computer'")) {
         if (empty($infocom->fields['use_date']) || $infocom->fields['use_date'] == 'NULL') {
             //add use_date
             $infocom->update(array('id' => $infocom->fields['id'], 'use_date' => $use_date));
         }
     } else {
         //add infocom
         $infocom->add(array('items_id' => $computers_id, 'itemtype' => 'Computer', 'use_date' => $use_date));
     }
     //Add lock
     $ocslink = new PluginOcsinventoryngOcslink();
     if ($ocslink->getFromDBforComputer($computers_id)) {
         $cfg_ocs = PluginOcsinventoryngOcsServer::getConfig($ocslink->fields["plugin_ocsinventoryng_ocsservers_id"]);
         if ($cfg_ocs["use_locks"]) {
             $computer_updates[] = "use_date";
             $query = "UPDATE `glpi_plugin_ocsinventoryng_ocslinks`\n                         SET `computer_update` = '" . addslashes(exportArrayToDB($computer_updates)) . "'\n                         WHERE `computers_id` = '{$computers_id}'";
             $DB->query($query);
         }
     }
     return $computer_updates;
 }
Beispiel #2
0
 /**
  * Constructor
  *
  * @param $ID ID of the ocs server ID
  **/
 function __construct($ID)
 {
     $this->ocsservers_id = $ID;
     $data = PluginOcsinventoryngOcsServer::getConfig($ID);
     $this->dbhost = $data["ocs_db_host"];
     $this->dbuser = $data["ocs_db_user"];
     $this->dbpassword = rawurldecode($data["ocs_db_passwd"]);
     $this->dbdefault = $data["ocs_db_name"];
     $this->dbenc = $data["ocs_db_utf8"] ? "utf8" : "latin1";
     parent::__construct();
 }
Beispiel #3
0
 static function showMenu()
 {
     global $CFG_GLPI;
     echo "<table class='tab_cadre_fixe'>";
     echo "<tr><th>" . __('Configuration') . "</th></tr>";
     echo "<tr class='tab_bg_1'><td class='center b'>";
     echo "<a href='" . $CFG_GLPI['root_doc'] . "/plugins/ocsinventoryng/front/ocsserver.php'>" . _n('OCSNG server', 'OCSNG servers', 2, 'ocsinventoryng') . "</a>";
     echo "</td></tr>";
     if (PluginOcsinventoryngOcsServer::useMassImport()) {
         echo "<tr class='tab_bg_1'><td class='center b'>";
         echo "<a href='" . $CFG_GLPI['root_doc'] . "/plugins/ocsinventoryng/front/config.form.php'>" . __("Automatic synchronization's configuration", 'ocsinventoryng') . "</a>";
         echo "</td></tr>";
     }
     echo "</table>";
 }
Beispiel #4
0
        PluginOcsinventoryngOcsServer::linkComputer($key["ocsid"], $_SESSION["plugin_ocsinventoryng_ocsservers_id"], $key["computers_id"]);
        Html::redirect($_SERVER['PHP_SELF']);
    } else {
        Html::displayProgressBar(400, 100);
        unset($_SESSION["ocs_link"]);
        echo "<div class='center b'>" . __('Successful importation') . "<br>";
        echo "<a href='" . $_SERVER['PHP_SELF'] . "'>" . __('Back') . "</a></div>";
    }
}
if (!isset($_POST["import_ok"])) {
    if (!isset($_GET['check'])) {
        $_GET['check'] = 'all';
    }
    if (!isset($_GET['start'])) {
        $_GET['start'] = 0;
    }
    PluginOcsinventoryngOcsServer::manageDeleted($_SESSION["plugin_ocsinventoryng_ocsservers_id"]);
    PluginOcsinventoryngOcsServer::showComputersToAdd($_SESSION["plugin_ocsinventoryng_ocsservers_id"], $_SESSION["change_import_mode"], $_GET['check'], $_GET['start'], $_SESSION['glpiactiveentities'], 1);
} else {
    if (isset($_POST['tolink']) && count($_POST['tolink']) > 0) {
        $_SESSION["ocs_link_count"] = 0;
        foreach ($_POST['tolink'] as $ocsid => $computers_id) {
            if ($computers_id > 0) {
                $_SESSION["ocs_link"][] = array('ocsid' => $ocsid, 'computers_id' => $computers_id);
                $_SESSION["ocs_link_count"]++;
            }
        }
    }
    Html::redirect($_SERVER['PHP_SELF']);
}
Html::footer();
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("computer", READ);
if (isset($_POST["force_ocs_resynch"])) {
    $computer = new Computer();
    $computer->check($_POST['id'], UPDATE);
    //Get the ocs server id associated with the machine
    $ocsservers_id = PluginOcsinventoryngOcsServer::getByMachineID($_POST["id"]);
    //Update the computer
    $cfg_ocs = PluginOcsinventoryngOcsServer::getConfig($ocsservers_id);
    $dohistory = isset($cfg_ocs['dohistory']) ? $cfg_ocs['dohistory'] : false;
    PluginOcsinventoryngOcsServer::updateComputer($_POST["resynch_id"], $ocsservers_id, $dohistory, 1);
    Html::back();
} else {
    if (isset($_POST["update"])) {
        $link = new PluginOcsinventoryngOcslink();
        $values["id"] = $_POST["link_id"];
        $values["use_auto_update"] = $_POST["use_auto_update"];
        $link->update($values);
        Html::back();
    } else {
        if (isset($_POST["delete_link"])) {
            $comp = new Computer();
            $link = new PluginOcsinventoryngOcslink();
            if ($comp->getFromDB($_POST["items_id"])) {
                $link->purgeComputer($comp);
                Html::back();
Beispiel #6
0
 /**
  * @param $target
  **/
 function showProcesses($target)
 {
     global $DB, $CFG_GLPI;
     $canedit = Session::haveRight("plugin_ocsinventoryng", UPDATE);
     $config = new PluginOcsinventoryngConfig();
     $config->getFromDB(1);
     $minfreq = 9999;
     //$task    = new CronTask();
     //if ($task->getFromDBbyName('PluginOcsinventoryngThread', 'CleanOldThreads')) {
     //First of all, deleted old processes
     //   $this->deleteOldProcesses($task->fields['param']);
     //   if ($task->fields['param'] > 0) {
     //      $minfreq=$task->fields['param'];
     //   }
     //}
     $imported_number = new PluginOcsinventoryngMiniStat();
     $synchronized_number = new PluginOcsinventoryngMiniStat();
     $linked_number = new PluginOcsinventoryngMiniStat();
     $failed_number = new PluginOcsinventoryngMiniStat();
     $notupdated_number = new PluginOcsinventoryngMiniStat();
     $notunique_number = new PluginOcsinventoryngMiniStat();
     $linkedrefused_number = new PluginOcsinventoryngMiniStat();
     $process_time = new PluginOcsinventoryngMiniStat();
     $sql = "SELECT `id`, `processid`, SUM(`total_number_machines`) AS total_machines,\n                     `plugin_ocsinventoryng_ocsservers_id`, `status`, COUNT(*) AS threads_number,\n                     MIN(`start_time`) AS starting_date, MAX(`end_time`) AS ending_date,\n                     TIME_TO_SEC(MAX(`end_time`)) - TIME_TO_SEC(MIN(`start_time`)) AS duree,\n                     SUM(`imported_machines_number`) AS imported_machines,\n                     SUM(`synchronized_machines_number`) AS synchronized_machines,\n                     SUM(`linked_machines_number`) AS linked_machines,\n                     SUM(`failed_rules_machines_number`) AS failed_rules_machines,\n                     SUM(`notupdated_machines_number`) AS notupdated_machines,\n                     SUM(`not_unique_machines_number`) AS not_unique_machines_number,\n                     SUM(`link_refused_machines_number`) AS link_refused_machines_number,\n                     `end_time` >= DATE_ADD(NOW(), INTERVAL - " . $minfreq . " HOUR) AS DoStat\n              FROM `" . $this->getTable() . "`\n              GROUP BY `processid`\n              ORDER BY `id` DESC\n              LIMIT 50";
     $result = $DB->query($sql);
     echo "<div class='center'>";
     echo "<form name='processes' id='processes' action='{$target}' method='post'>";
     echo "<table class='tab_cadrehov'>";
     echo "<tr><th colspan='16'>" . __('Processes execution of automatic actions', 'ocsinventoryng') . "</th></tr>";
     echo "<tr>";
     echo "<th>&nbsp;</th>";
     echo "<th>&nbsp;</th>";
     echo "<th>" . __('Status') . "</th>";
     echo "<th>" . __('Number of threads', 'ocsinventoryng') . "</th>";
     echo "<th>" . __('Beginning date of execution', 'ocsinventoryng') . "</th>";
     echo "<th>" . __('Ending date of execution', 'ocsinventoryng') . "</th>";
     echo "<th>" . __('Computers imported by automatic actions', 'ocsinventoryng') . "</th>";
     echo "<th>" . __('Computers synchronized', 'ocsinventoryng') . "</th>";
     echo "<th>" . __('Computers linked', 'ocsinventoryng') . "</th>";
     echo "<th>" . __('Computers not imported by automatic actions', 'ocsinventoryng') . "</th>";
     echo "<th>" . __('Computers not updated', 'ocsinventoryng') . "</th>";
     echo "<th>" . __('Computers not unique', 'ocsinventoryng') . "</th>";
     echo "<th>" . __('Computers refused', 'ocsinventoryng') . "</th>";
     echo "<th>" . __('Process time execution', 'ocsinventoryng') . "</th>";
     echo "<th>" . __('Server') . "</th>";
     echo "<th>&nbsp;</th>";
     echo "</th></tr>\n";
     if ($DB->numrows($result)) {
         while ($thread = $DB->fetch_array($result)) {
             if ($config->fields["is_displayempty"] || $thread["status"] != PLUGIN_OCSINVENTORYNG_STATE_FINISHED || !$config->fields["is_displayempty"] && $thread["total_machines"] > 0 && $thread["status"] == PLUGIN_OCSINVENTORYNG_STATE_FINISHED) {
                 if ($thread["DoStat"] && $thread["status"] == PLUGIN_OCSINVENTORYNG_STATE_FINISHED) {
                     $imported_number->AddValue($thread["imported_machines"]);
                     $synchronized_number->AddValue($thread["synchronized_machines"]);
                     $linked_number->AddValue($thread["linked_machines"]);
                     $failed_number->AddValue($thread["failed_rules_machines"]);
                     $notupdated_number->AddValue($thread["notupdated_machines"]);
                     $notunique_number->AddValue($thread["not_unique_machines_number"]);
                     $linkedrefused_number->AddValue($thread["link_refused_machines_number"]);
                     $process_time->AddValue($thread["duree"]);
                 } else {
                     if ($imported_number->GetCount() > 0) {
                         $this->showshowStat($minfreq, $imported_number, $synchronized_number, $linked_number, $failed_number, $notupdated_number, $notunique_number, $linkedrefused_number, $process_time);
                         $imported_number->Reset();
                     }
                 }
                 echo "<tr class='tab_bg_1'>";
                 echo "<td width='10'>";
                 if ($canedit) {
                     echo "<input type='checkbox' name='item[" . $thread["processid"] . "]' value='1'>";
                 } else {
                     echo "&nbsp;";
                 }
                 echo "</td>";
                 echo "<td class='center'>";
                 echo "<a href=\"./thread.form.php?pid=" . $thread["processid"] . "\">" . $thread["processid"] . "</a></td>";
                 echo "<td class='center'>";
                 $this->displayProcessStatusIcon($this->getProcessStatus($thread["processid"]));
                 echo "</td>";
                 echo "<td class='center'>" . $thread["threads_number"] . "</td>";
                 echo "<td class='center'>" . Html::convDateTime($thread["starting_date"]) . "</td>";
                 echo "<td class='center'>" . Html::convDateTime($thread["ending_date"]) . "</td>";
                 echo "<td class='center'>" . $thread["imported_machines"] . "</td>";
                 echo "<td class='center'>" . $thread["synchronized_machines"] . "</td>";
                 echo "<td class='center'>" . $thread["linked_machines"] . "</td>";
                 echo "<td class='center'>" . $thread["failed_rules_machines"] . "</td>";
                 echo "<td class='center'>" . $thread["notupdated_machines"] . "</td>";
                 echo "<td class='center'>" . $thread["not_unique_machines_number"] . "</td>";
                 echo "<td class='center'>" . $thread["link_refused_machines_number"] . "</td>";
                 echo "<td class='center'>";
                 if ($thread["status"] == PLUGIN_OCSINVENTORYNG_STATE_FINISHED) {
                     echo Html::timestampToString($thread["duree"]);
                 } else {
                     echo Dropdown::EMPTY_VALUE;
                 }
                 echo "</td>";
                 echo "<td class='center'>";
                 if ($thread["plugin_ocsinventoryng_ocsservers_id"] != -1) {
                     $ocsConfig = PluginOcsinventoryngOcsServer::getConfig($thread["plugin_ocsinventoryng_ocsservers_id"]);
                     echo "<a href=\"ocsserver.form.php?id=" . $ocsConfig["id"] . "\">" . $ocsConfig["name"] . "</a>";
                 } else {
                     _e('All servers', 'ocsinventoryng');
                 }
                 echo "</td>";
                 echo "<td class='center'>";
                 echo "<a href=\"detail.php?reset=reset_before&field[0]=" . "5&contains[0]=^" . $thread["processid"] . '$">' . "<img  src='" . $CFG_GLPI["root_doc"] . "/pics/rdv.png'</a></td>";
                 echo "</tr>\n";
             }
         }
     }
     if ($imported_number->GetCount() > 0) {
         $this->showshowStat($minfreq, $imported_number, $synchronized_number, $linked_number, $failed_number, $notupdated_number, $notunique_number, $linkedrefused_number, $process_time);
     }
     echo "</table>";
     if ($canedit) {
         Html::openArrowMassives("processes");
         Html::closeArrowMassives(array("delete_processes" => _x('button', 'Delete permanently')));
     }
     Html::closeForm();
 }
Beispiel #7
0
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

Ocsinventoryng plugin 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::checkSeveralRightsOr(array("plugin_ocsinventoryng" => READ, "plugin_ocsinventoryng_clean" => READ));
Html::header('OCS Inventory NG', '', "tools", "pluginocsinventoryngmenu", "ocsinventoryng");
if (isset($_SESSION["ocs_import"])) {
    unset($_SESSION["ocs_import"]);
}
if (isset($_SESSION["ocs_link"])) {
    unset($_SESSION["ocs_link"]);
}
if (isset($_SESSION["ocs_update"])) {
    unset($_SESSION["ocs_update"]);
}
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();
}
PluginOcsinventoryngOcsServer::ocsMenu($_SESSION["plugin_ocsinventoryng_ocsservers_id"]);
PluginOcsinventoryngOcsServer::checkOCSconnection($_SESSION["plugin_ocsinventoryng_ocsservers_id"]);
Html::footer();
         $_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];
             $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"])) {
Beispiel #9
0
--------------------------------------------------------------------------
*/
include '../../../inc/includes.php';
Session::checkSeveralRightsOr(array("plugin_ocsinventoryng" => READ, "plugin_ocsinventoryng_clean" => READ));
Html::header('OCS Inventory NG', '', "tools", "pluginocsinventoryngmenu", "ocsinventoryng");
if (isset($_SESSION["ocs_import"])) {
    unset($_SESSION["ocs_import"]);
}
if (isset($_SESSION["ocs_link"])) {
    unset($_SESSION["ocs_link"]);
}
if (isset($_SESSION["ocs_update"])) {
    unset($_SESSION["ocs_update"]);
}
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();
}
//PluginOcsinventoryngOcsServer::newOcsMenu($_SESSION["plugin_ocsinventoryng_ocsservers_id"]);
$menu = new PluginOcsinventoryngMenu();
$menu->show();
//load mac constructors in sessionMemory
$_SESSION["OCS"]["count"] = 0;
if (!isset($_SESSION["OCS"]["IpdiscoverMacConstructors"])) {
    $ip = new PluginOcsinventoryngIpdiscoverOcslink();
    $ip->loadMacConstructor();
    $_SESSION["OCS"]["count"] = $_SESSION["OCS"]["count"] + 1;
}
//PluginOcsinventoryngOcsServer::ocsMenu($_SESSION["plugin_ocsinventoryng_ocsservers_id"]);
Html::footer();
Beispiel #10
0
/**
 *
 * Unlock fields managed by the plugin
 * @since 1.0
 * @param $_POST array
 */
function plugin_ocsinventoryng_unlockFields($params = array())
{
    $computer = new Computer();
    $computer->check($_POST['id'], 'w');
    if (isset($_POST["lockfield"]) && count($_POST["lockfield"])) {
        foreach ($_POST["lockfield"] as $key => $val) {
            PluginOcsinventoryngOcsServer::deleteInOcsArray($_POST["id"], $key, "computer_update");
        }
    }
}
 /**
  * @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;
 }
Beispiel #12
0
echo "Last new computer : " . $data["DEVICEID"] . " ({$maxid}, {$maxti})\n";
if (!$maxid) {
    die("Bad value\n");
}
// Computer from OCS : New, ID Changed, Linked
$sql = "SELECT *\n        FROM `glpi_logs`\n        WHERE `date_mod` >= '{$maxti}'\n              AND `itemtype` = 1\n              AND `linked_action` IN (8,10,11)\n        ORDER BY `id` DESC";
$res = $DB->query($sql);
if (!$res) {
    die("No data from GLPI\n");
}
$comp = new Computer();
echo "Start\n";
$tabres = array();
$nb = $nbupd = 0;
while ($event = $DB->fetch_array($res)) {
    if ($event["new_value"] > $maxid && PluginOcsinventoryngOcsServer::getByMachineID($event["items_id"]) == $_GET["server"] && $comp->getFromDB($event["items_id"])) {
        $nb++;
        printf("+ %5d : %s : %s (%s > %s)\n", $nb, $event["date_mod"], $comp->fields["name"], $event["old_value"], $event["new_value"]);
        if (!isset($tabres[$comp->fields["entities_id"]])) {
            $tabres[$comp->fields["entities_id"]] = array();
        }
        if ($event["linked_action"] == 10) {
            // ID Changed
            $tabres[$comp->fields["entities_id"]][] = "ID:" . $comp->fields["id"] . " - " . $comp->fields["name"] . " (" . $comp->fields["serial"] . ") => rollback lien";
            // Search the old Device_ID in OCS
            $sql = "SELECT `DEVICEID`\n                 FROM `hardware`\n                 WHERE `ID` = '" . $event["old_value"] . "'";
            $resocs = $DBocs->query($sql);
            $olddevid = "";
            if ($hard = $DBocs->fetch_array($resocs)) {
                $olddevid = $hard["DEVICEID"];
            }
Beispiel #13
0
/**
 * @param $item
 */
function plugin_ocsinventoryng_item_update($item)
{
    global $DB;
    if ($item->fields['itemtype'] == "Computer") {
        if (in_array('use_date', $item->updates)) {
            $query = "SELECT *\r\n                   FROM `glpi_plugin_ocsinventoryng_ocslinks`\r\n                   WHERE `computers_id` = '" . $item->fields['items_id'] . "'";
            $result = $DB->query($query);
            if ($DB->numrows($result) == 1) {
                $line = $DB->fetch_assoc($result);
                $cfg_ocs = PluginOcsinventoryngOcsServer::getConfig($line["plugin_ocsinventoryng_ocsservers_id"]);
                if ($cfg_ocs["use_locks"]) {
                    $computer_updates = importArrayFromDB($line["computer_update"]);
                    //Add lock
                    $computer_updates[] = "use_date";
                    $query = "UPDATE `glpi_plugin_ocsinventoryng_ocslinks`\r\n                            SET `computer_update` = '" . addslashes(exportArrayToDB($computer_updates)) . "'\r\n                            WHERE `computers_id` = '" . $item->fields['items_id'] . "'";
                    $DB->query($query);
                }
            }
        }
    }
}
 /**
  * @param $params array
  **/
 static function getOcsComputerInfos($params = array())
 {
     global $PluginOcsinventoryngDBocs;
     PluginOcsinventoryngOcsServer::checkOCSconnection($params['plugin_ocsinventoryng_ocsservers_id']);
     $changes = array();
     $query = "SELECT `SSN` FROM `bios`\n                  WHERE `HARDWARE_ID` = '" . $params['ocsid'] . "'";
     $result = $PluginOcsinventoryngDBocs->query($query);
     if ($PluginOcsinventoryngDBocs->numrows($result) > 0) {
         $ocs_serial = $PluginOcsinventoryngDBocs->result($result, 0, 'SSN');
         if ($ocs_serial != $params['serial']) {
             $query_serial = "UPDATE `bios`\n                             SET `SSN` = '" . $params['serial'] . "'" . "          WHERE `HARDWARE_ID` = '" . $params['ocsid'] . "'";
             $PluginOcsinventoryngDBocs->query($query_serial);
             $changes[] = 'serial';
         }
     }
     $query = "SELECT `TAG`\n                FROM `accountinfo`\n                WHERE `HARDWARE_ID` = '" . $params['ocsid'] . "'";
     $result = $PluginOcsinventoryngDBocs->query($query);
     if ($PluginOcsinventoryngDBocs->numrows($result) > 0) {
         $ocs_tag = $PluginOcsinventoryngDBocs->result($result, 0, 'TAG');
         if ($ocs_tag != $params['tag']) {
             $query_serial = "UPDATE `accountinfo`\n                             SET `TAG` = '" . $params['tag'] . "'\n                            WHERE `HARDWARE_ID` = '" . $params['ocsid'] . "'";
             $PluginOcsinventoryngDBocs->query($query_serial);
             $changes[] = 'tag';
         }
     }
     return $changes;
 }
/**
 * @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;
}
Beispiel #16
0
 static function showOcsReportsConsole($id)
 {
     $ocsconfig = PluginOcsinventoryngOcsServer::getConfig($id);
     echo "<div class='center'>";
     if ($ocsconfig["ocs_url"] != '') {
         echo "<iframe src='" . $ocsconfig["ocs_url"] . "/index.php?multi=4' width='95%' height='650'>";
     }
     echo "</div>";
 }
Beispiel #17
0
 /**
  * @param $item            CommonGLPI object
  * @param $tabnum          (default 1)
  * @param $withtemplate    (default 0)
  **/
 static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0)
 {
     if (in_array($item->getType(), PluginOcsinventoryngOcsServer::getTypes(true))) {
         switch ($item->getType()) {
             case 'Computer':
                 self::showForItem($item, $withtemplate);
                 break;
         }
     }
     return true;
 }
            echo "<tr class='tab_bg_1'><td>" . __('Pc deleted', 'ocsinventoryng') . "</td><td>" . $_SESSION["ocs_deleted_equiv"]['computers_deleted'] . "</td></tr>";
            echo "</table></div>";
        }
        echo "<a href='" . $CFG_GLPI["root_doc"] . "/plugins/ocsinventoryng/front/ocsng.php'>";
        _e('Back');
        echo "</a>";
    }
} else {
    if (empty($_SESSION["ocs_deleted_equiv"]["total"])) {
        PluginOcsinventoryngOcsServer::manageDeleted($_SESSION["plugin_ocsinventoryng_ocsservers_id"]);
    }
    if ($_SESSION["ocs_deleted_equiv"]["total"] != $_SESSION["ocs_deleted_equiv"]["deleted"] && $_SESSION["ocs_deleted_equiv"]["last_req"]) {
        echo $_SESSION["ocs_deleted_equiv"]["deleted"] . "/" . $_SESSION["ocs_deleted_equiv"]["total"];
        $count = $_SESSION["ocs_deleted_equiv"]["deleted"];
        $percent = min(100, round(100 * $count / $_SESSION["ocs_deleted_equiv"]["total"], 0));
        PluginOcsinventoryngOcsServer::manageDeleted($_SESSION["plugin_ocsinventoryng_ocsservers_id"]);
        Html::displayProgressBar(400, $percent, $param['forcepadding'] = true);
        Html::redirect($_SERVER['PHP_SELF']);
    } else {
        if ($_SESSION["ocs_deleted_equiv"]["total"] === 0) {
            echo "<div class='center b'>" . __('No new computers to delete', 'ocsinventoryng') . ".</div>";
        } else {
            $total = $_SESSION["ocs_deleted_equiv"]["total"];
            $_SESSION["ocs_deleted_equiv"]["total"] = 0;
            $count = $_SESSION["ocs_deleted_equiv"]["deleted"];
            $_SESSION["ocs_deleted_equiv"]["deleted"] = 0;
            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>" . $count . "/" . $total . "</td></tr>";
 /**
  * @param $cfg_ocs
  * @param $ocsComputer
  * @param $computers_id
  * @param $entities_id
  */
 static function importNetwork($cfg_ocs, $ocsComputer, $computers_id, $entities_id)
 {
     global $DB;
     // Group by DESCRIPTION, MACADDR, TYPE, TYPEMIB, SPEED, VIRTUALDEV
     // to get an array in IPADDRESS
     $ocsNetworks = array();
     foreach ($ocsComputer as $ocsNetwork) {
         $key = $ocsNetwork['DESCRIPTION'] . $ocsNetwork['MACADDR'] . $ocsNetwork['TYPE'] . $ocsNetwork['TYPEMIB'] . $ocsNetwork['SPEED'] . $ocsNetwork['VIRTUALDEV'];
         if (!isset($ocsNetworks[$key])) {
             $ocsNetworks[$key] = $ocsNetwork;
             $ocsNetworks[$key]['IPADDRESS'] = array($ocsNetwork['IPADDRESS']);
         } else {
             $ocsNetworks[$key]['IPADDRESS'][] = $ocsNetwork['IPADDRESS'];
         }
     }
     $network_ports = array();
     $network_ifaces = array();
     foreach ($ocsNetworks as $line) {
         $line = Toolbox::clean_cross_side_scripting_deep(Toolbox::addslashes_deep($line));
         $mac = $line['MACADDR'];
         if (!isset($network_ports[$mac])) {
             $network_ports[$mac] = array('virtual' => array());
         }
         $name = PluginOcsinventoryngOcsServer::encodeOcsDataInUtf8($cfg_ocs["ocs_db_utf8"], $line['DESCRIPTION']);
         if (!empty($line['IPADDRESS'])) {
             $ip = $line['IPADDRESS'];
         } else {
             $ip = false;
         }
         $networkport_type = new PluginOcsinventoryngNetworkPortType();
         $networkport_type->getFromTypeAndTypeMIB($line);
         $speed = NetworkPortEthernet::transformPortSpeed($line['SPEED'], false);
         if (!empty($speed)) {
             $networkport_type->fields['speed'] = $speed;
         }
         $values = array('name' => $name, 'type' => array_push($network_ifaces, $networkport_type) - 1, 'ip' => $ip, 'result' => $line);
         // Virtual dev can be :
         //    1°) specifically defined from OCS
         //    2°) if there is already one main device
         //    3°) if the networkport is issued by VMWare
         if (isset($line['VIRTUALDEV']) && $line['VIRTUALDEV'] == '1' || isset($network_ports[$mac]['main']) || preg_match('/^vm(k|nic)([0-9]+)$/', $name)) {
             $network_ports[$mac]['virtual'][] = $values;
         } else {
             $network_ports[$mac]['main'] = $values;
         }
     }
     $already_known_ports = array();
     $already_known_ifaces = array();
     foreach ($network_ports as $mac => $ports) {
         if (isset($ports['main'])) {
             $main = $ports['main'];
             $type = $network_ifaces[$main['type']];
             // First search for the Network Card
             $item_device = new Item_DeviceNetworkCard();
             $item_device->getFromDBByQuery("INNER JOIN `glpi_devicenetworkcards`\n                               ON (`glpi_devicenetworkcards`.`designation`='" . $main['name'] . "')\n                        WHERE `glpi_items_devicenetworkcards`.`itemtype`='Computer'\n                           AND `glpi_items_devicenetworkcards`.`items_id`='{$computers_id}'\n                           AND `glpi_items_devicenetworkcards`.`mac`='{$mac}'\n                           AND `glpi_items_devicenetworkcards`.`devicenetworkcards_id`=\n                               `glpi_devicenetworkcards`.`id`");
             // If not found, then, create it
             if ($item_device->isNewItem()) {
                 $deviceNetworkCard = new DeviceNetworkCard();
                 $device_input = array('designation' => $main['name'], 'bandwidth' => $type->fields['speed'], 'entities_id' => $entities_id);
                 $net_id = $deviceNetworkCard->import($device_input);
                 if ($net_id) {
                     $item_device->add(array('items_id' => $computers_id, 'itemtype' => 'Computer', 'entities_id' => $entities_id, 'devicenetworkcards_id' => $net_id, 'mac' => $mac, '_no_history' => !$cfg_ocs['history_network'], 'is_dynamic' => 1, 'is_deleted' => 0));
                 }
             }
             if (!$item_device->isNewItem()) {
                 $already_known_ifaces[] = $item_device->getID();
             }
             if ($type->fields['instantiation_type'] == __CLASS__) {
                 $result = $main['result'];
                 $inst_input = array('TYPE' => $result['TYPE'], 'TYPEMIB' => $result['TYPEMIB'], 'speed' => $result['SPEED']);
             } else {
                 $inst_input = $type->fields;
                 foreach (array('id', 'name', 'OCS_TYPE', 'OCS_TYPEMIB', 'instantiation_type', 'comment') as $field) {
                     unset($inst_input[$field]);
                 }
             }
             $inst_input['items_devicenetworkcards_id'] = $item_device->getID();
             $networkports_id = self::updateNetworkPort($mac, $main['name'], $computers_id, $type->fields['instantiation_type'], $inst_input, $main['ip'], false, $cfg_ocs['history_network'], $already_known_ports);
             if ($networkports_id < 0) {
                 continue;
             }
             $already_known_ports[] = $networkports_id;
         } else {
             $networkports_id = 0;
         }
         foreach ($ports['virtual'] as $port) {
             $inst_input = array('networkports_id_alias' => $networkports_id);
             $id = self::updateNetworkPort($mac, $port['name'], $computers_id, 'NetworkPortAlias', $inst_input, $port['ip'], true, $cfg_ocs['history_network'], $already_known_ports);
             if ($id > 0) {
                 $already_known_ports[] = $id;
             }
         }
     }
     $query = "SELECT `id`\n                FROM `glpi_networkports`\n                WHERE `itemtype` = 'Computer'\n                   AND `items_id` = '{$computers_id}'\n                   AND `is_dynamic` = '1'";
     if (count($already_known_ports) > 0) {
         $query .= " AND `id` NOT IN ('" . implode("', '", $already_known_ports) . "')";
     }
     $network_ports = new NetworkPort();
     foreach ($DB->request($query) as $line) {
         $network_ports->delete($line, true, $cfg_ocs['history_network']);
     }
     $query = "SELECT `id`\n                FROM `glpi_items_devicenetworkcards`\n                WHERE `itemtype` = 'Computer'\n                   AND `items_id` = '{$computers_id}'\n                   AND `is_dynamic` = '1'";
     if (count($already_known_ifaces) > 0) {
         $query .= " AND `id` NOT IN ('" . implode("', '", $already_known_ifaces) . "')";
     }
     $item_device = new Item_DeviceNetworkCard();
     foreach ($DB->request($query) as $line) {
         $item_device->delete($line, true, $cfg_ocs['history_network']);
     }
 }
Beispiel #20
0
Ocsinventoryng plugin 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';
Html::header('OCS Inventory NG', "", "plugins", "ocsinventoryng", "clean");
if (!isset($_POST["clean_ok"])) {
    plugin_ocsinventoryng_checkRight("clean_ocsng", "r");
    if (!isset($_GET['check'])) {
        $_GET['check'] = 'all';
    }
    if (!isset($_GET['start'])) {
        $_GET['start'] = 0;
    }
    PluginOcsinventoryngOcsServer::manageDeleted($_SESSION["plugin_ocsinventoryng_ocsservers_id"]);
    PluginOcsinventoryngOcsServer::showComputersToClean($_SESSION["plugin_ocsinventoryng_ocsservers_id"], $_GET['check'], $_GET['start']);
} else {
    plugin_ocsinventoryng_checkRight("clean_ocsng", "w");
    if (count($_POST['toclean']) > 0) {
        PluginOcsinventoryngOcsServer::cleanLinksFromList($_SESSION["plugin_ocsinventoryng_ocsservers_id"], $_POST['toclean']);
        echo "<div class='center b'>" . __('Clean links between GLPI and OCSNG', 'ocsinventoryng') . "<br>" . __('Operation successful') . "<br>";
        Html::displayBackLink();
        echo "</div>";
    }
}
Html::footer();
Beispiel #21
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";
 /**
  * @see PluginOcsinventoryngOcsClient::getComputersToUpdate()
  * @param array $cfg_ocs
  * @param date $max_date
  * @return array
  */
 public function getComputersToUpdate($cfg_ocs, $max_date)
 {
     $query = "SELECT *\n                       FROM `hardware`\n                       INNER JOIN `accountinfo` ON (`hardware`.`ID` = `accountinfo`.`HARDWARE_ID`)\n                       WHERE ((`hardware`.`CHECKSUM` & " . $cfg_ocs["checksum"] . ") > '0'\n                              OR `hardware`.`LASTDATE` > '{$max_date}') ";
     // workaround to avoid duplicate when synchro occurs during an inventory
     // "after" insert in ocsweb.hardware  and "before" insert in ocsweb.deleted_equiv
     $query .= " AND UNIX_TIMESTAMP(`LASTDATE`) < (UNIX_TIMESTAMP(NOW())-180) ";
     $tag_limit = PluginOcsinventoryngOcsServer::getTagLimit($cfg_ocs);
     if (!empty($tag_limit)) {
         $query .= "AND " . $tag_limit;
     }
     $query .= " ORDER BY `hardware`.`LASTDATE` ASC\n                        LIMIT " . intval($cfg_ocs["cron_sync_number"]);
     $res = $this->db->query($query);
     $data = array();
     if ($res->num_rows > 0) {
         while ($num = $this->db->fetch_assoc($res)) {
             $data[] = $num;
         }
     }
     return $data;
 }
 /**
  * @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;
 }
Beispiel #24
0
}
$tps = microtime(true);
$nbchk = 0;
$nbdel = 0;
$nbtodo = 0;
$crit = array('is_active' => 1);
foreach ($DB->request('glpi_plugin_ocsinventoryng_ocsservers', $crit) as $serv) {
    $ocsservers_id = $serv['id'];
    echo "\nServeur: " . $serv['name'] . "\n";
    if (!PluginOcsinventoryngOcsServer::checkOCSconnection($ocsservers_id)) {
        echo "** no connexion\n";
        continue;
    }
    if (isset($_GET['clean'])) {
        echo "+ Handle ID changes\n";
        PluginOcsinventoryngOcsServer::manageDeleted($ocsservers_id);
    }
    if (isset($_GET['glpi'])) {
        echo "+ Search links with no computer in GLPI\n";
        $query = "SELECT `glpi_plugin_ocsinventoryng_ocslinks`.`id`,\n                       `glpi_plugin_ocsinventoryng_ocslinks`.`ocs_deviceid`\n                FROM `glpi_plugin_ocsinventoryng_ocslinks`\n                LEFT JOIN `glpi_computers`\n                       ON `glpi_computers`.`id`=`glpi_plugin_ocsinventoryng_ocslinks`.`computers_id`\n                WHERE `glpi_computers`.`id` IS NULL\n                      AND `plugin_ocsinventoryng_ocsservers_id`='{$ocsservers_id}'";
        $result = $DB->query($query);
        if ($DB->numrows($result) > 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 {
 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;
 }
/**
 * @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;
}
Beispiel #27
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)
{
    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;
}
Beispiel #28
0
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

Ocsinventoryng plugin 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/>.
---------------------------------------------------------------------------------------------------------------------------------------------------- */
// Ensure current directory when run from crontab
chdir(dirname($_SERVER["SCRIPT_FILENAME"]));
include '../../../inc/includes.php';
ini_set('display_errors', 1);
restore_error_handler();
if (!isset($_SERVER['argv'][1])) {
    die("usage testsync.php <computerid>\n");
}
$link = new PluginOcsinventoryngOcslink();
if (!$link->getFromDBforComputer($_SERVER['argv'][1])) {
    die("unknow computer\n");
}
printf("Device: %s\n", $link->getField('ocs_deviceid'));
$timer = new Timer();
$timer->start();
$prof = new XHProf("OCS sync");
PluginOcsinventoryngOcsServer::updateComputer($link->getID(), $link->getField('plugin_ocsinventoryng_ocsservers_id'), 1, 1);
unset($prof);
printf("Done in %s\n", $timer->getTime());
        }
        unset($_SESSION["ocs_update"]);
        $display_list = false;
        echo "<div class='center b'><br>";
        echo "<a href='" . $_SERVER['PHP_SELF'] . "'>" . __('Back') . "</a></div>";
    }
}
if (!isset($_POST["update_ok"])) {
    if (!isset($_GET['check'])) {
        $_GET['check'] = 'all';
    }
    if (!isset($_GET['start'])) {
        $_GET['start'] = 0;
    }
    PluginOcsinventoryngOcsServer::manageDeleted($_SESSION["plugin_ocsinventoryng_ocsservers_id"]);
    if ($display_list) {
        PluginOcsinventoryngOcsServer::showComputersToUpdate($_SESSION["plugin_ocsinventoryng_ocsservers_id"], $_GET['check'], $_GET['start']);
    }
} else {
    if (count($_POST['toupdate']) > 0) {
        $_SESSION["ocs_update_count"] = 0;
        foreach ($_POST['toupdate'] as $key => $val) {
            if ($val == "on") {
                $_SESSION["ocs_update"]['computers'][] = $key;
                $_SESSION["ocs_update_count"]++;
            }
        }
    }
    Html::redirect($_SERVER['PHP_SELF']);
}
Html::footer();
 /**
  * @param CommonGLPI $item
  * @param int $tabnum
  * @param int $withtemplate
  * @return bool
  */
 static function displayTabContentForItem(CommonGLPI $item, $tabnum = 0, $withtemplate = 0)
 {
     if ($item->getType() == __CLASS__) {
         $ocs = new PluginOcsinventoryngOcsServer();
         $ipdisc = new PluginOcsinventoryngIpdiscoverOcslink();
         $snmp = new PluginOcsinventoryngSnmpOcslink();
         switch ($tabnum) {
             case 0:
                 $ocs->setupMenu($_SESSION["plugin_ocsinventoryng_ocsservers_id"]);
                 break;
             case 1:
                 $ocs->importMenu($_SESSION["plugin_ocsinventoryng_ocsservers_id"]);
                 break;
             case 2:
                 $ipdisc->ipDiscoverMenu();
                 break;
             case 3:
                 $snmp->snmpMenu($_SESSION["plugin_ocsinventoryng_ocsservers_id"]);
                 break;
         }
     }
     return true;
 }