mise à jour ansible glpi

This commit is contained in:
lucas.dubief
2022-02-11 15:48:06 +01:00
parent 3bae0bc39a
commit 9ddd78ea91
1017 changed files with 394347 additions and 0 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,459 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the modules of agents
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage (enable or not) the modules in the agent.
*/
class PluginFusioninventoryAgentmodule extends CommonDBTM {
/**
* The right name for this class
*
* @var string
*/
static $rightname = "plugin_fusioninventory_agent";
/**
* Get the tab name used for item
*
* @param object $item the item object
* @param integer $withtemplate 1 if is a template form
* @return string name of the tab
*/
function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) {
if ($item->getType()=='PluginFusioninventoryConfig') {
return __('Agents modules', 'fusioninventory');
} else if ($item->getType()=='PluginFusioninventoryAgent') {
return __('Agents modules', 'fusioninventory');
}
return '';
}
/**
* Display the content of the tab
*
* @param object $item
* @param integer $tabnum number of the tab to display
* @param integer $withtemplate 1 if is a template form
* @return boolean
*/
static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) {
if ($item->getType()=='PluginFusioninventoryConfig') {
$pfAgentmodule = new self();
$pfAgentmodule->showForm();
return true;
} else if ($item->getType()=='PluginFusioninventoryAgent') {
$pfAgentmodule = new self();
$pfAgentmodule->showFormAgentException($item->fields['id']);
return true;
}
return false;
}
/**
* Display form to configure modules in agents
*
* @return boolean true if no problem
*/
function showForm() {
$pfAgent = new PluginFusioninventoryAgent();
$a_modules = $this->find();
foreach ($a_modules as $data) {
echo "<form name='form_ic' method='post' action='".
Toolbox::getItemTypeFormURL(__CLASS__)."'>";
echo "<table class='tab_cadre_fixe'>";
echo "<tr>";
echo "<th width='130'>".__('Module', 'fusioninventory')."</th>";
echo "<th width='180'>".__('Activation (by default)', 'fusioninventory')."</th>";
echo "<th>".__('Exceptions', 'fusioninventory')."</th>";
echo "</tr>";
echo "<tr class='tab_bg_1'>";
$a_methods = PluginFusioninventoryStaticmisc::getmethods();
$modulename = $data["modulename"];
foreach ($a_methods as $datamod) {
if ((strtolower($data["modulename"]) == strtolower($datamod['method'])) ||
isset($datamod['task'])
&& (strtolower($data["modulename"]) == strtolower($datamod['task']))) {
if (isset($datamod['name'])) {
$modulename = $datamod['name'];
}
break;
}
}
// Hack for snmpquery
if ($data["modulename"] == 'SNMPQUERY') {
$modulename = __('Network inventory (SNMP)', 'fusioninventory');
}
// Hack for deploy
if ($data["modulename"] == 'DEPLOY') {
$modulename = __('Package deployment', 'fusioninventory');
}
echo "<td align='center'><strong>".$modulename."</strong></td>";
echo "<td align='center'>";
$checked = $data['is_active'];
Html::showCheckbox(['name' => 'activation',
'value' => '1',
'checked' => $checked]);
echo "</td>";
echo "<td>";
echo "<table>";
echo "<tr>";
echo "<td width='45%'>";
$a_agentList = importArrayFromDB($data['exceptions']);
$a_used = [];
foreach ($a_agentList as $agent_id) {
$a_used[] = $agent_id;
}
Dropdown::show("PluginFusioninventoryAgent", ["name" => "agent_to_add[]",
"used" => $a_used]);
echo "</td>";
echo "<td align='center'>";
echo "<input type='submit' class='submit' name='agent_add' value='" .
__s('Add') . " >>'>";
echo "<br><br>";
echo "<input type='submit' class='submit' name='agent_delete' value='<< " .
__s('Delete') . "'>";
echo "</td>";
echo "<td width='45%'>";
echo "<select size='6' name='agent_to_delete[]'>";
foreach ($a_agentList as $agent_id) {
$pfAgent->getFromDB($agent_id);
echo "<option value='".$agent_id."'>".$pfAgent->getName()."</option>";
}
echo "</select>";
echo "</td>";
echo "</tr>";
echo "</table>";
echo "</td>";
echo "<tr>";
echo "<td class='tab_bg_2 center' colspan='3'>";
echo "<input type='submit' name='update' value=\"".__s('Update')."\" class='submit'>";
echo "</td>";
echo "</tr>";
echo "</table>";
echo Html::hidden('id', ['value' => $data['id']]);
Html::closeForm();
echo "<br/>";
}
return true;
}
/**
* Display form to configure activation of modules in agent form (in tab)
*
* @global array $CFG_GLPI
* @param integer $agents_id id of the agent
*/
function showFormAgentException($agents_id) {
$pfAgent = new PluginFusioninventoryAgent();
$pfAgent->getFromDB($agents_id);
$canedit = $pfAgent->can($agents_id, UPDATE);
echo "<br/>";
if ($canedit) {
echo "<form name='form_ic' method='post' action='".Plugin::getWebDir('fusioninventory').
"/front/agentmodule.form.php'>";
}
echo "<table class='tab_cadre_fixe'>";
echo "<tr>";
echo "<th>".__('Module', 'fusioninventory')."</th>";
echo "<th>Activation</th>";
echo "<th>".__('Module', 'fusioninventory')."</th>";
echo "<th>Activation</th>";
echo "</tr>";
$a_modules = $this->find();
$i = 0;
$a_methods = PluginFusioninventoryStaticmisc::getmethods();
foreach ($a_modules as $data) {
if ($i == 0) {
echo "<tr class='tab_bg_1'>";
}
$modulename = $data["modulename"];
foreach ($a_methods as $datamod) {
if ((strtolower($data["modulename"]) == strtolower($datamod['method'])) ||
isset($datamod['task'])
&& (strtolower($data["modulename"]) == strtolower($datamod['task']))) {
if (isset($datamod['name'])) {
$modulename = $datamod['name'];
}
break;
}
}
// Hack for snmpquery
if ($data["modulename"] == 'SNMPQUERY') {
$modulename = __('Network inventory (SNMP)', 'fusioninventory');
}
// Hack for deploy
if ($data["modulename"] == 'DEPLOY') {
$modulename = __('Package deployment', 'fusioninventory');
}
echo "<td width='50%'>".$modulename." :</td>";
echo "<td align='center'>";
$checked = $data['is_active'];
$a_agentList = importArrayFromDB($data['exceptions']);
if (in_array($agents_id, $a_agentList)) {
if ($checked == 1) {
$checked = 0;
} else {
$checked = 1;
}
}
Html::showCheckbox(['name' => "activation-".$data["modulename"],
'value' => '1',
'checked' => $checked]);
echo "</td>";
if ($i == 1) {
echo "</tr>";
$i = -1;
}
$i++;
}
if ($i == 1) {
echo "<td></td>";
echo "<td></td>";
echo "</tr>";
}
if ($canedit) {
echo "<tr>";
echo "<td class='tab_bg_2 center' colspan='4'>";
echo Html::hidden('id', ['value' => $agents_id]);
echo "<input type='submit' name='updateexceptions' ".
"value=\"".__('Update')."\" class='submit'>";
echo "</td>";
echo "</tr>";
echo "</table>";
Html::closeForm();
} else {
echo "</table>";
}
}
/**
* Get global activation status of a module
*
* @param string $module_name name of module
* @return array information of module activation
*/
function getActivationExceptions($module_name) {
$a_modules = $this->find(['modulename' => $module_name], [], 1);
return current($a_modules);
}
/**
* Get list of agents have this module activated
*
* @param string $module_name name of the module
* @return array id list of agents
*/
function getAgentsCanDo($module_name) {
$pfAgent = new PluginFusioninventoryAgent();
if ($module_name == 'SNMPINVENTORY') {
$module_name = 'SNMPQUERY';
}
$agentModule = $this->getActivationExceptions($module_name);
$where = [];
if ($agentModule['is_active'] == 0) {
$a_agentList = importArrayFromDB($agentModule['exceptions']);
if (count($a_agentList) > 0) {
$ips = [];
$i = 0;
foreach ($a_agentList as $agent_id) {
if ($i> 0) {
$ips[] = $agent_id;
}
$i++;
}
if (count($ips) > 0) {
$where = ['id' => $ips];
}
if (isset($_SESSION['glpiactiveentities_string'])) {
$where += getEntitiesRestrictCriteria($pfAgent->getTable());
}
} else {
return [];
}
} else {
$a_agentList = importArrayFromDB($agentModule['exceptions']);
if (count($a_agentList) > 0) {
$ips = [];
$i = 0;
foreach ($a_agentList as $agent_id) {
if ($i> 0) {
$ips[] = $agent_id;
}
$i++;
}
if (count($ips) > 0) {
$where = ['id' => ['NOT' => $ips]];
}
if (isset($_SESSION['glpiactiveentities_string'])) {
$where += getEntitiesRestrictCriteria($pfAgent->getTable());
}
}
}
$a_agents = $pfAgent->find($where);
return $a_agents;
}
/**
* Get if agent has this module enabled
*
* @param string $module_name module name
* @param integer $agents_id id of the agent
* @return boolean true if enabled, otherwise false
*/
function isAgentCanDo($module_name, $agents_id) {
$agentModule = $this->getActivationExceptions($module_name);
if ($agentModule['is_active'] == 0) {
$a_agentList = importArrayFromDB($agentModule['exceptions']);
if (in_array($agents_id, $a_agentList)) {
return true;
} else {
return false;
}
} else {
$a_agentList = importArrayFromDB($agentModule['exceptions']);
if (in_array($agents_id, $a_agentList)) {
return false;
} else {
return true;
}
}
}
/**
* Generate the server module URL to send to agent
*
* @param string $modulename name of the module
* @param integer $entities_id id of the entity
* @return string the URL generated
*/
static function getUrlForModule($modulename, $entities_id = -1) {
$fi_dir = '/'.Plugin::getWebDir('fusioninventory', false);
// Get current entity URL if it exists ...
$pfEntity = new PluginFusioninventoryEntity();
$baseUrl = $pfEntity->getValue('agent_base_url', $entities_id);
if (! empty($baseUrl)) {
PluginFusioninventoryToolbox::logIfExtradebug(
"pluginFusioninventory-agent-url",
"Entity ".$entities_id.", agent base URL: ".$baseUrl
);
if ($baseUrl != 'N/A') {
return $baseUrl.$fi_dir.'/b/'.strtolower($modulename).'/';
}
}
// ... else use global plugin configuration parameter.
if (strlen($pfEntity->getValue('agent_base_url', $entities_id))<10) {
PluginFusioninventoryCommunicationRest::sendError();
exit;
// die ("agent_base_url is unset!\n");
}
PluginFusioninventoryToolbox::logIfExtradebug(
"pluginFusioninventory-agent-url",
"Global configuration URL: ".$pfEntity->getValue('agent_base_url', $entities_id)
);
// Construct the path to the JSON back from the agent_base_url.
// agent_base_url is the initial URL used by the agent
return $pfEntity->getValue('agent_base_url', $entities_id).$fi_dir.'/b/'.strtolower($modulename).'/';
}
/**
* Get list of all modules
*
* @return array list of name of modules
*/
static function getModules() {
$a_modules = [];
$a_data = getAllDataFromTable(PluginFusioninventoryAgentmodule::getTable());
foreach ($a_data as $data) {
$a_modules[] = $data['modulename'];
}
return $a_modules;
}
}

View File

@@ -0,0 +1,228 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the wake up the agents
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author Walid Nouh
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the wake up the agents remotely.
*/
class PluginFusioninventoryAgentWakeup extends CommonDBTM {
/**
* The right name for this class
*
* @var string
*/
static $rightname = 'plugin_fusioninventory_taskjob';
/**
* Get name of this type by language of the user connected
*
* @param integer $nb number of elements
* @return string name of this type
*/
static function getTypeName($nb = 0) {
return __('Job', 'fusioninventory');
}
/**
* Check if can wake up an agent
*
* @return true
*/
static function canCreate() {
return true;
}
/*
* @function cronWakeupAgents
* This function update already running tasks with dynamic groups
*/
/**
* Cron task: wake up agents. Configuration is in each tasks
*
* @global object $DB
* @param object $crontask
* @return boolean true if successfully, otherwise false
*/
static function cronWakeupAgents($crontask) {
global $DB;
$wakeupArray = [];
$tasks = [];
//Get the maximum number of agent to wakeup,
//as allowed in the general configuration
$config = new PluginFusioninventoryConfig();
$agent = new PluginFusioninventoryAgent();
$maxWakeUp = $config->getValue('wakeup_agent_max');
//Get all active timeslots
$timeslot = new PluginFusioninventoryTimeslot();
$timeslots = $timeslot->getCurrentActiveTimeslots();
$query_timeslots = [
'plugin_fusioninventory_timeslots_exec_id' => 0
];
if (!empty($timeslots)) {
array_push($query_timeslots, [
'plugin_fusioninventory_timeslots_exec_id' => $timeslots
]);
}
//Get all active task requiring an agent wakeup
//Check all tasks without timeslot or task with a current active timeslot
$iterator = $DB->request([
'SELECT' => ['id', 'wakeup_agent_counter', 'wakeup_agent_time', 'last_agent_wakeup'],
'FROM' => 'glpi_plugin_fusioninventory_tasks',
'WHERE' => [
'wakeup_agent_counter' => ['>', 0],
'wakeup_agent_time' => ['>', 0],
'is_active' => 1,
[
'OR' => $query_timeslots
]
]
]);
while ($task = $iterator->next()) {
if (!is_null($task['wakeup_agent_time'])) {
//Do not wake up is last wake up in inferior to the minimum wake up interval
$interval = time() - strtotime($task['last_agent_wakeup']);
if ($interval < ($task['wakeup_agent_time'] * MINUTE_TIMESTAMP)) {
continue;
}
}
$maxWakeUpTask = $task['wakeup_agent_counter'];
if ($maxWakeUp < $maxWakeUpTask) {
$maxWakeUpTask = $maxWakeUp;
}
//Store task ID
if (!in_array($task['id'], $tasks)) {
$tasks[] = $task['id'];
}
//For each task, get a number of taskjobs at the PREPARED state
//(the maximum is defined in wakeup_agent_counter)
$iterator2 = $DB->request([
'SELECT' => [
'glpi_plugin_fusioninventory_taskjobstates.plugin_fusioninventory_agents_id',
],
'FROM' => [
'glpi_plugin_fusioninventory_taskjobstates'
],
'LEFT JOIN' => [
'glpi_plugin_fusioninventory_taskjobs' => [
'FKEY' => [
'glpi_plugin_fusioninventory_taskjobs' => 'id',
'glpi_plugin_fusioninventory_taskjobstates' => 'plugin_fusioninventory_taskjobs_id'
]
]
],
'WHERE' => [
'glpi_plugin_fusioninventory_taskjobs.plugin_fusioninventory_tasks_id' => $task['id'],
'glpi_plugin_fusioninventory_taskjobstates.state' => PluginFusioninventoryTaskjobstate::PREPARED
],
'ORDER' => 'glpi_plugin_fusioninventory_taskjobstates.id',
'START' => 0,
]);
$counter = 0;
while ($state = $iterator2->next()) {
$agents_id = $state['plugin_fusioninventory_agents_id'];
if (isset($wakeupArray[$agents_id])) {
$counter++;
} else {
$agent->getFromDB($agents_id);
$statusAgent = $agent->getStatus();
if ($statusAgent['message'] == 'waiting') {
$wakeupArray[$agents_id] = $agents_id;
$counter++;
}
}
// check if max number of agent reached for this task
if ($counter >= $maxWakeUpTask) {
break;
}
}
}
//Number of agents successfully woken up
$wokeup = 0;
if (!empty($tasks)) {
//Update last wake up time each task
$DB->update(
'glpi_plugin_fusioninventory_tasks', [
'last_agent_wakeup' => $_SESSION['glpi_currenttime']
], [
'id' => $tasks
]
);
//Try to wake up agents one by one
foreach ($wakeupArray as $ID) {
$agent->getFromDB($ID);
if ($agent->wakeUp()) {
$wokeup++;
}
}
}
$crontask->addVolume($wokeup);
return true;
}
}

View File

@@ -0,0 +1,892 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the collect (registry, file, wmi) module of
* the agents
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the collect information by the agent.
*/
class PluginFusioninventoryCollect extends CommonDBTM {
/**
* The right name for this class
*
* @var string
*/
static $rightname = 'plugin_fusioninventory_collect';
/**
* Get name of this type by language of the user connected
*
* @param integer $nb number of elements
* @return string name of this type
*/
static function getTypeName($nb = 0) {
return __('Collect information', 'fusioninventory');
}
/**
* Get the tab name used for item
*
* @param object $item the item object
* @param integer $withtemplate 1 if is a template form
* @return string name of the tab
*/
function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) {
if ($item->fields['id'] > 0) {
$index = self::getNumberOfCollectsForAComputer($item->fields['id']);
$nb = 0;
if ($index > 0) {
if ($_SESSION['glpishow_count_on_tabs']) {
$nb = $index;
}
return self::createTabEntry(self::getTypeName(Session::getPluralNumber()), $nb);
}
}
return '';
}
/**
* Display the content of the tab
*
* @param object $item
* @param integer $tabnum number of the tab to display
* @param integer $withtemplate 1 if is a template form
* @return boolean
*/
static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) {
$pfComputer = new PluginFusioninventoryInventoryComputerComputer();
$id = $item->fields['id'];
if ($item->getType() == 'Computer'
&& $pfComputer->hasAutomaticInventory($id)) {
foreach (['PluginFusioninventoryCollect_File_Content',
'PluginFusioninventoryCollect_Wmi_Content',
'PluginFusioninventoryCollect_Registry_Content'] as $itemtype) {
$collect_item = new $itemtype();
$collect_item->showForComputer($id);
}
}
return false;
}
/**
* Get the number of collects for a computer
* @since 9.2
*
* @param integer $computers_id the computer ID
* @return the number of collects for this computer
*/
static function getNumberOfCollectsForAComputer($computers_id) {
$tables = ['glpi_plugin_fusioninventory_collects_registries_contents',
'glpi_plugin_fusioninventory_collects_wmis_contents',
'glpi_plugin_fusioninventory_collects_files_contents',
];
$total = 0;
foreach ($tables as $table) {
$total+= countElementsInTable($table, ['computers_id' => $computers_id]);
}
return $total;
}
/**
* Get all collect types
*
* @return array [name] => description
*/
static function getTypes() {
return [
'registry' => __('Registry', 'fusioninventory'),
'wmi' => __('WMI', 'fusioninventory'),
'file' => __('Find file', 'fusioninventory')
];
}
function rawSearchOptions() {
$tab = [];
$tab[] = [
'id' => 'common',
'name' => __('Characteristics')
];
$tab[] = [
'id' => '1',
'table' => $this->getTable(),
'field' => 'name',
'name' => __('Name'),
'datatype' => 'itemlink',
'autocomplete' => true,
];
return $tab;
}
/**
* Add search options
*
* @return array
*/
static function getSearchOptionsToAdd($itemtype = null) {
$tab = [];
$i = 5200;
$pfCollect = new PluginFusioninventoryCollect();
foreach ($pfCollect->find(getEntitiesRestrictCriteria($pfCollect->getTable(), '', '', true), ['id ASC']) as $collect) {
//registries
$pfCollect_Registry = new PluginFusioninventoryCollect_Registry();
$registries = $pfCollect_Registry->find(['plugin_fusioninventory_collects_id' => $collect['id']], ['id ASC']);
foreach ($registries as $registry) {
$tab[$i]['table'] = 'glpi_plugin_fusioninventory_collects_registries_contents';
$tab[$i]['field'] = 'value';
$tab[$i]['linkfield'] = '';
$tab[$i]['name'] = __('Registry', 'fusioninventory')." - ".$registry['name'];
$tab[$i]['joinparams'] = ['jointype' => 'child'];
$tab[$i]['datatype'] = 'text';
$tab[$i]['forcegroupby'] = true;
$tab[$i]['massiveaction'] = false;
$tab[$i]['nodisplay'] = true;
$tab[$i]['joinparams'] = ['condition' => "AND NEWTABLE.`plugin_fusioninventory_collects_registries_id` = ".$registry['id'],
'jointype' => 'child'];
$i++;
}
//WMIs
$pfCollect_Wmi = new PluginFusioninventoryCollect_Wmi();
$wmis = $pfCollect_Wmi->find(['plugin_fusioninventory_collects_id' => $collect['id']], ['id ASC']);
foreach ($wmis as $wmi) {
$tab[$i]['table'] = 'glpi_plugin_fusioninventory_collects_wmis_contents';
$tab[$i]['field'] = 'value';
$tab[$i]['linkfield'] = '';
$tab[$i]['name'] = __('WMI', 'fusioninventory')." - ".$wmi['name'];
$tab[$i]['joinparams'] = ['jointype' => 'child'];
$tab[$i]['datatype'] = 'text';
$tab[$i]['forcegroupby'] = true;
$tab[$i]['massiveaction'] = false;
$tab[$i]['nodisplay'] = true;
$tab[$i]['joinparams'] = ['condition' => "AND NEWTABLE.`plugin_fusioninventory_collects_wmis_id` = ".$wmi['id'],
'jointype' => 'child'];
$i++;
}
//Files
$pfCollect_File = new PluginFusioninventoryCollect_File();
$files = $pfCollect_File->find(['plugin_fusioninventory_collects_id' => $collect['id']], ['id ASC']);
foreach ($files as $file) {
$tab[$i]['table'] = 'glpi_plugin_fusioninventory_collects_files_contents';
$tab[$i]['field'] = 'pathfile';
$tab[$i]['linkfield'] = '';
$tab[$i]['name'] = __('Find file', 'fusioninventory').
" - ".$file['name'].
" - ".__('pathfile', 'fusioninventory');
$tab[$i]['joinparams'] = ['jointype' => 'child'];
$tab[$i]['datatype'] = 'text';
$tab[$i]['forcegroupby'] = true;
$tab[$i]['massiveaction'] = false;
$tab[$i]['nodisplay'] = true;
$tab[$i]['joinparams'] = ['condition' => "AND NEWTABLE.`plugin_fusioninventory_collects_files_id` = ".$file['id'],
'jointype' => 'child'];
$i++;
$tab[$i]['table'] = 'glpi_plugin_fusioninventory_collects_files_contents';
$tab[$i]['field'] = 'size';
$tab[$i]['linkfield'] = '';
$tab[$i]['name'] = __('Find file', 'fusioninventory').
" - ".$file['name'].
" - ".__('Size', 'fusioninventory');
$tab[$i]['joinparams'] = ['jointype' => 'child'];
$tab[$i]['datatype'] = 'text';
$tab[$i]['forcegroupby'] = true;
$tab[$i]['massiveaction'] = false;
$tab[$i]['nodisplay'] = true;
$tab[$i]['joinparams'] = ['condition' => "AND NEWTABLE.`plugin_fusioninventory_collects_files_id` = ".$file['id'],
'jointype' => 'child'];
$i++;
}
}
return $tab;
}
/**
* Display form
*
* @param integer $ID
* @param array $options
* @return true
*/
function showForm($ID, $options = []) {
$this->initForm($ID, $options);
$this->showFormHeader($options);
echo "<tr class='tab_bg_1'>";
echo "<td>";
echo __('Name');
echo "</td>";
echo "<td>";
Html::autocompletionTextField($this, 'name');
echo "</td>";
echo "<td>".__('Type')."</td>";
echo "<td>";
Dropdown::showFromArray('type',
PluginFusioninventoryCollect::getTypes(),
['value' => $this->fields['type']]);
echo "</td>";
echo "</tr>\n";
echo "<tr class='tab_bg_1'>";
echo "<td>";
echo __('Comments');
echo "</td>";
echo "<td class='middle'>";
echo "<textarea cols='45' rows='3' name='comment' >".
$this->fields["comment"]."</textarea>";
echo "</td>";
echo "<td>".__('Active')."</td>";
echo "<td>";
Dropdown::showYesNo('is_active', $this->fields['is_active']);
echo "</td>";
echo "</tr>\n";
$this->showFormButtons($options);
return true;
}
/**
* Prepare run, so it prepare the taskjob with module 'collect'.
* It prepare collect information and computer list for task run
*
* @global object $DB
* @param integer $taskjobs_id id of taskjob
*/
function prepareRun($taskjobs_id) {
global $DB;
$task = new PluginFusioninventoryTask();
$job = new PluginFusioninventoryTaskjob();
$joblog = new PluginFusioninventoryTaskjoblog();
$jobstate = new PluginFusioninventoryTaskjobstate();
$agent = new PluginFusioninventoryAgent();
$job->getFromDB($taskjobs_id);
$task->getFromDB($job->fields['plugin_fusioninventory_tasks_id']);
$communication = $task->fields['communication'];
$actions = importArrayFromDB($job->fields['action']);
$definitions = importArrayFromDB($job->fields['definition']);
$taskvalid = 0;
$computers = [];
foreach ($actions as $action) {
$itemtype = key($action);
$items_id = current($action);
switch ($itemtype) {
case 'Computer':
$computers[] = $items_id;
break;
case 'Group':
$computer_object = new Computer();
//find computers by user associated with this group
$group_users = new Group_User();
$group = new Group();
$group->getFromDB($items_id);
$computers_a_1 = [];
$computers_a_2 = [];
$members = $group_users->getGroupUsers($items_id);
foreach ($members as $member) {
$computers = $computer_object->find(['users_id' => $member['id']]);
foreach ($computers as $computer) {
$computers_a_1[] = $computer['id'];
}
}
//find computers directly associated with this group
$computers = $computer_object->find(['groups_id' => $items_id]);
foreach ($computers as $computer) {
$computers_a_2[] = $computer['id'];
}
//merge two previous array and deduplicate entries
$computers = array_unique(array_merge($computers_a_1, $computers_a_2));
break;
case 'PluginFusioninventoryDeployGroup':
$group = new PluginFusioninventoryDeployGroup;
$group->getFromDB($items_id);
switch ($group->getField('type')) {
case 'STATIC':
$query = "SELECT items_id
FROM glpi_plugin_fusioninventory_deploygroups_staticdatas
WHERE groups_id = '$items_id'
AND itemtype = 'Computer'";
$res = $DB->query($query);
while ($row = $DB->fetchAssoc($res)) {
$computers[] = $row['items_id'];
}
break;
case 'DYNAMIC':
$query = "SELECT fields_array
FROM glpi_plugin_fusioninventory_deploygroups_dynamicdatas
WHERE groups_id = '$items_id'
LIMIT 1";
$res = $DB->query($query);
$row = $DB->fetchAssoc($res);
if (isset($_GET)) {
$get_tmp = $_GET;
}
if (isset($_SESSION["glpisearchcount"]['Computer'])) {
unset($_SESSION["glpisearchcount"]['Computer']);
}
if (isset($_SESSION["glpisearchcount2"]['Computer'])) {
unset($_SESSION["glpisearchcount2"]['Computer']);
}
$_GET = importArrayFromDB($row['fields_array']);
$_GET["glpisearchcount"] = count($_GET['field']);
if (isset($_GET['field2'])) {
$_GET["glpisearchcount2"] = count($_GET['field2']);
}
$pfSearch = new PluginFusioninventorySearch();
$glpilist_limit = $_SESSION['glpilist_limit'];
$_SESSION['glpilist_limit'] = 999999999;
$result = $pfSearch->constructSQL('Computer',
$_GET);
$_SESSION['glpilist_limit'] = $glpilist_limit;
while ($data=$DB->fetchArray($result)) {
$computers[] = $data['id'];
}
if (count($get_tmp) > 0) {
$_GET = $get_tmp;
}
break;
}
break;
}
}
$c_input= [];
$c_input['plugin_fusioninventory_taskjobs_id'] = $taskjobs_id;
$c_input['state'] = 0;
$c_input['plugin_fusioninventory_agents_id'] = 0;
$c_input['execution_id'] = $task->fields['execution_id'];
$pfCollect = new PluginFusioninventoryCollect();
foreach ($computers as $computer_id) {
//get agent if for this computer
$agents_id = $agent->getAgentWithComputerid($computer_id);
if ($agents_id === false) {
$jobstates_id = $jobstate->add($c_input);
$jobstate->changeStatusFinish($jobstates_id,
0,
'',
1,
"No agent found for [[Computer::".$computer_id."]]");
} else {
foreach ($definitions as $definition) {
$pfCollect->getFromDB($definition['PluginFusioninventoryCollect']);
switch ($pfCollect->fields['type']) {
case 'registry':
// get all registry
$pfCollect_Registry = new PluginFusioninventoryCollect_Registry();
$a_registries = $pfCollect_Registry->find(
['plugin_fusioninventory_collects_id' => $pfCollect->fields['id']]);
foreach ($a_registries as $data_r) {
$uniqid= uniqid();
$c_input['state'] = 0;
$c_input['itemtype'] = 'PluginFusioninventoryCollect_Registry';
$c_input['items_id'] = $data_r['id'];
$c_input['date'] = date("Y-m-d H:i:s");
$c_input['uniqid'] = $uniqid;
$c_input['plugin_fusioninventory_agents_id'] = $agents_id;
// Push the agent, in the stack of agent to awake
if ($communication == "push") {
$_SESSION['glpi_plugin_fusioninventory']['agents'][$agents_id] = 1;
}
$jobstates_id= $jobstate->add($c_input);
//Add log of taskjob
$c_input['plugin_fusioninventory_taskjobstates_id'] = $jobstates_id;
$c_input['state']= PluginFusioninventoryTaskjoblog::TASK_PREPARED;
$taskvalid++;
$joblog->add($c_input);
}
break;
case 'wmi':
// get all wmi
$pfCollect_Wmi = new PluginFusioninventoryCollect_Wmi();
$a_wmies = $pfCollect_Wmi->find(
['plugin_fusioninventory_collects_id' => $pfCollect->fields['id']]);
foreach ($a_wmies as $data_r) {
$uniqid= uniqid();
$c_input['state'] = 0;
$c_input['itemtype'] = 'PluginFusioninventoryCollect_Wmi';
$c_input['items_id'] = $data_r['id'];
$c_input['date'] = date("Y-m-d H:i:s");
$c_input['uniqid'] = $uniqid;
$c_input['plugin_fusioninventory_agents_id'] = $agents_id;
// Push the agent, in the stack of agent to awake
if ($communication == "push") {
$_SESSION['glpi_plugin_fusioninventory']['agents'][$agents_id] = 1;
}
$jobstates_id= $jobstate->add($c_input);
//Add log of taskjob
$c_input['plugin_fusioninventory_taskjobstates_id'] = $jobstates_id;
$c_input['state']= PluginFusioninventoryTaskjoblog::TASK_PREPARED;
$taskvalid++;
$joblog->add($c_input);
}
break;
case 'file':
// find files
$pfCollect_File = new PluginFusioninventoryCollect_File();
$a_files = $pfCollect_File->find(
['plugin_fusioninventory_collects_id' => $pfCollect->fields['id']]);
foreach ($a_files as $data_r) {
$uniqid= uniqid();
$c_input['state'] = 0;
$c_input['itemtype'] = 'PluginFusioninventoryCollect_File';
$c_input['items_id'] = $data_r['id'];
$c_input['date'] = date("Y-m-d H:i:s");
$c_input['uniqid'] = $uniqid;
$c_input['plugin_fusioninventory_agents_id'] = $agents_id;
// Push the agent, in the stack of agent to awake
if ($communication == "push") {
$_SESSION['glpi_plugin_fusioninventory']['agents'][$agents_id] = 1;
}
$jobstates_id= $jobstate->add($c_input);
//Add log of taskjob
$c_input['plugin_fusioninventory_taskjobstates_id'] = $jobstates_id;
$c_input['state']= PluginFusioninventoryTaskjoblog::TASK_PREPARED;
$taskvalid++;
$joblog->add($c_input);
}
break;
}
}
}
}
if ($taskvalid > 0) {
$job->fields['status']= 1;
$job->update($job->fields);
} else {
$job->reinitializeTaskjobs($job->fields['plugin_fusioninventory_tasks_id']);
}
}
/**
* run function, so return data to send to the agent for collect information
*
* @param object $taskjobstate PluginFusioninventoryTaskjobstate instance
* @param array $agent agent information from agent table in database
* @return array
*/
function run($taskjobstate, $agent) {
global $DB;
$output = [];
$this->getFromDB($taskjobstate->fields['items_id']);
$sql_where = ['plugin_fusioninventory_collects_id' => $this->fields['id']];
switch ($this->fields['type']) {
case 'registry':
$pfCollect_Registry = new PluginFusioninventoryCollect_Registry();
$reg_db = $pfCollect_Registry->find($sql_where);
foreach ($reg_db as $reg) {
$output[] = [
'function' => 'getFromRegistry',
'path' => $reg['hive'].$reg['path'].$reg['key'],
'uuid' => $taskjobstate->fields['uniqid'],
'_sid' => $reg['id']
];
}
break;
case 'wmi':
$pfCollect_Wmi = new PluginFusioninventoryCollect_Wmi();
$wmi_db = $pfCollect_Wmi->find($sql_where);
foreach ($wmi_db as $wmi) {
$datawmi = [
'function' => 'getFromWMI',
'class' => $wmi['class'],
'properties' => [$wmi['properties']],
'uuid' => $taskjobstate->fields['uniqid'],
'_sid' => $wmi['id']];
if ($wmi['moniker'] != '') {
$datawmi['moniker'] = $wmi['moniker'];
}
$output[] = $datawmi;
}
break;
case 'file':
$pfCollect_File = new PluginFusioninventoryCollect_File();
$files_db = $pfCollect_File->find($sql_where);
foreach ($files_db as $files) {
$datafile = [
'function' => 'findFile',
'dir' => $files['dir'],
'limit' => $files['limit'],
'recursive' => $files['is_recursive'],
'filter' => [
'is_file' => $files['filter_is_file'],
'is_dir' => $files['filter_is_dir']
],
'uuid' => $taskjobstate->fields['uniqid'],
'_sid' => $files['id']
];
if ($files['filter_regex'] != '') {
$datafile['filter']['regex'] = $files['filter_regex'];
}
if ($files['filter_sizeequals'] > 0) {
$datafile['filter']['sizeEquals'] = $files['filter_sizeequals'];
} else if ($files['filter_sizegreater'] > 0) {
$datafile['filter']['sizeGreater'] = $files['filter_sizegreater'];
} else if ($files['filter_sizelower'] > 0) {
$datafile['filter']['sizeLower'] = $files['filter_sizelower'];
}
if ($files['filter_checksumsha512'] != '') {
$datafile['filter']['checkSumSHA512'] = $files['filter_checksumsha512'];
}
if ($files['filter_checksumsha2'] != '') {
$datafile['filter']['checkSumSHA2'] = $files['filter_checksumsha2'];
}
if ($files['filter_name'] != '') {
$datafile['filter']['name'] = $files['filter_name'];
}
if ($files['filter_iname'] != '') {
$datafile['filter']['iname'] = $files['filter_iname'];
}
$output[] = $datafile;
//clean old files
$DB->delete(
'glpi_plugin_fusioninventory_collects_files_contents', [
'plugin_fusioninventory_collects_files_id' => $files['id'],
'computers_id' => $agent['computers_id']
]
);
}
break;
}
return $output;
}
function communication($action, $machineId, $uuid) {
$response = new \stdClass();
if (empty($action)) {
return $response;
}
$pfAgent = new PluginFusioninventoryAgent();
$pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
$pfTaskjoblog = new PluginFusioninventoryTaskjoblog();
switch ($action) {
case 'getJobs':
if (empty($machineId)) {
return $response;
}
$pfAgentModule = new PluginFusioninventoryAgentmodule();
$pfTask = new PluginFusioninventoryTask();
$agent = $pfAgent->infoByKey(Toolbox::addslashes_deep($machineId));
if (isset($agent['id'])) {
$taskjobstates = $pfTask->getTaskjobstatesForAgent(
$agent['id'],
['collect']
);
$order = new \stdClass();
$order->jobs = [];
foreach ($taskjobstates as $taskjobstate) {
if (!$pfAgentModule->isAgentCanDo("Collect", $agent['id'])) {
$taskjobstate->cancel(
__("Collect module has been disabled for this agent", 'fusioninventory')
);
} else {
$out = $this->run($taskjobstate, $agent);
if (count($out) > 0) {
$order->jobs = array_merge($order->jobs, $out);
}
// change status of state table row
$pfTaskjobstate->changeStatus(
$taskjobstate->fields['id'],
PluginFusioninventoryTaskjobstate::SERVER_HAS_SENT_DATA
);
$a_input = [
'plugin_fusioninventory_taskjobstates_id' => $taskjobstate->fields['id'],
'items_id' => $agent['id'],
'itemtype' => 'PluginFusioninventoryAgent',
'date' => date("Y-m-d H:i:s"),
'comment' => '',
'state' => PluginFusioninventoryTaskjoblog::TASK_STARTED
];
$pfTaskjoblog->add($a_input);
if (count($order->jobs) > 0) {
$response = $order;
// Inform agent we request POST method, agent will then submit result
// in POST request if it supports the method or it will continue with GET
$response->postmethod = 'POST';
$response->token = Session::getNewCSRFToken();
}
}
}
}
break;
case 'setAnswer':
// example
// ?action=setAnswer&InformationSource=0x00000000&BIOSVersion=VirtualBox&SystemManufacturer=innotek%20GmbH&uuid=fepjhoug56743h&SystemProductName=VirtualBox&BIOSReleaseDate=12%2F01%2F2006
if (empty($uuid)) {
return $response;
}
$jobstate = current($pfTaskjobstate->find(
[
'uniqid' => $uuid,
'state' => ['!=', PluginFusioninventoryTaskjobstate::FINISHED]
],
[],
1)
);
if (isset($jobstate['plugin_fusioninventory_agents_id'])) {
$add_value = true;
$pfAgent->getFromDB($jobstate['plugin_fusioninventory_agents_id']);
$computers_id = $pfAgent->fields['computers_id'];
$a_values = $_GET;
// Check agent uses POST method to use the right submitted values. Also renew token to support CSRF for next post.
if (isset($_GET['method']) && $_GET['method'] == 'POST') {
$a_values = $_POST;
$response->token = Session::getNewCSRFToken();
unset($a_values['_glpi_csrf_token']);
}
$sid = isset($a_values['_sid'])?$a_values['_sid']:0;
$cpt = isset($a_values['_cpt'])?$a_values['_cpt']:0;
unset($a_values['action']);
unset($a_values['uuid']);
unset($a_values['_cpt']);
unset($a_values['_sid']);
$this->getFromDB($jobstate['items_id']);
switch ($this->fields['type']) {
case 'registry':
// update registry content
$pfCollect_subO = new PluginFusioninventoryCollect_Registry_Content();
break;
case 'wmi':
// update wmi content
$pfCollect_subO = new PluginFusioninventoryCollect_Wmi_Content();
break;
case 'file':
if (!empty($a_values['path']) && isset($a_values['size'])) {
// update files content
$params = [
'machineid' => $pfAgent->fields['device_id'],
'uuid' => $uuid,
'code' => 'running',
'msg' => "file ".$a_values['path']." | size ".$a_values['size']
];
if (isset($a_values['sendheaders'])) {
$params['sendheaders'] = $a_values['sendheaders'];
}
PluginFusioninventoryCommunicationRest::updateLog($params);
$pfCollect_subO = new PluginFusioninventoryCollect_File_Content();
$a_values = [$sid => $a_values];
} else {
$add_value = false;
}
break;
}
if (!isset($pfCollect_subO)) {
// return anyway the next CSRF token to client
break;
}
if ($add_value) {
// add collected informations to computer
$pfCollect_subO->updateComputer(
$computers_id,
$a_values,
$sid
);
}
// change status of state table row
$pfTaskjobstate->changeStatus($jobstate['id'],
PluginFusioninventoryTaskjobstate::AGENT_HAS_SENT_DATA);
// add logs to job
if (count($a_values)) {
$flag = PluginFusioninventoryTaskjoblog::TASK_INFO;
$message = json_encode($a_values, JSON_UNESCAPED_SLASHES);
} else {
$flag = PluginFusioninventoryTaskjoblog::TASK_ERROR;
$message = __('Path not found', 'fusioninventory');
}
$pfTaskjoblog->addTaskjoblog($jobstate['id'],
$jobstate['items_id'],
$jobstate['itemtype'],
$flag,
$message);
}
break;
case 'jobsDone':
$jobstate = current($pfTaskjobstate->find(
[
'uniqid' => $uuid,
'state' => ['!=', PluginFusioninventoryTaskjobstate::FINISHED]
],
[],
1)
);
$pfTaskjobstate->changeStatusFinish(
$jobstate['id'],
$jobstate['items_id'],
$jobstate['itemtype']
);
break;
}
return $response;
}
/**
* After purge item, delete collect data
*/
function post_purgeItem() {
// Delete all registry
$pfCollect_Registry = new PluginFusioninventoryCollect_Registry();
$items = $pfCollect_Registry->find(['plugin_fusioninventory_collects_id' => $this->fields['id']]);
foreach ($items as $item) {
$pfCollect_Registry->delete(['id' => $item['id']], true);
}
// Delete all WMI
$pfCollect_Wmi = new PluginFusioninventoryCollect_Wmi();
$items = $pfCollect_Wmi->find(['plugin_fusioninventory_collects_id' => $this->fields['id']]);
foreach ($items as $item) {
$pfCollect_Wmi->delete(['id' => $item['id']], true);
}
// Delete all File
$pfCollect_File = new PluginFusioninventoryCollect_File();
$items = $pfCollect_File->find(['plugin_fusioninventory_collects_id' => $this->fields['id']]);
foreach ($items as $item) {
$pfCollect_File->delete(['id' => $item['id']], true);
}
parent::post_deleteItem();
}
}

View File

@@ -0,0 +1,225 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage file collect of agent
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the files to search in collect module.
*/
class PluginFusioninventoryCollect_File extends PluginFusioninventoryCollectCommon {
public $type = 'file';
/**
* Get name of this type by language of the user connected
*
* @param integer $nb number of elements
* @return string name of this type
*/
static function getTypeName($nb = 0) {
return _n('Found file', 'Found files', $nb, 'fusioninventory');
}
function getListHeaders() {
return [
__("Name"),
__("Limit", "fusioninventory"),
__("Folder", "fusioninventory"),
__("Recursive", "fusioninventory"),
__("Regex", "fusioninventory"),
__("Size", "fusioninventory"),
__("Checksum SHA512", "fusioninventory"),
__("Checksum SHA2", "fusioninventory"),
__("Name", "fusioninventory"),
__("Iname", "fusioninventory"),
__("Type", "fusioninventory"),
__("Action")
];
}
function displayOneRow($row = []) {
$filter = $type = '';
if (!empty($row['filter_sizeequals'])) {
$filter = '= '.$row['filter_sizeequals'];
} else if (!empty($row['filter_sizegreater'])) {
$filer = '> '.$row['filter_sizegreater'];
} else if (!empty($row['filter_sizelower'])) {
$filter = '< '.$row['filter_sizelower'];
}
if ($row['filter_is_file'] == 1) {
$type = __('File', 'fusioninventory');
} else {
$type = __('Folder', 'fusioninventory');
}
return [
$row['name'],
$row['limit'],
$row['dir'],
$row['is_recursive'],
$row['filter_regex'],
$filter,
$row['filter_checksumsha512'],
$row['filter_checksumsha2'],
$row['filter_name'],
$row['filter_iname'],
$type
];
}
function displayNewSpecificities() {
echo "<td>".__('Limit', 'fusioninventory')."</td>";
echo "<td>";
Dropdown::showNumber('limit', [
'min' => 1,
'max' => 100,
'value' => 5
]
);
echo "</td>";
echo "</tr>\n";
echo "<tr class='tab_bg_1'>";
echo "<th colspan='4'>";
echo _n('Filter', 'Filters', 2, 'fusioninventory');
echo "</th>";
echo "</tr>\n";
echo "<tr class='tab_bg_1'>";
echo "<td>";
echo __('Base folder', 'fusioninventory');
echo "</td>";
echo "<td>";
echo "<input type='text' name='dir' value='/' size='50' />";
echo "</td>";
echo "<td>";
echo __('Folder recursive', 'fusioninventory');
echo "</td>";
echo "<td>";
Dropdown::showYesNo('is_recursive', 1);
echo "</td>";
echo "</tr>\n";
echo "<tr class='tab_bg_1'>";
echo "<td>";
echo __('Regex', 'fusioninventory');
echo "</td>";
echo "<td>";
echo "<input type='text' name='filter_regex' value='' size='50' />";
echo "</td>";
echo "<td>";
echo __('Size', 'fusioninventory');
echo "</td>";
echo "<td>";
Dropdown::showFromArray('sizetype', [
'none' => __('Disabled', 'fusioninventory'),
'equals' => '=',
'greater' => '>',
'lower' => '<'
]
);
echo "<input type='text' name='size' value='' />";
echo "</td>";
echo "</tr>\n";
echo "<tr class='tab_bg_1'>";
echo "<td>";
echo __('Checksum SHA512', 'fusioninventory');
echo "</td>";
echo "<td>";
echo "<input type='text' name='filter_checksumsha512' value='' />";
echo "</td>";
echo "<td>";
echo __('Checksum SHA2', 'fusioninventory');
echo "</td>";
echo "<td>";
echo "<input type='text' name='filter_checksumsha2' value='' />";
echo "</td>";
echo "</tr>\n";
echo "<tr class='tab_bg_1'>";
echo "<td>";
echo __('Filename', 'fusioninventory');
echo "</td>";
echo "<td>";
Dropdown::showFromArray('filter_nametype', [
'none' => __('Disabled', 'fusioninventory'),
'name' => __('Non sentitive case', 'fusioninventory'),
'iname' => __('Sentitive case', 'fusioninventory')
]
);
echo "<input type='text' name='filter_name' value='' />";
echo "</td>";
echo "<td>";
echo __('Type', 'fusioninventory');
echo "</td>";
echo "<td>";
Dropdown::showFromArray('type', [
'file' => __('File', 'fusioninventory'),
'dir' => __('Folder', 'fusioninventory')
]
);
echo "</td>";
}
/**
* After purge item, delete collect files
*/
function post_purgeItem() {
// Delete all File
$pfCollectFileContent = new PluginFusioninventoryCollect_File_Content();
$items = $pfCollectFileContent->find(['plugin_fusioninventory_collects_files_id' => $this->fields['id']]);
foreach ($items as $item) {
$pfCollectFileContent->delete(['id' => $item['id']], true);
}
parent::post_deleteItem();
}
}

View File

@@ -0,0 +1,173 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the files found on computr by agent and
* linked to the computer
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the files found by the collect module of agent.
*/
class PluginFusioninventoryCollect_File_Content
extends PluginFusioninventoryCollectContentCommon {
public $collect_itemtype = 'PluginFusioninventoryCollect_File';
public $collect_table = 'glpi_plugin_fusioninventory_collects_files';
public $type = 'file';
/**
* Update computer files (add and update files) related to this
* collect file id
*
* @global object $DB
* @param integer $computers_id id of the computer
* @param integer $collects_files_id id of collect_file
* @param integer $taskjobstates_id id of taskjobstate
*/
function updateComputer($computers_id, $file_data, $collects_files_id) {
foreach ($file_data as $key => $value) {
$input = [
'computers_id' => $computers_id,
'plugin_fusioninventory_collects_files_id' => $collects_files_id,
'pathfile' => str_replace(['\\', '//'], ['/', '/'], $value['path']),
'size' => $value['size']
];
$this->add($input);
}
}
/**
* Display files found on the computer
*
* @param integer $computers_id id of the computer
*/
function showForComputer($computers_id) {
$pfCollect_File = new PluginFusioninventoryCollect_File();
echo "<table class='tab_cadre_fixe'>";
$a_data = $this->find(['computers_id' => $computers_id],
['plugin_fusioninventory_collects_files_id', 'pathfile']);
$previous_key = 0;
foreach ($a_data as $data) {
$pfCollect_File->getFromDB($data['plugin_fusioninventory_collects_files_id']);
if ($previous_key != $data['plugin_fusioninventory_collects_files_id']) {
echo "<tr class='tab_bg_1'>";
echo '<th colspan="3">';
echo $pfCollect_File->fields['name']. ": ".$pfCollect_File->fields['dir'];
echo '</th>';
echo '</tr>';
echo "<tr>";
echo "<th>".__('Path/file', 'fusioninventory')."</th>";
echo "<th>".__('Size', 'fusioninventory')."</th>";
echo "</tr>";
$previous_key = $data['plugin_fusioninventory_collects_files_id'];
}
echo "<tr class='tab_bg_1'>";
echo '<td>';
echo $data['pathfile'];
echo '</td>';
echo '<td>';
echo Toolbox::getSize($data['size']);
echo '</td>';
echo "</tr>";
}
echo '</table>';
}
/**
* Display all files found on all computers related to the collect file
*
* @param integer $collects_files_id id of collect_file
*/
function showContent($collects_files_id) {
$pfCollect_File = new PluginFusioninventoryCollect_File();
$computer = new Computer();
$pfCollect_File->getFromDB($collects_files_id);
echo "<table class='tab_cadre_fixe'>";
echo "<tr>";
echo "<th colspan='3'>";
echo $pfCollect_File->fields['name'];
echo "</th>";
echo "</tr>";
echo "<tr>";
echo "<th>".__('Computer')."</th>";
echo "<th>".__('pathfile', 'fusioninventory')."</th>";
echo "<th>".__('Size', 'fusioninventory')."</th>";
echo "</tr>";
$a_data = $this->find(['plugin_fusioninventory_collects_files_id' => $collects_files_id],
['pathfile']);
foreach ($a_data as $data) {
echo "<tr class='tab_bg_1'>";
echo '<td>';
$computer->getFromDB($data['computers_id']);
echo $computer->getLink(1);
echo '</td>';
echo '<td>';
echo $data['pathfile'];
echo '</td>';
echo '<td>';
echo Toolbox::getSize($data['size']);
echo '</td>';
echo "</tr>";
}
echo '</table>';
}
}

View File

@@ -0,0 +1,123 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the windows registry collect on agent
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the windows registry to get in collect module.
*/
class PluginFusioninventoryCollect_Registry extends PluginFusioninventoryCollectCommon {
public $type = 'registry';
/**
* Get name of this type by language of the user connected
*
* @param integer $nb number of elements
* @return string name of this type
*/
static function getTypeName($nb = 0) {
return _n('Found entry', 'Found entries', $nb, 'fusioninventory');
}
/**
* Get Hives of the registry
*
* @return array list of hives
*/
static function getHives() {
return [
"HKEY_LOCAL_MACHINE" => "HKEY_LOCAL_MACHINE",
];
}
function getListHeaders() {
return [
__('Name'),
__('Hive', 'fusioninventory'),
__("Path", "fusioninventory"),
__("Key", "fusioninventory"),
__("Action")
];
}
function displayOneRow($row = []) {
return [
$row['name'],
$row['hive'],
$row['path'],
$row['key']
];
}
function displayNewSpecificities() {
echo "<td>".__('Hive', 'fusioninventory')."</td>";
echo "<td>";
Dropdown::showFromArray('hive',
PluginFusioninventoryCollect_Registry::getHives());
echo "</td>";
echo "</tr>\n";
echo "<tr class='tab_bg_1'>";
echo "<td>";
echo __('Path', 'fusioninventory');
echo "</td>";
echo "<td>";
echo "<input type='text' name='path' value='' size='80' />";
echo "</td>";
echo "<td>";
echo __('Key', 'fusioninventory');
echo "</td>";
echo "<td>";
echo "<input type='text' name='key' value='' />";
echo "</td>";
}
}

View File

@@ -0,0 +1,242 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the windows registry keys found by agent and
* linked to the computer
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the registry keys found by the collect module of agent.
*/
class PluginFusioninventoryCollect_Registry_Content extends PluginFusioninventoryCollectContentCommon {
public $collect_itemtype = 'PluginFusioninventoryCollect_Registry';
public $collect_table = 'glpi_plugin_fusioninventory_collects_registries';
public $type = 'registry';
/**
* Get the tab name used for item
*
* @param object $item the item object
* @param integer $withtemplate 1 if is a template form
* @return string name of the tab
*/
function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) {
if ($item->fields['id'] > 0) {
if (get_class($item) == 'PluginFusioninventoryCollect') {
if ($item->fields['type'] == 'registry') {
$a_colregs = getAllDataFromTable('glpi_plugin_fusioninventory_collects_registries',
['plugin_fusioninventory_collects_id' => $item->fields['id']]);
if (count($a_colregs) == 0) {
return '';
}
$in = array_keys($a_colregs);
if (countElementsInTable('glpi_plugin_fusioninventory_collects_registries_contents',
['plugin_fusioninventory_collects_registries_id' => $in]) > 0) {
return __('Windows registry content', 'fusioninventory');
}
}
}
}
return '';
}
/**
* Update computer registry values (add and update) related to this
* collect registry id
*
* @global object $DB
* @param integer $computers_id id of the computer
* @param array $registry_data registry info sent by agent
* @param integer $collects_registries_id id of collect_registry
*/
function updateComputer($computers_id, $registry_data, $collects_registries_id) {
global $DB;
$db_registries = [];
$query = "SELECT `id`, `key`, `value`
FROM `glpi_plugin_fusioninventory_collects_registries_contents`
WHERE `computers_id` = '".$computers_id."'
AND `plugin_fusioninventory_collects_registries_id` =
'".$collects_registries_id."'";
$result = $DB->query($query);
while ($data = $DB->fetchAssoc($result)) {
$idtmp = $data['id'];
unset($data['id']);
$data1 = Toolbox::addslashes_deep($data);
$db_registries[$idtmp] = $data1;
}
unset($registry_data['_sid']);
foreach ($registry_data as $key => $value) {
foreach ($db_registries as $keydb => $arraydb) {
if ($arraydb['key'] == $key) {
$input = ['key' => $arraydb['key'],
'id' => $keydb,
'value' => $value];
$this->update($input);
unset($registry_data[$key]);
unset($db_registries[$keydb]);
break;
}
}
}
foreach ($db_registries as $id => $data) {
$this->delete(['id' => $id], true);
}
foreach ($registry_data as $key => $value) {
if (preg_match("/^0x[0-9a-fA-F]{1,}$/", $value)) {
$value = hexdec($value);
}
$input = [
'computers_id' => $computers_id,
'plugin_fusioninventory_collects_registries_id' => $collects_registries_id,
'key' => $key,
'value' => $value
];
$this->add($input);
}
}
/**
* Show registries keys of the computer
*
* @param integer $computers_id id of the computer
*/
function showForComputer($computers_id) {
$pfCollect_Registry = new PluginFusioninventoryCollect_Registry();
echo "<table class='tab_cadre_fixe'>";
$a_data = $this->find(['computers_id' => $computers_id],
['plugin_fusioninventory_collects_registries_id', 'key']);
$previous_key = 0;
foreach ($a_data as $data) {
$pfCollect_Registry->getFromDB($data['plugin_fusioninventory_collects_registries_id']);
if ($previous_key != $data['plugin_fusioninventory_collects_registries_id']) {
echo "<tr class='tab_bg_1'>";
echo '<th colspan="3">';
echo $pfCollect_Registry->fields['name'];
echo '</th>';
echo '</tr>';
echo "<tr>";
echo "<th>".__('Path', 'fusioninventory')."</th>";
echo "<th>".__('Value', 'fusioninventory')."</th>";
echo "<th>".__('Data', 'fusioninventory')."</th>";
echo "</tr>";
$previous_key = $data['plugin_fusioninventory_collects_registries_id'];
}
echo "<tr class='tab_bg_1'>";
echo '<td>';
echo $pfCollect_Registry->fields['hive'].
$pfCollect_Registry->fields['path'];
echo '</td>';
echo '<td>';
echo $data['key'];
echo '</td>';
echo '<td>';
echo $data['value'];
echo '</td>';
echo "</tr>";
}
echo '</table>';
}
/**
* Display registry keys / values of collect_registry id
*
* @param integer $collects_registries_id
*/
function showContent($collects_registries_id) {
$pfCollect_Registry = new PluginFusioninventoryCollect_Registry();
$computer = new Computer();
$pfCollect_Registry->getFromDB($collects_registries_id);
echo "<table class='tab_cadre_fixe'>";
echo "<tr>";
echo "<th colspan='3'>";
echo $pfCollect_Registry->fields['hive'].
$pfCollect_Registry->fields['path'];
echo "</th>";
echo "</tr>";
echo "<tr>";
echo "<th>".__('Computer')."</th>";
echo "<th>".__('Value', 'fusioninventory')."</th>";
echo "<th>".__('Data', 'fusioninventory')."</th>";
echo "</tr>";
$a_data = $this->find(['plugin_fusioninventory_collects_registries_id' => $collects_registries_id],
['key']);
foreach ($a_data as $data) {
echo "<tr class='tab_bg_1'>";
echo '<td>';
$computer->getFromDB($data['computers_id']);
echo $computer->getLink(1);
echo '</td>';
echo '<td>';
echo $data['key'];
echo '</td>';
echo '<td>';
echo $data['value'];
echo '</td>';
echo "</tr>";
}
echo '</table>';
}
}

View File

@@ -0,0 +1,108 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the wmi by the agent
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the wmi to get in collect module.
*/
class PluginFusioninventoryCollect_Wmi extends PluginFusioninventoryCollectCommon {
public $type = 'wmi';
/**
* Get name of this type by language of the user connected
*
* @param integer $nb number of elements
* @return string name of this type
*/
static function getTypeName($nb = 0) {
return _n('Found WMI', 'Found WMIs', $nb, 'fusioninventory');
}
function getListHeaders() {
return [
__("Name"),
__("Moniker", "fusioninventory"),
__("Class", "fusioninventory"),
__("Properties", "fusioninventory"),
__("Action")
];
}
function displayOneRow($row = []) {
return [
$row['name'],
$row['moniker'],
$row['class'],
$row['properties']
];
}
function displayNewSpecificities() {
echo "<td>".__('moniker', 'fusioninventory')."</td>";
echo "<td>";
echo "<input type='text' name='moniker' value='' size='50' />";
echo "</td>";
echo "</tr>\n";
echo "<tr class='tab_bg_1'>";
echo "<td>";
echo __('Class', 'fusioninventory');
echo "</td>";
echo "<td>";
echo "<input type='text' name='class' value='' />";
echo "</td>";
echo "<td>";
echo __('Properties', 'fusioninventory');
echo "</td>";
echo "<td>";
echo "<input type='text' name='properties' value='' size='50' />";
echo "</td>";
}
}

View File

@@ -0,0 +1,233 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the wmi content found by agent and linked
* to the computer
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the wmi information found by the collect module of agent.
*/
class PluginFusioninventoryCollect_Wmi_Content
extends PluginFusioninventoryCollectContentCommon {
public $collect_itemtype = 'PluginFusioninventoryCollect_Wmi';
public $collect_table = 'glpi_plugin_fusioninventory_collects_wmis';
public $type = 'wmi';
/**
* Get the tab name used for item
*
* @param object $item the item object
* @param integer $withtemplate 1 if is a template form
* @return string name of the tab
*/ /*
function getTabNameForItem(CommonGLPI $item, $withtemplate=0) {
if ($item->getID() > 0) {
if (get_class($item) == 'PluginFusioninventoryCollect') {
if ($item->fields['type'] == 'wmi') {
$a_colregs = getAllDataFromTable('glpi_plugin_fusioninventory_collects_wmis',
"`plugin_fusioninventory_collects_id`='".$item->getID()."'");
if (count($a_colregs) == 0) {
return '';
}
$in = array_keys($a_colregs);
if (countElementsInTable('glpi_plugin_fusioninventory_collects_wmis_contents',
"`plugin_fusioninventory_collects_wmis_id` IN ('".implode("','", $in)."')") > 0) {
return __('Windows WMI content', 'fusioninventory');
}
}
}
}
return '';
}*/
/**
* update wmi data to compute (add and update) with data sent by the agent
*
* @global object $DB
* @param integer $computers_id id of the computer
* @param array $wmi_data
* @param integer $collects_wmis_id
*/
function updateComputer($computers_id, $wmi_data, $collects_wmis_id) {
global $DB;
$db_wmis = [];
$query = "SELECT `id`, `property`, `value`
FROM `glpi_plugin_fusioninventory_collects_wmis_contents`
WHERE `computers_id` = '".$computers_id."'
AND `plugin_fusioninventory_collects_wmis_id` =
'".$collects_wmis_id."'";
$result = $DB->query($query);
while ($data = $DB->fetchAssoc($result)) {
$wmi_id = $data['id'];
unset($data['id']);
$data1 = Toolbox::addslashes_deep($data);
$db_wmis[$wmi_id] = $data1;
}
unset($wmi_data['_sid']);
foreach ($wmi_data as $key => $value) {
foreach ($db_wmis as $keydb => $arraydb) {
if ($arraydb['property'] == $key) {
$input = ['property' => $arraydb['property'],
'id' => $keydb,
'value' => $value];
$this->update($input);
unset($wmi_data[$key]);
unset($db_wmis[$keydb]);
break;
}
}
}
foreach ($db_wmis as $id => $data) {
$this->delete(['id' => $id], true);
}
foreach ($wmi_data as $key => $value) {
$input = [
'computers_id' => $computers_id,
'plugin_fusioninventory_collects_wmis_id' => $collects_wmis_id,
'property' => $key,
'value' => $value
];
$this->add($input);
}
}
/**
* Display wmi information of computer
*
* @param integer $computers_id id of computer
*/
function showForComputer($computers_id) {
$pfCollect_Wmi = new PluginFusioninventoryCollect_Wmi();
echo "<table class='tab_cadre_fixe'>";
echo "<tr>";
echo "<th>".__('Moniker', 'fusioninventory')."</th>";
echo "<th>".__('Class', 'fusioninventory')."</th>";
echo "<th>".__('Property', 'fusioninventory')."</th>";
echo "<th>".__('Value', 'fusioninventory')."</th>";
echo "</tr>";
$a_data = $this->find(['computers_id' => $computers_id],
['plugin_fusioninventory_collects_wmis_id', 'property']);
foreach ($a_data as $data) {
echo "<tr class='tab_bg_1'>";
echo '<td>';
$pfCollect_Wmi->getFromDB($data['plugin_fusioninventory_collects_wmis_id']);
echo $pfCollect_Wmi->fields['moniker'];
echo '</td>';
echo '<td>';
echo $pfCollect_Wmi->fields['class'];
echo '</td>';
echo '<td>';
echo $data['property'];
echo '</td>';
echo '<td>';
echo $data['value'];
echo '</td>';
echo "</tr>";
}
echo '</table>';
}
/**
* Display wmi information of collect_wmi_id
*
* @param integer $collects_wmis_id
*/
function showContent($collects_wmis_id) {
$pfCollect_Wmi = new PluginFusioninventoryCollect_Wmi();
$computer = new Computer();
$pfCollect_Wmi->getFromDB($collects_wmis_id);
echo "<table class='tab_cadre_fixe'>";
echo "<tr>";
echo "<th colspan='3'>";
echo $pfCollect_Wmi->fields['class'];
echo "</th>";
echo "</tr>";
echo "<tr>";
echo "<th>".__('Computer')."</th>";
echo "<th>".__('Property', 'fusioninventory')."</th>";
echo "<th>".__('Value', 'fusioninventory')."</th>";
echo "</tr>";
$a_data = $this->find(['plugin_fusioninventory_collects_wmis_id' => $collects_wmis_id],
['property']);
foreach ($a_data as $data) {
echo "<tr class='tab_bg_1'>";
echo '<td>';
$computer->getFromDB($data['computers_id']);
echo $computer->getLink(1);
echo '</td>';
echo '<td>';
echo $data['property'];
echo '</td>';
echo '<td>';
echo $data['value'];
echo '</td>';
echo "</tr>";
}
echo '</table>';
}
}

View File

@@ -0,0 +1,236 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the windows registry collect on agent
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the windows registry to get in collect module.
*/
class PluginFusioninventoryCollectCommon extends CommonDBTM {
/**
* The right name for this class
*
* @var string
*/
static $rightname = 'plugin_fusioninventory_collect';
public $type = '';
/**
* Get name of this type by language of the user connected
*
* @param integer $nb number of elements
* @return string name of this type
*/
static function getTypeName($nb = 0) {
return '';
}
/**
* Get the tab name used for item
*
* @param object $item the item object
* @param integer $withtemplate 1 if is a template form
* @return string name of the tab
*/
function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) {
if ($item->fields['id'] > 0) {
if ($item->fields['type'] == $this->type) {
return __('Collect configuration');
}
}
return '';
}
/**
* Display the content of the tab
*
* @param object $item
* @param integer $tabnum number of the tab to display
* @param integer $withtemplate 1 if is a template form
* @return boolean
*/
static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) {
$class = get_called_class();
$pfCollect = new $class();
$pfCollect->showList($item->fields['id']);
$pfCollect->showForm($item->fields['id']);
return true;
}
/**
* Get headers to be displayed, as an array
* @since 9.2+2.0
*
* @return array a list of header labels to be displayed
*/
function getListHeaders() {
return [
__('Name')
];
}
/**
* Get values for a row to display in the list
* @since 9.2+2.0
*
* @param array $row the row data to be displayed
* @return array values to be display
*/
function displayOneRow($row = []) {
return [
$row['name']
];
}
/**
* Display registries defined in collect
*
* @param integer $collects_id id of collect
*/
function showList($collects_id) {
global $DB;
$params = [
'FROM' => $this->getTable(),
'WHERE' => ['plugin_fusioninventory_collects_id' => $collects_id]
];
$iterator = $DB->request($params);
$class = get_called_class();
$headers = $this->getListHeaders();
echo "<div class='spaced'>";
echo "<table class='tab_cadre_fixe'>";
echo "<tr>";
echo "<th colspan=".count($headers).">"
.__('Windows registry associated', 'fusioninventory')."</th>";
echo "</tr>";
echo "<tr>";
foreach ($headers as $label) {
echo "<th>".$label."</th>";
}
echo "</tr>";
while ($data = $iterator->next()) {
echo "<tr>";
$row_data = $this->displayOneRow($data);
foreach ($row_data as $value) {
echo "<td align='center'>$value</td>";
}
echo "<td align='center'>";
echo "<form name='form_bundle_item' action='".$class::getFormURL().
"' method='post'>";
echo Html::hidden('id', ['value' => $data['id']]);
echo "<input type='image' name='delete' src='../pics/drop.png'>";
Html::closeForm();
echo "</td>";
echo "</tr>";
}
echo "</table>";
echo "</div>";
}
function displayNewSpecificities() {
}
/**
* Display form to add registry
*
* @param integer $collects_id id of collect
* @param array $options
* @return true
*/
function showForm($collects_id, $options = []) {
$this->initForm(0, $options);
$this->showFormHeader($options);
echo "<tr class='tab_bg_1'>";
echo "<td>";
echo __('Name');
echo "</td>";
echo "<td>";
echo Html::hidden('plugin_fusioninventory_collects_id',
['value' => $collects_id]);
Html::autocompletionTextField($this, 'name');
echo "</td>";
$this->displayNewSpecificities();
echo "</tr>\n";
$this->showFormButtons($options);
return true;
}
function rawSearchOptions() {
$tab = [];
$tab[] = [
'id' => 'common',
'name' => __('Characteristics')
];
$tab[] = [
'id' => '1',
'table' => $this->getTable(),
'field' => 'name',
'name' => __('Name'),
'datatype' => 'itemlink',
'autocomplete' => true,
];
return $tab;
}
}

View File

@@ -0,0 +1,180 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the files found on computr by agent and
* linked to the computer
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the files found by the collect module of agent.
*/
class PluginFusioninventoryCollectContentCommon extends CommonDBTM {
/**
* The right name for this class
*
* @var string
*/
static $rightname = 'plugin_fusioninventory_collect';
public $collect_itemtype = '';
public $collect_table = '';
public $type = '';
/**
* Get name of this type by language of the user connected
*
* @param integer $nb number of elements
* @return string name of this type
*/
static function getTypeName($nb = 0) {
$class = get_called_class();
return $class::getTypeName();
}
/**
* Get the collect associated with the content class
* @since 9.2+2.0
*
* @return string the collect class name
*/
function getCollectClass() {
$class = get_called_class();
$item = new $class();
return $item->collect_itemtype;
}
/**
* Display the content of the tab
*
* @param object $item
* @param integer $tabnum number of the tab to display
* @param integer $withtemplate 1 if is a template form
* @return boolean
*/
static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) {
$class = get_called_class();
$pfCollectContent = new $class();
switch (get_class($item)) {
case 'PluginFusioninventoryCollect':
$pfCollectContent->showForCollect($item->fields['id']);
break;
}
return true;
}
/**
* Get the tab name used for item
*
* @param object $item the item object
* @param integer $withtemplate 1 if is a template form
* @return string name of the tab
*/
function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) {
if ($item->fields['id'] > 0) {
$class = $this->collect_itemtype;
$collect = $this->getCollectClass();
switch (get_class($item)) {
case 'PluginFusioninventoryCollect':
if ($item->fields['type'] == $this->type) {
$a_colfiles = getAllDataFromTable($collect::getTable(),
['plugin_fusioninventory_collects_id' => $item->fields['id']]);
if (count($a_colfiles) == 0) {
return '';
}
$in = array_keys($a_colfiles);
$fk = getForeignKeyFieldForItemType($collect);
if ($nb = countElementsInTable($this->getTable(),
[$fk => $in]) > 0) {
return self::createTabEntry($collect::getTypeName(Session::getPluralNumber()), $nb);
}
}
break;
}
}
return '';
}
/**
* Delete all contents linked to the computer (most cases when delete a
* computer)
*
* @param integer $computers_id
*/
static function cleanComputer($computers_id) {
$classname = get_called_class();
$content = new $classname();
$content->deleteByCriteria(['computers_id' => $computers_id]);
}
/**
* Show all files defined
*
* @param integer $collects_id id of collect
*/
function showForCollect($collects_id) {
global $DB;
$class = $this->collect_itemtype;
$params = [
'FROM' => $class::getTable(),
'FIELDS' => [
'id'
],
'WHERE' => [
'plugin_fusioninventory_collects_id' => $collects_id
]
];
$iterator = $DB->request($params);
while ($data = $iterator->next()) {
$this->showContent($data['id']);
}
}
function showContent($id) {
}
}

View File

@@ -0,0 +1,289 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the collect rules.
* The goal is to fill inventory with collect information.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Rules for collect information.
* The goal is to fill inventory with collect information.
*/
class PluginFusioninventoryCollectRule extends Rule {
/**
* The right name for this class
*
* @var string
*/
static $rightname = "plugin_fusioninventory_rulecollect";
/**
* Set these rules can be sorted
*
* @var boolean
*/
public $can_sort=true;
/**
* Set these rules not have specific parameters
*
* @var boolean
*/
public $specific_parameters = false;
/**
* Get name of this type by language of the user connected
*
* @return string name of this type
*/
function getTitle() {
return __('Computer information rules', 'fusioninventory');
}
/**
* Make some changes before process review result
*
* @param array $output
* @return array
*/
function preProcessPreviewResults($output) {
return $output;
}
/**
* Define maximum number of actions possible in a rule
*
* @return integer
*/
function maxActionsCount() {
return 8;
}
/**
* Code execution of actions of the rule
*
* @param array $output
* @param array $params
* @return array
*/
function executeActions($output, $params, array $input = []) {
PluginFusioninventoryToolbox::logIfExtradebug(
"pluginFusioninventory-rules-collect",
"execute actions, data:\n". print_r($output, true). "\n" . print_r($params, true)
);
PluginFusioninventoryToolbox::logIfExtradebug(
"pluginFusioninventory-rules-collect",
"execute actions: ". count($this->actions) ."\n"
);
if (count($this->actions)) {
foreach ($this->actions as $action) {
PluginFusioninventoryToolbox::logIfExtradebug(
"pluginFusioninventory-rules-collect",
"- action: ". $action->fields["action_type"] ." for: ". $action->fields["field"] ."\n"
);
switch ($action->fields["action_type"]) {
case "assign" :
PluginFusioninventoryToolbox::logIfExtradebug(
"pluginFusioninventory-rules-collect",
"- value ".$action->fields["value"]."\n"
);
$output[$action->fields["field"]] = $action->fields["value"];
break;
case "regex_result" :
//Regex result : assign value from the regex
$res = "";
if (isset($this->regex_results[0])) {
PluginFusioninventoryToolbox::logIfExtradebug(
"pluginFusioninventory-rules-collect",
"- regex ".print_r($this->regex_results[0], true)."\n"
);
$res .= RuleAction::getRegexResultById($action->fields["value"],
$this->regex_results[0]);
PluginFusioninventoryToolbox::logIfExtradebug(
"pluginFusioninventory-rules-collect",
"- regex result: ".$res."\n"
);
} else {
$res .= $action->fields["value"];
}
if ($res != ''
&& ($action->fields["field"] != 'user'
&& $action->fields["field"] != 'otherserial'
&& $action->fields["field"] != 'software'
&& $action->fields["field"] != 'softwareversion')) {
$entities_id = 0;
if (isset($_SESSION["plugin_fusioninventory_entity"])) {
$entities_id = $_SESSION["plugin_fusioninventory_entity"];
}
$res = Dropdown::importExternal(getItemtypeForForeignKeyField($action->fields['field']), $res, $entities_id);
}
PluginFusioninventoryToolbox::logIfExtradebug(
"pluginFusioninventory-rules-collect",
"- value ".$res."\n"
);
$output[$action->fields["field"]] = $res;
break;
default:
//plugins actions
$executeaction = clone $this;
$output = $executeaction->executePluginsActions($action, $output, $params);
break;
}
}
}
return $output;
}
/**
* Get the criteria available for the rule
*
* @return array
*/
function getCriterias() {
$criterias = [];
$criterias['regkey']['field'] = 'name';
$criterias['regkey']['name'] = __('Registry key', 'fusioninventory');
$criterias['regkey']['table'] = 'glpi_plugin_fusioninventory_collects_registries';
$criterias['regvalue']['field'] = 'name';
$criterias['regvalue']['name'] = __('Registry value', 'fusioninventory');
$criterias['wmiproperty']['field'] = 'name';
$criterias['wmiproperty']['name'] = __('WMI property', 'fusioninventory');
$criterias['wmiproperty']['table'] = 'glpi_plugin_fusioninventory_collects_wmis';
$criterias['wmivalue']['field'] = 'name';
$criterias['wmivalue']['name'] = __('WMI value', 'fusioninventory');
$criterias['filename']['field'] = 'name';
$criterias['filename']['name'] = __('File name', 'fusioninventory');
$criterias['filepath']['field'] = 'name';
$criterias['filepath']['name'] = __('File path', 'fusioninventory');
$criterias['filesize']['field'] = 'name';
$criterias['filesize']['name'] = __('File size', 'fusioninventory');
return $criterias;
}
/**
* Get the actions available for the rule
*
* @return array
*/
function getActions() {
$actions = [];
$actions['computertypes_id']['name'] = __('Type');
$actions['computertypes_id']['type'] = 'dropdown';
$actions['computertypes_id']['table'] = 'glpi_computertypes';
$actions['computertypes_id']['force_actions'] = ['assign', 'regex_result'];
$actions['computermodels_id']['name'] = __('Model');
$actions['computermodels_id']['type'] = 'dropdown';
$actions['computermodels_id']['table'] = 'glpi_computermodels';
$actions['computermodels_id']['force_actions'] = ['assign', 'regex_result'];
$actions['operatingsystems_id']['name'] = OperatingSystem::getTypeName(1);
$actions['operatingsystems_id']['type'] = 'dropdown';
$actions['operatingsystems_id']['table'] = 'glpi_operatingsystems';
$actions['operatingsystems_id']['force_actions'] = ['assign', 'regex_result'];
$actions['operatingsystemversions_id']['name'] = _n('Version of the operating system', 'Versions of the operating system', 1);
$actions['operatingsystemversions_id']['type'] = 'dropdown';
$actions['operatingsystemversions_id']['table'] = 'glpi_operatingsystemversions';
$actions['operatingsystemversions_id']['force_actions'] = ['assign', 'regex_result'];
$actions['user']['name'] = __('User');
$actions['user']['force_actions'] = ['assign', 'regex_result'];
$actions['locations_id']['name'] = __('Location');
$actions['locations_id']['type'] = 'dropdown';
$actions['locations_id']['table'] = 'glpi_locations';
$actions['locations_id']['force_actions'] = ['assign', 'regex_result'];
$actions['states_id']['name'] = __('Status');
$actions['states_id']['type'] = 'dropdown';
$actions['states_id']['table'] = 'glpi_states';
$actions['states_id']['force_actions'] = ['assign', 'regex_result'];
$actions['software']['name'] = __('Software');
$actions['software']['force_actions'] = ['assign', 'regex_result'];
$actions['softwareversion']['name'] = __('Software version', 'fusioninventory');
$actions['softwareversion']['force_actions'] = ['assign', 'regex_result'];
$actions['otherserial']['name'] = __('Inventory number');
$actions['otherserial']['force_actions'] = ['assign', 'regex_result'];
$actions['comment']['name'] = _n('Comment', 'Comments', 2);
$actions['comment']['force_actions'] = ['assign', 'regex_result'];
return $actions;
}
}

View File

@@ -0,0 +1,98 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage collect collection rule
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage collect rule collection.
*/
class PluginFusioninventoryCollectRuleCollection extends RuleCollection {
/**
* The right name for this class
*
* @var string
*/
static $rightname = "plugin_fusioninventory_rulecollect";
/**
* Set we check all rules
*
* @var boolean
*/
public $stop_on_first_match=false;
/**
* Set the menu option name
*
* @var string
*/
public $menu_option='test';
/**
* Get name of this type by language of the user connected
*
* @return string name of this type
*/
function getTitle() {
return __('Computer information rules', 'fusioninventory');
}
/**
* Prepare input data for process the rule
*
* @param array $input
* @param array $params
* @return array
*/
function prepareInputDataForProcess($input, $params) {
return $input;
}
}

View File

@@ -0,0 +1,334 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to display elements in the plugin.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author Kevin Roy
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* It's a common code for display information in GLPI.
*/
class PluginFusioninventoryCommonView extends CommonDBTM {
/**
* Define the number for the message information constant
*
* @var interger
*/
const MSG_INFO = 0;
/**
* Define the number for the message warning constant
*
* @var interger
*/
const MSG_WARNING = 1;
/**
* Define the number for the message error constant
*
* @var interger
*/
const MSG_ERROR = 2;
/**
* Define default value for the base URLs
*
* @var array
*/
public $base_urls = [];
/**
* __contruct function and the different base URLs
*
* @global array $CFG_GLPI
*/
public function __construct() {
global $CFG_GLPI;
parent::__construct();
$fi_path = Plugin::getWebDir('fusioninventory');
$this->base_urls = [
'fi.base' => $fi_path,
'fi.ajax' => $fi_path . "/ajax",
'fi.front' => $fi_path . "/front",
'fi.pics' => $fi_path . "/pics",
'glpi.pics' => $CFG_GLPI['root_doc'] . "/pics",
];
}
/**
* Get a specific url root by type name
*
* @param string $name the type of url requested (can be used for ajax call
* or pictures location)
* @return string the requested url if found otherwise empty string
*/
function getBaseUrlFor($name) {
if (array_key_exists($name, $this->base_urls)) {
return $this->base_urls[$name];
}
trigger_error(
"The requested url type '$name' doesn't exists. ".
"Maybe the developper have forgotten to register it in the 'base_urls' variable.");
return "";
}
/**
* Show Search list for this itemtype
*/
public function showList() {
Search::show(get_class($this));
}
/**
* Display input form element
*
* @param string $title
* @param string $varname
*/
public function showTextField($title, $varname) {
echo "<label>".$title."&nbsp;:</label>";
echo "<div class='input_wrap'>";
Html::autocompletionTextField ($this, $varname, $this->fields['name']);
echo "</div>";
}
/**
* Display input form element only with numbers
*
* @param string $title
* @param string $varname
* @param array $options
*/
public function showIntegerField($title, $varname, $options = []) {
echo "<label>".$title."&nbsp;:</label>";
echo "<div class='input_wrap'>";
Dropdown::showNumber($varname, $options);
echo "</div>";
}
/**
* Display checkbox form element
*
* @param string $title
* @param string $varname
* @param array $options
*/
public function showCheckboxField($title, $varname, $options = []) {
echo "<label>" . $title."&nbsp;:" . "</label>";
$options['name'] = $varname;
$options['checked'] = $this->fields[$varname];
$options['zero_on_empty']= true;
echo "<div class='input_wrap'>";
Html::showCheckbox($options);
echo "</div>";
}
/**
* Display dropdown form element for itemtype
*
* @param string $title
* @param string $itemtype a glpi/plugin itemtype
* @param array $options
* @return string the rand number can be used with ajax to update something
*/
public function showDropdownForItemtype($title, $itemtype, $options = []) {
echo "<label>" . $title."&nbsp;:" . "</label>";
echo "<div class='input_wrap'>";
$dropdown_options = array_merge(
[
'width'=>'90%',
'display'=>true,
],
$options
);
$rand = Dropdown::show($itemtype, $dropdown_options);
echo "</div>";
return $rand;
}
/**
* Display dropdown form element with array data
*
* @param string $title
* @param string $varname
* @param array $values
* @param array $options
* @return string the rand number can be used with ajax to update something
*/
public function showDropdownFromArray($title, $varname, $values = [], $options = []) {
echo "<label>" . $title."&nbsp;:" . "</label>";
echo "<div class='input_wrap'>";
if (!isset($options['width'])) {
$options['width'] = '100%';
}
if (!is_null($varname)) {
$options['value'] = $this->fields[$varname];
}
$rand = Dropdown::showFromArray(
$varname, $values,
$options
);
echo "</div>";
return $rand;
}
/**
* Display date time select form element
*
* @param string $title
* @param string $varname
* @param array $options
*/
public function showDateTimeField($title, $varname, $options = []) {
// Get datetime value if the object is defined
if ($this->fields['id'] > 0) {
$value = $this->fields[$varname];
} else {
// Else set default value to current date and time
if (array_key_exists('maybeempty', $options)
and $options['maybeempty']) {
$value = "";
} else {
$value = date("Y-m-d H:i:s");
}
}
$options['value'] = $value;
echo "<label>".$title."&nbsp;:</label>";
echo "<div class='input_wrap datetime'>";
Html::showDateTimeField(
$varname,
$options
);
echo "</div>";
}
/**
* Display a text area form element
*
* @param string $title
* @param string $varname
*/
public function showTextArea($title, $varname) {
echo "<label>".$title."&nbsp;:</label>";
echo "<div class='input_wrap'>";
echo
"<textarea class='autogrow' name='".$varname."' >".
$this->fields[$varname].
"</textarea>";
echo "</div>";
echo Html::scriptBlock("$('.autogrow').autogrow();");
}
/**
* Get a HTML message
*
* @param string $msg
* @param integer $type
* @return string
*/
public function getMessage($msg, $type = self::MSG_INFO) {
switch ($type) {
case self::MSG_WARNING:
$msg = __('Warning:', 'fusioninventory') . " $msg";
$class_msg = 'warning';
break;
case self::MSG_ERROR:
$msg = __('Error:', 'fusioninventory') . " $msg";
$class_msg = 'error';
break;
case self::MSG_INFO:
default:
$class_msg = '';
break;
}
return "<div class='box' style='margin-bottom:20px;'>
<div class='box-tleft'>
<div class='box-tright'>
<div class='box-tcenter'></div>
</div>
</div>
<div class='box-mleft'>
<div class='box-mright'>
<div class='box-mcenter'>
<span class='b $class_msg'>$msg</span>
</div>
</div>
</div>
<div class='box-bleft'>
<div class='box-bright'>
<div class='box-bcenter'></div>
</div>
</div>
</div>";
}
}

View File

@@ -0,0 +1,490 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the communication between the plugin and the
* agents.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author Vincent Mazzoni
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage communication with agents using XML
*/
class PluginFusioninventoryCommunication {
/**
* Define message variable
*
* @var SimpleXMLElement
*/
protected $message;
/**
* __contruct function used to initialize protected message variable
*/
function __construct() {
$this->message = new SimpleXMLElement(
"<?xml version='1.0' encoding='UTF-8'?><REPLY></REPLY>"
);
PluginFusioninventoryToolbox::logIfExtradebug(
'pluginFusioninventory-communication',
'New PluginFusioninventoryCommunication object.'
);
}
/**
* Get readable XML message (add carriage returns)
*
* @return object SimpleXMLElement
*/
function getMessage() {
return $this->message;
}
/**
* Set XML message
*
* @param string $message XML in string format
*/
function setMessage($message) {
// avoid xml warnings
$this->message = @simplexml_load_string(
$message, 'SimpleXMLElement',
LIBXML_NOCDATA
);
}
/**
* Send response to agent, using given compression algorithm
*
* @param string $compressmode compressed mode: none|zlib|deflate|gzip
*/
function sendMessage($compressmode = 'none') {
if (!$this->message) {
return;
}
switch ($compressmode) {
case 'none':
header("Content-Type: application/xml");
echo PluginFusioninventoryToolbox::formatXML($this->message);
break;
case 'zlib':
// rfc 1950
header("Content-Type: application/x-compress-zlib");
echo gzcompress(
PluginFusioninventoryToolbox::formatXML($this->message)
);
break;
case 'deflate':
// rfc 1951
header("Content-Type: application/x-compress-deflate");
echo gzdeflate(
PluginFusioninventoryToolbox::formatXML($this->message)
);
break;
case 'gzip':
// rfc 1952
header("Content-Type: application/x-compress-gzip");
echo gzencode(
PluginFusioninventoryToolbox::formatXML($this->message)
);
break;
}
}
/**
* If extra-debug is active, write log
*
* @param string $p_logs log message to write
*/
static function addLog($p_logs) {
if ($_SESSION['glpi_use_mode']==Session::DEBUG_MODE) {
if (PluginFusioninventoryConfig::isExtradebugActive()) {
file_put_contents(GLPI_LOG_DIR.'/pluginFusioninventory-communication.log',
"\n".time().' : '.$p_logs,
FILE_APPEND);
}
}
}
/**
* Import and parse the XML sent by the agent
*
* @param object $arrayinventory SimpleXMLElement
* @return boolean
*/
function import($arrayinventory) {
$pfAgent = new PluginFusioninventoryAgent();
PluginFusioninventoryToolbox::logIfExtradebug(
'pluginFusioninventory-communication',
'Function import().'
);
$this->message = $arrayinventory;
$errors = '';
$xmltag = $this->message['QUERY'];
if ($xmltag == "NETDISCOVERY") {
$xmltag = "NETWORKDISCOVERY";
}
if ($xmltag == "SNMPQUERY"
OR $xmltag == "SNMPINVENTORY") {
$xmltag = "NETWORKINVENTORY";
}
if (!isset($_SESSION['plugin_fusioninventory_agents_id'])) {
$agent = $pfAgent->infoByKey($this->message['DEVICEID']);
} else {
$agent = ['id' => $_SESSION['plugin_fusioninventory_agents_id']];
}
if ($xmltag == "PROLOG") {
return false;
}
if (isset($this->message['CONTENT']['MODULEVERSION'])) {
$pfAgent->setAgentVersions($agent['id'],
$xmltag,
$this->message['CONTENT']['MODULEVERSION']);
} else if (isset($this->message['CONTENT']['VERSIONCLIENT'])) {
$version = str_replace("FusionInventory-Agent_",
"",
$this->message['CONTENT']['VERSIONCLIENT']);
$pfAgent->setAgentVersions($agent['id'], $xmltag, $version);
}
if (isset($this->message->CONTENT->MODULEVERSION)) {
$pfAgent->setAgentVersions($agent['id'],
$xmltag,
(string)$this->message->CONTENT->MODULEVERSION);
} else if (isset($this->message->CONTENT->VERSIONCLIENT)) {
$version = str_replace("FusionInventory-Agent_",
"",
(string)$this->message->CONTENT->VERSIONCLIENT);
$pfAgent->setAgentVersions($agent['id'], $xmltag, $version);
}
if (isset($_SESSION['glpi_plugin_fusioninventory']['xmltags']["$xmltag"])) {
$moduleClass = $_SESSION['glpi_plugin_fusioninventory']['xmltags']["$xmltag"];
$moduleCommunication = new $moduleClass();
$errors.=$moduleCommunication->import($this->message['DEVICEID'],
$this->message['CONTENT'],
$arrayinventory);
} else {
$errors.=__('Unattended element in', 'fusioninventory').' QUERY : *'.$xmltag."*\n";
}
$result=true;
// TODO manage this error ( = delete it)
if ($errors != '') {
echo $errors;
if (isset($_SESSION['glpi_plugin_fusioninventory_processnumber'])) {
$result=true;
} else {
// It's PROLOG
$result=false;
}
}
return $result;
}
/**
* Get all tasks prepared for the agent
*
* @param integer $agent_id id of the agent
*/
function getTaskAgent($agent_id) {
$pfTask = new PluginFusioninventoryTask();
/**
* TODO: the following must be definitely done differently !
* (... but i'm kind in a hurry right now ;-) )
*/
$methods = [];
$classnames = [];
foreach (PluginFusioninventoryStaticmisc::getmethods() as $method) {
if (isset($method['classname'])) {
$methods[] = $method['method'];
$classnames[$method['method']] = $method['classname'];
}
}
$jobstates = $pfTask->getTaskjobstatesForAgent($agent_id, $methods);
foreach ($jobstates as $jobstate) {
$className = $classnames[$jobstate->method];
if (class_exists($className)) {
/*
* TODO: check if use_rest is enabled in Staticmisc::get_methods.
* Also, this get_methods function need to be reviewed
*/
if ($className != "PluginFusioninventoryInventoryComputerESX"
&& $className != "PluginFusioninventoryDeployCommon"
&& $className != "PluginFusioninventoryCollect") {
$class = new $className();
$sxml_temp = $class->run($jobstate);
PluginFusioninventoryToolbox::appendSimplexml(
$this->message, $sxml_temp
);
}
}
}
}
/**
* Set prolog for agent
*/
function addProlog() {
$pfConfig = new PluginFusioninventoryConfig();
$this->message->addChild('PROLOG_FREQ', $pfConfig->getValue("inventory_frequence"));
}
/**
* Order to agent to do inventory if module inventory is activated for the
* agent
*
* @param integer $agents_id id of the agent
*/
function addInventory($agents_id) {
$pfAgentmodule = new PluginFusioninventoryAgentmodule();
if ($pfAgentmodule->isAgentCanDo('INVENTORY', $agents_id)) {
$this->message->addChild('RESPONSE', "SEND");
}
}
/**
* Manage communication with old protocol (XML over POST)
*
**/
/**
* Manage communication with old protocol (XML over POST).
* Used for inventory, network discovery, network inventory and wake on lan
*
* @param string $rawdata data get from agent (compressed or not)
* @param string $xml
* @param string $output
*/
function handleOCSCommunication($rawdata, $xml = '', $output = 'ext') {
// ***** For debug only ***** //
//$rawdata = gzcompress('');
// ********** End ********** //
$config = new PluginFusioninventoryConfig();
$user = new User();
if (!isset($_SESSION['glpiID'])) {
$users_id = $config->getValue('users_id');
$_SESSION['glpiID'] = $users_id;
$user->getFromDB($users_id);
Session::changeActiveEntities();
$_SESSION["glpiname"] = $user->getField('name');
$_SESSION['glpiactiveprofile'] = [];
$_SESSION['glpiactiveprofile']['interface'] = 'central';
$_SESSION['glpiactiveprofile']['internet'] = ALLSTANDARDRIGHT;
$_SESSION['glpiactiveprofile']['computer'] = ALLSTANDARDRIGHT;
$_SESSION['glpiactiveprofile']['monitor'] = ALLSTANDARDRIGHT;
$_SESSION['glpiactiveprofile']['printer'] = ALLSTANDARDRIGHT;
$_SESSION['glpiactiveprofile']['peripheral'] = ALLSTANDARDRIGHT;
$_SESSION['glpiactiveprofile']['networking'] = ALLSTANDARDRIGHT;
$_SESSION["glpi_plugin_fusioninventory_profile"]['unmanaged'] = ALLSTANDARDRIGHT;
}
$communication = new PluginFusioninventoryCommunication();
$pfToolbox = new PluginFusioninventoryToolbox();
// identify message compression algorithm
PluginFusioninventoryDisplay::disableDebug();
$compressmode = '';
$content_type = filter_input(INPUT_SERVER, "CONTENT_TYPE");
if (!empty($xml)) {
$compressmode = 'none';
} else if ($content_type == "application/x-compress-zlib") {
$xml = gzuncompress($rawdata);
$compressmode = "zlib";
} else if ($content_type == "application/x-compress-gzip") {
$xml = $pfToolbox->gzdecode($rawdata);
$compressmode = "gzip";
} else if ($content_type == "application/xml") {
$xml = $rawdata;
$compressmode = 'none';
} else {
// try each algorithm successively
if (($xml = gzuncompress($rawdata))) {
$compressmode = "zlib";
} else if (($xml = $pfToolbox->gzdecode($rawdata))) {
$compressmode = "gzip";
} else if (($xml = gzinflate (substr($rawdata, 2)))) {
// accept deflate for OCS agent 2.0 compatibility,
// but use zlib for answer
if (strstr($xml, "<QUERY>PROLOG</QUERY>")
AND !strstr($xml, "<TOKEN>")) {
$compressmode = "zlib";
} else {
$compressmode = "deflate";
}
} else {
$xml = $rawdata;
$compressmode = 'none';
}
}
PluginFusioninventoryDisplay::reenableusemode();
// check if we are in ssl only mode
$ssl = $config->getValue('ssl_only');
if ($ssl == "1" AND filter_input(INPUT_SERVER, "HTTPS") != "on") {
if ($output == 'glpi') {
Session::addMessageAfterRedirect('SSL REQUIRED BY SERVER', false, ERROR);
} else {
$communication->setMessage("<?xml version='1.0' encoding='UTF-8'?>
<REPLY>
<ERROR>SSL REQUIRED BY SERVER</ERROR>
</REPLY>");
$communication->sendMessage($compressmode);
}
return;
}
PluginFusioninventoryConfig::logIfExtradebug(
'pluginFusioninventory-dial' . uniqid(),
$xml
);
// Check XML integrity
$pxml = @simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
if (!$pxml) {
$pxml = @simplexml_load_string(
utf8_encode($xml),
'SimpleXMLElement',
LIBXML_NOCDATA
);
if ($pxml) {
$xml = utf8_encode($xml);
}
}
if (!$pxml) {
$xml = preg_replace ('/<FOLDER>.*?<\/SOURCE>/', '', $xml);
$pxml = @simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
if (!$pxml) {
if ($output == 'glpi') {
Session::addMessageAfterRedirect('XML not well formed!', false, ERROR);
} else {
$communication->setMessage("<?xml version='1.0' encoding='UTF-8'?>
<REPLY>
<ERROR>XML not well formed!</ERROR>
</REPLY>");
$communication->sendMessage($compressmode);
}
return;
}
}
$_SESSION['plugin_fusioninventory_compressmode'] = $compressmode;
// Convert XML into PHP array
$arrayinventory = PluginFusioninventoryFormatconvert::XMLtoArray($pxml);
unset($pxml);
$deviceid = '';
if (isset($arrayinventory['DEVICEID'])) {
$deviceid = $arrayinventory['DEVICEID'];
}
$agent = new PluginFusioninventoryAgent();
$agents_id = $agent->importToken($arrayinventory);
$_SESSION['plugin_fusioninventory_agents_id'] = $agents_id;
if (!$communication->import($arrayinventory)) {
if ($deviceid != '') {
$communication->setMessage("<?xml version='1.0' encoding='UTF-8'?>
<REPLY>
</REPLY>");
$a_agent = $agent->infoByKey($deviceid);
// Get taskjob in waiting
$communication->getTaskAgent($a_agent['id']);
// ******** Send XML
$communication->addInventory($a_agent['id']);
$communication->addProlog();
$communication->sendMessage($compressmode);
}
} else {
if ($output == 'glpi') {
Session::addMessageAfterRedirect('XML has been imported succesfully!');
} else {
$communication->setMessage("<?xml version='1.0' encoding='UTF-8'?>
<REPLY>
</REPLY>");
$communication->sendMessage($compressmode);
}
}
}
}

View File

@@ -0,0 +1,747 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the communication of network discovery
* feature with the agents.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author Vincent Mazzoni
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access this file directly");
}
/**
* Manage the communication of network discovery feature with the agents.
*/
class PluginFusioninventoryCommunicationNetworkDiscovery {
/**
* Import data, so get data from agent to put in GLPI
*
* @param string $p_DEVICEID device_id of agent
* @param array $a_CONTENT
* @param array $arrayinventory
* @return string errors or empty string
*/
function import($p_DEVICEID, $a_CONTENT, $arrayinventory) {
$pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
$pfAgent = new PluginFusioninventoryAgent();
PluginFusioninventoryCommunication::addLog(
'Function PluginFusioninventoryCommunicationNetworkDiscovery->import().');
$errors = '';
$a_agent = $pfAgent->infoByKey($p_DEVICEID);
if (isset($a_CONTENT['PROCESSNUMBER'])) {
$_SESSION['glpi_plugin_fusioninventory_processnumber'] = $a_CONTENT['PROCESSNUMBER'];
if ($pfTaskjobstate->getFromDB($a_CONTENT['PROCESSNUMBER'])) {
if ($pfTaskjobstate->fields['state'] != PluginFusioninventoryTaskjobstate::FINISHED) {
$pfTaskjobstate->changeStatus($a_CONTENT['PROCESSNUMBER'], 2);
if ((!isset($a_CONTENT['AGENT']['START']))
AND (!isset($a_CONTENT['AGENT']['END']))) {
$nb_devices = 0;
if (isset($a_CONTENT['DEVICE'])) {
if (is_int(key($a_CONTENT['DEVICE']))) {
$nb_devices = count($a_CONTENT['DEVICE']);
} else {
$nb_devices = 1;
}
}
$_SESSION['plugin_fusinvsnmp_taskjoblog']['taskjobs_id'] =
$a_CONTENT['PROCESSNUMBER'];
$_SESSION['plugin_fusinvsnmp_taskjoblog']['items_id'] = $a_agent['id'];
$_SESSION['plugin_fusinvsnmp_taskjoblog']['itemtype'] =
'PluginFusioninventoryAgent';
$_SESSION['plugin_fusinvsnmp_taskjoblog']['state'] = PluginFusioninventoryTaskjoblog::TASK_RUNNING;
$_SESSION['plugin_fusinvsnmp_taskjoblog']['comment'] =
$nb_devices.' ==devicesfound==';
$this->addtaskjoblog();
}
}
}
}
if ($pfTaskjobstate->getFromDB($a_CONTENT['PROCESSNUMBER'])) {
if ($pfTaskjobstate->fields['state'] != PluginFusioninventoryTaskjobstate::FINISHED) {
$pfImportExport = new PluginFusioninventorySnmpmodelImportExport();
$errors .= $pfImportExport->import_netdiscovery($a_CONTENT, $p_DEVICEID);
if (isset($a_CONTENT['AGENT']['END'])) {
$messages = [
'Total Found' => 0,
'Created' => 0,
'Updated' => 0
];
$messages['Updated'] = countElementsInTable('glpi_plugin_fusioninventory_taskjoblogs',
[
'plugin_fusioninventory_taskjobstates_id' => $a_CONTENT['PROCESSNUMBER'],
'comment' => ['LIKE', '%==updatetheitem==%'],
]);
$messages['Created'] = countElementsInTable('glpi_plugin_fusioninventory_taskjoblogs',
[
'plugin_fusioninventory_taskjobstates_id' => $a_CONTENT['PROCESSNUMBER'],
'comment' => ['LIKE', '%==addtheitem==%'],
]);
$messages['Total Found'] = $messages['Updated'] + $messages['Created'];
$message = __('Processed:', 'fusioninventory').$messages['Total Found'].' ';
$message.= __('Created:', 'fusioninventory').$messages['Created'].' ';
$message.= __(' Updated:', 'fusioninventory').$messages['Updated'];
$pfTaskjobstate->changeStatusFinish($a_CONTENT['PROCESSNUMBER'],
$a_agent['id'],
'PluginFusioninventoryAgent',
'0',
$message);
}
}
}
return $errors;
}
/**
* Prepare data and send them to rule engine
*
* @param array $arrayinventory inventory array
*/
function sendCriteria($arrayinventory) {
PluginFusioninventoryCommunication::addLog(
'Function PluginFusioninventoryCommunicationNetworkDiscovery->sendCriteria().');
if ((isset($arrayinventory['MAC']))
&& ($arrayinventory['MAC'] == "00:00:00:00:00:00")) {
unset($arrayinventory['MAC']);
}
$_SESSION['SOURCE_XMLDEVICE'] = $arrayinventory;
$input = [];
// Global criterias
if ((isset($arrayinventory['SERIAL']))
&& (!empty($arrayinventory['SERIAL']))) {
$input['serial'] = $arrayinventory['SERIAL'];
}
if ((isset($arrayinventory['MAC']))
&& (!empty($arrayinventory['MAC']))) {
$input['mac'][] = $arrayinventory['MAC'];
}
if ((isset($arrayinventory['IP']))
&& (!empty($arrayinventory['IP']))) {
$input['ip'][] = $arrayinventory['IP'];
}
if ((isset($arrayinventory['MODELSNMP']))
&& (!empty($arrayinventory['MODELSNMP']))) {
$input['model'] = $arrayinventory['MODELSNMP'];
}
if ((isset($arrayinventory['SNMPHOSTNAME']))
&& (!empty($arrayinventory['SNMPHOSTNAME']))) {
$input['name'] = $arrayinventory['SNMPHOSTNAME'];
} else if ((isset($arrayinventory['NETBIOSNAME']))
&& (!empty($arrayinventory['NETBIOSNAME']))) {
$input['name'] = $arrayinventory['NETBIOSNAME'];
} else if ((isset($arrayinventory['DNSHOSTNAME']))
&& (!empty($arrayinventory['DNSHOSTNAME']))) {
if (strpos($arrayinventory['DNSHOSTNAME'], '.') !== false) {
$splitname = explode('.', $arrayinventory['DNSHOSTNAME']);
$input['name'] = $splitname[0];
if (!isset($arrayinventory['WORKGROUP'])) {
unset($splitname[0]);
$arrayinventory['WORKGROUP'] = implode('.', $splitname);
$_SESSION['SOURCE_XMLDEVICE'] = $arrayinventory;
}
} else {
$input['name'] = $arrayinventory['DNSHOSTNAME'];
}
}
if (!isset($arrayinventory['ENTITY'])) {
$arrayinventory['ENTITY'] = 0;
}
$input['entities_id'] = $arrayinventory['ENTITY'];
if (isset($arrayinventory['TYPE'])) {
switch ($arrayinventory['TYPE']) {
case '1':
case 'COMPUTER':
$input['itemtype'] = "Computer";
// Computer
break;
case '2':
case 'NETWORKING':
case 'STORAGE':
$input['itemtype'] = "NetworkEquipment";
break;
case '3':
case 'PRINTER':
$input['itemtype'] = "Printer";
break;
}
}
$_SESSION['plugin_fusinvsnmp_datacriteria'] = serialize($input);
$_SESSION['plugin_fusioninventory_classrulepassed'] =
"PluginFusioninventoryCommunicationNetworkDiscovery";
$rule = new PluginFusioninventoryInventoryRuleImportCollection();
$data = $rule->processAllRules($input, []);
PluginFusioninventoryConfig::logIfExtradebug("pluginFusioninventory-rules",
$data);
if (isset($data['action'])
&& ($data['action'] == PluginFusioninventoryInventoryRuleImport::LINK_RESULT_DENIED)) {
$a_text = [];
foreach ($input as $key=>$data) {
if (is_array($data)) {
$a_text[] = "[".$key."]:".implode(", ", $data);
} else {
$a_text[] = "[".$key."]:".$data;
}
}
$_SESSION['plugin_fusinvsnmp_taskjoblog']['comment'] = '==importdenied== '.
implode(", ", $a_text);
$this->addtaskjoblog();
$pfIgnoredimport = new PluginFusioninventoryIgnoredimportdevice();
$inputdb = [];
if (isset($input['name'])) {
$inputdb['name'] = $input['name'];
}
$inputdb['date'] = date("Y-m-d H:i:s");
if (isset($input['itemtype'])) {
$inputdb['itemtype'] = $input['itemtype'];
}
if (isset($input['serial'])) {
$inputdb['serial'] = $input['serial'];
}
if (isset($input['ip'])) {
$inputdb['ip'] = exportArrayToDB($input['ip']);
}
if (isset($input['mac'])) {
$inputdb['mac'] = exportArrayToDB($input['mac']);
}
if (isset($input['uuid'])) {
$inputdb['uuid'] = $input['uuid'];
}
$inputdb['rules_id'] = $_SESSION['plugin_fusioninventory_rules_id'];
$inputdb['method'] = 'networkdiscovery';
$pfIgnoredimport->add($inputdb);
unset($_SESSION['plugin_fusioninventory_rules_id']);
}
if (isset($data['_no_rule_matches']) AND ($data['_no_rule_matches'] == '1')) {
if (!isset($_SESSION['glpiactiveentities_string'])) {
$_SESSION['glpiactiveentities_string'] = "'".$input['entities_id']."'";
}
if (isset($input['itemtype'])
&& isset($data['action'])
&& ($data['action'] == PluginFusioninventoryInventoryRuleImport::LINK_RESULT_CREATE)) {
$this->rulepassed(0, $input['itemtype'], 0, $input['entities_id']);
} else if (isset($input['itemtype'])
AND !isset($data['action'])) {
$this->rulepassed(0, $input['itemtype'], 0, $input['entities_id']);
} else {
$this->rulepassed(0, "PluginFusioninventoryUnmanaged", 0, $input['entities_id']);
}
}
}
/**
* After rule engine passed, update task (log) and create item if required
*
* @param integer $items_id id of the item (0 = not exist in database)
* @param string $itemtype
* @param integer $entities_id
*/
function rulepassed($items_id, $itemtype, $ports_id = 0, $entities_id = 0) {
PluginFusioninventoryLogger::logIfExtradebug(
"pluginFusioninventory-rules",
"Rule passed : ".$items_id.", ".$itemtype."\n"
);
PluginFusioninventoryLogger::logIfExtradebugAndDebugMode(
'fusioninventorycommunication',
'Function PluginFusinvsnmpCommunicationNetDiscovery->rulepassed().'
);
if (!isset($_SESSION['glpiactiveentities_string'])) {
$_SESSION['glpiactiveentities_string'] = "'".$entities_id."'";
}
$_SESSION['glpiactive_entity'] = $entities_id;
$item = new $itemtype();
if ($items_id == "0") {
$input = [];
$input['date_mod'] = date("Y-m-d H:i:s");
$input['entities_id'] = $entities_id;
$items_id = $item->add($input);
if (isset($_SESSION['plugin_fusioninventory_rules_id'])) {
$pfRulematchedlog = new PluginFusioninventoryRulematchedlog();
$inputrulelog = [];
$inputrulelog['date'] = date('Y-m-d H:i:s');
$inputrulelog['rules_id'] = $_SESSION['plugin_fusioninventory_rules_id'];
if (isset($_SESSION['plugin_fusioninventory_agents_id'])) {
$inputrulelog['plugin_fusioninventory_agents_id'] =
$_SESSION['plugin_fusioninventory_agents_id'];
}
$inputrulelog['items_id'] = $items_id;
$inputrulelog['itemtype'] = $itemtype;
$inputrulelog['method'] = 'networkdiscovery';
$pfRulematchedlog->add($inputrulelog);
$pfRulematchedlog->cleanOlddata($items_id, $itemtype);
unset($_SESSION['plugin_fusioninventory_rules_id']);
}
if (!isset($_SESSION['glpiactiveentities_string'])) {
$_SESSION['glpiactiveentities_string'] = "'".$entities_id."'";
}
$_SESSION['plugin_fusinvsnmp_taskjoblog']['comment'] =
'[==detail==] ==addtheitem== '.$item->getTypeName().
' [['.$itemtype.'::'.$items_id.']]';
$this->addtaskjoblog();
} else {
$_SESSION['plugin_fusinvsnmp_taskjoblog']['comment'] =
'[==detail==] ==updatetheitem== '.$item->getTypeName().
' [['.$itemtype.'::'.$items_id.']]';
$this->addtaskjoblog();
}
$item->getFromDB($items_id);
$this->importDevice($item);
}
/**
* Import discovered device (add / update data in GLPI DB)
*
* @param object $item
*/
function importDevice($item) {
PluginFusioninventoryLogger::logIfExtradebugAndDebugMode(
'fusioninventorycommunication',
'Function PluginFusinvsnmpCommunicationNetDiscovery->importDevice().'
);
$arrayinventory = $_SESSION['SOURCE_XMLDEVICE'];
$input = [];
$input['id'] = $item->getID();
$a_lockable = PluginFusioninventoryLock::getLockFields(getTableForItemType($item->getType()),
$item->getID());
if (!in_array('name', $a_lockable)) {
if (isset($arrayinventory['SNMPHOSTNAME'])
&& !empty($arrayinventory['SNMPHOSTNAME'])) {
$input['name'] = $arrayinventory['SNMPHOSTNAME'];
} else if (isset($arrayinventory['NETBIOSNAME'])
&& !empty($arrayinventory['NETBIOSNAME'])) {
$input['name'] = $arrayinventory['NETBIOSNAME'];
} else if (isset($arrayinventory['DNSHOSTNAME'])
&&!empty($arrayinventory['DNSHOSTNAME'])) {
$input['name'] = $arrayinventory['DNSHOSTNAME'];
}
}
if (!in_array('serial', $a_lockable)) {
if (isset($arrayinventory['SERIAL'])) {
if (trim($arrayinventory['SERIAL']) != '') {
$input['serial'] = trim($arrayinventory['SERIAL']);
}
}
}
if (isset($input['name'])
&& $input['name'] == '') {
unset($input['name']);
}
if (isset($input['serial'])
&& $input['serial'] == '') {
unset($input['serial']);
}
if (isset($arrayinventory['ENTITY']) AND !empty($arrayinventory['ENTITY'])) {
$input['entities_id'] = $arrayinventory['ENTITY'];
if (!isset($_SESSION['glpiactiveentities_string'])) {
$_SESSION['glpiactiveentities_string'] = "'".$arrayinventory['ENTITY']."'";
}
}
if (!isset($_SESSION['glpiactiveentities_string'])) {
$_SESSION['glpiactiveentities_string'] = "'".$item->fields['entities_id']."'";
}
switch ($item->getType()) {
case 'Computer':
// don't update this computer, if it is already handled by
// its own agent
if (Dropdown::getDropdownName("glpi_autoupdatesystems",
$item->fields['autoupdatesystems_id'])
== 'FusionInventory') {
return;
}
if (isset($arrayinventory['WORKGROUP'])) {
$ditem = new Domain_Item();
if (!in_array('domains_id', $a_lockable)) {
$domain = new Domain();
$domains_id = $domain->import([
'name' => $arrayinventory['WORKGROUP'],
'entities_id' => $item->fields['entities_id']
]);
$dinput = [
'itemtype' => 'Computer',
'items_id' => $item->fields['id'],
'domains_id' => $domains_id
];
if (!$ditem->getFromDBByCrit($dinput)) {
$ditem->add($dinput);
}
}
}
$item->update($input);
$this->updateNetworkInfo(
$arrayinventory,
'Computer',
$item->getID(),
'NetworkPortEthernet',
1
);
break;
case 'PluginFusioninventoryUnmanaged':
// Write XML file
if (isset($_SESSION['SOURCE_XMLDEVICE'])) {
PluginFusioninventoryToolbox::writeXML(
$input['id'],
serialize($_SESSION['SOURCE_XMLDEVICE']),
'PluginFusioninventoryUnmanaged'
);
}
if (!in_array('contact', $a_lockable)
&& isset($arrayinventory['USERSESSION'])) {
$input['contact'] = $arrayinventory['USERSESSION'];
}
if (!in_array('domain', $a_lockable)) {
if (isset($arrayinventory['WORKGROUP'])
&& !empty($arrayinventory['WORKGROUP'])) {
$input['domain'] = Dropdown::importExternal("Domain",
$arrayinventory['WORKGROUP'], $arrayinventory['ENTITY']);
}
}
if (!empty($arrayinventory['TYPE'])) {
switch ($arrayinventory['TYPE']) {
case '1':
case 'COMPUTER':
$input['item_type'] = 'Computer';
break;
case '2':
case 'NETWORKING':
case 'STORAGE':
$input['item_type'] = 'NetworkEquipment';
break;
case '3':
case 'PRINTER':
$input['item_type'] = 'Printer';
break;
}
}
$input['plugin_fusioninventory_agents_id'] =
$_SESSION['glpi_plugin_fusioninventory_agentid'];
$this->updateSNMPInfo($arrayinventory, $input, $item);
$this->updateNetworkInfo(
$arrayinventory,
'PluginFusioninventoryUnmanaged',
$item->getID(),
'NetworkPortEthernet',
1
);
break;
case 'NetworkEquipment':
// Write XML file
if (isset($_SESSION['SOURCE_XMLDEVICE'])) {
PluginFusioninventoryToolbox::writeXML(
$input['id'],
serialize($_SESSION['SOURCE_XMLDEVICE']),
'NetworkEquipment'
);
}
$item->update($input);
$this->updateNetworkInfo(
$arrayinventory,
'NetworkEquipment',
$item->getID(),
'NetworkPortAggregate',
0
);
$pfNetworkEquipment = new PluginFusioninventoryNetworkEquipment();
$input = $this->initSpecificInfo(
'networkequipments_id',
$item->getID(),
$pfNetworkEquipment
);
$this->updateSNMPInfo($arrayinventory, $input, $pfNetworkEquipment);
break;
case 'Printer':
// Write XML file
if (isset($_SESSION['SOURCE_XMLDEVICE'])) {
PluginFusioninventoryToolbox::writeXML(
$input['id'],
serialize($_SESSION['SOURCE_XMLDEVICE']),
'Printer'
);
}
$input['have_ethernet'] = '1';
$item->update($input);
$this->updateNetworkInfo(
$arrayinventory,
'Printer',
$item->getID(),
'NetworkPortEthernet',
1
);
$pfPrinter = new PluginFusioninventoryPrinter();
$input = $this->initSpecificInfo(
'printers_id',
$item->getID(),
$pfPrinter
);
$this->updateSNMPInfo($arrayinventory, $input, $pfPrinter);
break;
}
}
/**
* Update networkport information
*
* @param array $arrayinventory
* @param string $itemtype
* @param integer $items_id
* @param string $instanciation_type type of port (ethernet, wifi...)
* @param boolean $check_addresses
*/
function updateNetworkInfo($arrayinventory, $itemtype, $items_id, $instanciation_type, $check_addresses) {
$NetworkPort = new NetworkPort();
$port = current($NetworkPort->find(
['itemtype' => $itemtype,
'items_id' => $items_id,
'instantiation_type' => $instanciation_type],
[], 1));
$port_id = 0;
if (isset($port['id'])) {
if (isset($arrayinventory['MAC']) AND !empty($arrayinventory['MAC'])) {
$input = [];
$input['id'] = $port['id'];
$input['mac'] = $arrayinventory['MAC'];
$NetworkPort->update($input);
}
$port_id = $port['id'];
} else {
$item = new $itemtype;
$item->getFromDB($items_id);
$input = [];
$input['itemtype'] = $itemtype;
$input['items_id'] = $items_id;
$input['instantiation_type'] = $instanciation_type;
$input['name'] = "management";
$input['entities_id'] = $item->fields['entities_id'];
if (isset($arrayinventory['MAC'])
&& !empty($arrayinventory['MAC'])) {
$input['mac'] = $arrayinventory['MAC'];
}
$port_id = $NetworkPort->add($input);
}
$NetworkName = new NetworkName();
$name = current($NetworkName->find(
['itemtype' => 'NetworkPort', 'items_id' => $port_id], [], 1));
$name_id = 0;
if (isset($name['id'])) {
$name_id = $name['id'];
} else {
$input = [];
$input['itemtype'] = 'NetworkPort';
$input['items_id'] = $port_id;
$name_id = $NetworkName->add($input);
}
if (isset($arrayinventory['IP'])) {
$IPAddress = new IPAddress();
if ($check_addresses) {
$addresses = $IPAddress->find(
['itemtype' => 'NetworkName',
'items_id' => $name_id],
[], 1);
} else {
// Case of NetworkEquipment
$a_ips = $IPAddress->find(
['itemtype' => 'NetworkName',
'items_id' => $name_id,
'name' => $arrayinventory['IP']],
[], 1);
if (count($a_ips) > 0) {
$addresses = $a_ips;
} else {
$addresses = [];
}
}
if (count($addresses) == 0) {
$input = [];
$input['itemtype'] = 'NetworkName';
$input['items_id'] = $name_id;
$input['name'] = $arrayinventory['IP'];
$IPAddress->add($input);
} else {
$address = current($addresses);
if ($address['name'] != $arrayinventory['IP']) {
$input = [];
$input['id'] = $address['id'];
$input['name'] = $arrayinventory['IP'];
$IPAddress->update($input);
}
}
}
}
/**
* Get info from database
*
* @param string $key_field
* @param integer $id
* @param object $item
* @return array
*/
function initSpecificInfo($key_field, $id, $item) {
$instances = $item->find([$key_field => $id]);
$input = [];
if (count($instances) > 0) {
$input = Toolbox::addslashes_deep(current($instances));
} else {
$input[$key_field] = $id;
$id = $item->add($input);
$item->getFromDB($id);
$input = $item->fields;
}
return $input;
}
/**
* Update SNMP information of a device (sysdescr, SNMP credentials...)
*
* @param array $arrayinventory
* @param array $input
* @param object $item
*/
function updateSNMPInfo($arrayinventory, $input, $item) {
if (isset($arrayinventory['DESCRIPTION'])
&& !empty($arrayinventory['DESCRIPTION'])) {
$input['sysdescr'] = $arrayinventory['DESCRIPTION'];
}
if (isset($arrayinventory['AUTHSNMP'])
&& !empty($arrayinventory['AUTHSNMP'])) {
$input['plugin_fusioninventory_configsecurities_id'] = $arrayinventory['AUTHSNMP'];
}
$item->update($input);
}
/**
* Used to add log in the taskjob
*/
function addtaskjoblog() {
$pfTaskjoblog = new PluginFusioninventoryTaskjoblog();
$pfTaskjoblog->addTaskjoblog(
$_SESSION['plugin_fusinvsnmp_taskjoblog']['taskjobs_id'],
$_SESSION['plugin_fusinvsnmp_taskjoblog']['items_id'],
$_SESSION['plugin_fusinvsnmp_taskjoblog']['itemtype'],
$_SESSION['plugin_fusinvsnmp_taskjoblog']['state'],
$_SESSION['plugin_fusinvsnmp_taskjoblog']['comment']);
}
/**
* Get method name linked to this class
*
* @return string
*/
static function getMethod() {
return 'networkdiscovery';
}
}

View File

@@ -0,0 +1,754 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the communication for the network inventory
* with the agents.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author Vincent Mazzoni
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access this file directly");
}
/**
* Manage the communication of network inventory feature with the agents.
*/
class PluginFusioninventoryCommunicationNetworkInventory {
/**
* Define protected variables
*
* @var null
*/
private $logFile, $agent, $arrayinventory;
/**
* The right name for this class
*
* @var string
*/
static $rightname = 'plugin_fusioninventory_networkequipment';
/**
* __contruct function where fill logFile if extradebug enabled
*/
function __construct() {
if (PluginFusioninventoryConfig::isExtradebugActive()) {
$this->logFile = GLPI_LOG_DIR.'/fusioninventorycommunication.log';
}
}
/**
* Import data, so get data from agent to put in GLPI
*
* @param string $p_DEVICEID device_id of the agent
* @param array $a_CONTENT
* @param array $arrayinventory
*/
function import($p_DEVICEID, $a_CONTENT, $arrayinventory) {
PluginFusioninventoryCommunication::addLog(
'Function PluginFusioninventoryCommunicationNetworkInventory->import().');
$pfAgent = new PluginFusioninventoryAgent();
$pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
$this->agent = $pfAgent->infoByKey($p_DEVICEID);
$this->arrayinventory = $arrayinventory;
if (!isset($a_CONTENT['PROCESSNUMBER'])) {
$a_CONTENT['PROCESSNUMBER'] = 1;
}
$_SESSION['glpi_plugin_fusioninventory_processnumber'] = $a_CONTENT['PROCESSNUMBER'];
if ((!isset($a_CONTENT['AGENT']['START'])) AND (!isset($a_CONTENT['AGENT']['END']))) {
$nb_devices = 0;
if (isset($a_CONTENT['DEVICE'])) {
if (is_int(key($a_CONTENT['DEVICE']))) {
$nb_devices = count($a_CONTENT['DEVICE']);
} else {
$nb_devices = 1;
}
}
$_SESSION['plugin_fusinvsnmp_taskjoblog']['taskjobs_id'] =
$a_CONTENT['PROCESSNUMBER'];
$_SESSION['plugin_fusinvsnmp_taskjoblog']['items_id'] = $this->agent['id'];
$_SESSION['plugin_fusinvsnmp_taskjoblog']['itemtype'] = 'PluginFusioninventoryAgent';
$_SESSION['plugin_fusinvsnmp_taskjoblog']['state'] = '6';
$_SESSION['plugin_fusinvsnmp_taskjoblog']['comment'] = $nb_devices.
' ==devicesqueried==';
$this->addtaskjoblog();
}
$this->importContent($a_CONTENT);
if (isset($a_CONTENT['AGENT']['END'])) {
$cnt = countElementsInTable('glpi_plugin_fusioninventory_taskjoblogs',
[
'plugin_fusioninventory_taskjobstates_id' => $a_CONTENT['PROCESSNUMBER'],
'comment' => ["LIKE", '%[==detail==] Update %'],
]);
$pfTaskjobstate->changeStatusFinish(
$a_CONTENT['PROCESSNUMBER'],
$this->agent['id'],
'PluginFusioninventoryAgent',
'0',
'Total updated:'.$cnt);
}
if (isset($a_CONTENT['AGENT']['START'])) {
$_SESSION['plugin_fusinvsnmp_taskjoblog']['taskjobs_id'] =
$a_CONTENT['PROCESSNUMBER'];
$_SESSION['plugin_fusinvsnmp_taskjoblog']['items_id'] = $this->agent['id'];
$_SESSION['plugin_fusinvsnmp_taskjoblog']['itemtype'] = 'PluginFusioninventoryAgent';
$_SESSION['plugin_fusinvsnmp_taskjoblog']['state'] = '6';
$_SESSION['plugin_fusinvsnmp_taskjoblog']['comment'] = '==inventorystarted==';
$this->addtaskjoblog();
}
}
/**
* Import the content (where have all devices)
*
* @param array $arrayinventory
* @return string errors or empty string
*/
function importContent($arrayinventory) {
PluginFusioninventoryCommunication::addLog(
'Function PluginFusioninventoryCommunicationNetworkInventory->importContent().');
$pfAgent = new PluginFusioninventoryAgent();
$errors='';
$nbDevices = 0;
foreach ($arrayinventory as $childname=>$child) {
PluginFusioninventoryCommunication::addLog($childname);
switch ($childname) {
case 'DEVICE' :
$a_devices = [];
if (is_int(key($child))) {
$a_devices = $child;
} else {
$a_devices[] = $child;
}
$xml_num = 0;
foreach ($a_devices as $dchild) {
$_SESSION['plugin_fusioninventory_xmlnum'] = $xml_num;
$a_inventory = [];
if (isset($dchild['INFO'])) {
if ($dchild['INFO']['TYPE'] == "NETWORKING" || $dchild['INFO']['TYPE'] == "STORAGE") {
$a_inventory = PluginFusioninventoryFormatconvert::networkequipmentInventoryTransformation($dchild);
} else if ($dchild['INFO']['TYPE'] == "PRINTER") {
$a_inventory = PluginFusioninventoryFormatconvert::printerInventoryTransformation($dchild);
}
}
if (isset($dchild['ERROR'])) {
$itemtype = "";
if ($dchild['ERROR']['TYPE'] == "NETWORKING" || $dchild['ERROR']['TYPE'] == "STORAGE") {
$itemtype = "NetworkEquipment";
} else if ($dchild['ERROR']['TYPE'] == "PRINTER") {
$itemtype = "Printer";
}
$_SESSION['plugin_fusinvsnmp_taskjoblog']['comment'] = '[==detail==] '.
$dchild['ERROR']['MESSAGE'].' [['.$itemtype.'::'.
$dchild['ERROR']['ID'].']]';
$this->addtaskjoblog();
} else if ($a_inventory['PluginFusioninventory'.$a_inventory['itemtype']]['sysdescr'] == ''
&& $a_inventory[$a_inventory['itemtype']]['name'] == ''
&& $a_inventory[$a_inventory['itemtype']]['serial'] == '') {
$_SESSION['plugin_fusinvsnmp_taskjoblog']['comment'] =
'[==detail==] No informations [['.$a_inventory['itemtype'].'::'.$dchild['INFO']['ID'].']]';
$this->addtaskjoblog();
} else {
if (count($a_inventory) > 0) {
if ($a_inventory['itemtype'] == 'NetworkEquipment') {
// Detect if the device is a stacked switch
$staked = $this->is_stacked_switch($a_inventory);
if ($staked) {
$devices = $this->split_stacked_switch($a_inventory);
foreach ($devices as $device) {
$this->sendCriteria($device);
}
// So we had create the devices of the stack, no need continue to import the global stack
return $errors;
}
$wirelesscontroller = $this->is_wireless_controller($a_inventory);
if ($wirelesscontroller) {
$accesspoints = $this->get_wireless_controller_access_points($a_inventory);
foreach ($accesspoints as $device) {
$this->sendCriteria($device);
}
// we continue to manage / import / update the wireless controller
}
}
$errors .= $this->sendCriteria($a_inventory);
$nbDevices++;
}
}
$xml_num++;
}
break;
case 'AGENT' :
if (isset($this->arrayinventory['CONTENT']['AGENT']['AGENTVERSION'])) {
$agent = $pfAgent->infoByKey($this->arrayinventory['DEVICEID']);
$agent['fusioninventory_agent_version'] =
$this->arrayinventory['CONTENT']['AGENT']['AGENTVERSION'];
$agent['last_agent_update'] = date("Y-m-d H:i:s");
$pfAgent->update($agent);
}
break;
case 'PROCESSNUMBER' :
break;
case 'MODULEVERSION' :
break;
default :
$_SESSION['plugin_fusinvsnmp_taskjoblog']['comment'] = '[==detail==] '.
__('Unattended element in', 'fusioninventory').' CONTENT : '.$childname;
$this->addtaskjoblog();
}
}
return $errors;
}
/**
* import process of one device
*
* @global SimpleXMLElement $PLUGIN_FUSIONINVENTORY_XML
* @param string $itemtype
* @param integer $items_id
* @param array $a_inventory
* @param boolean $no_history notice if changes must be logged or not
* @return string errors or empty string
*/
function importDevice($itemtype, $items_id, $a_inventory, $no_history) {
global $PLUGIN_FUSIONINVENTORY_XML;
PluginFusioninventoryCommunication::addLog(
'Function PluginFusioninventoryCommunicationNetworkInventory->importDevice().');
$pfFormatconvert = new PluginFusioninventoryFormatconvert();
$a_inventory = $pfFormatconvert->replaceids($a_inventory, $itemtype, $items_id);
// Write XML file
if (count($a_inventory) > 0
AND isset($_SESSION['plugin_fusioninventory_xmlnum'])) {
$xml = $PLUGIN_FUSIONINVENTORY_XML->CONTENT->DEVICE[$_SESSION['plugin_fusioninventory_xmlnum']]->asXML();
PluginFusioninventoryToolbox::writeXML(
$items_id,
$xml,
$itemtype);
}
$errors='';
$this->deviceId=$items_id;
$serialized = gzcompress(serialize($a_inventory));
if (isset($a_inventory['name'])
&& $a_inventory['name'] == '') {
unset($a_inventory['name']);
}
if (isset($a_inventory['serial'])
&& $a_inventory['serial'] == '') {
unset($a_inventory['serial']);
}
switch ($itemtype) {
case 'Printer':
$pfiPrinterLib = new PluginFusioninventoryInventoryPrinterLib();
$a_inventory['PluginFusioninventoryPrinter']['serialized_inventory'] =
Toolbox::addslashes_deep($serialized);
$pfiPrinterLib->updatePrinter($a_inventory, $items_id, $no_history);
break;
case 'NetworkEquipment':
$pfiNetworkEquipmentLib = new PluginFusioninventoryInventoryNetworkEquipmentLib();
$a_inventory['PluginFusioninventoryNetworkEquipment']['serialized_inventory'] =
Toolbox::addslashes_deep($serialized);
$pfiNetworkEquipmentLib->updateNetworkEquipment($a_inventory, $items_id, $no_history);
break;
default:
return __('Unattended element in', 'fusioninventory').' TYPE : '.$a_inventory['itemtype']."\n";
}
return '';
}
/**
* Send inventory information to import rules
*
* @param array $a_inventory
* @return string errors or empty string
*/
function sendCriteria($a_inventory) {
PluginFusioninventoryCommunication::addLog(
'Function PluginFusioninventoryCommunicationNetworkInventory->sendCriteria().');
$errors = '';
// Manual blacklist
if ($a_inventory[$a_inventory['itemtype']]['serial'] == 'null') {
$a_inventory[$a_inventory['itemtype']]['serial'] = '';
}
// End manual blacklist
$_SESSION['SOURCE_XMLDEVICE'] = $a_inventory;
$input = [];
// Global criterias
if (!empty($a_inventory[$a_inventory['itemtype']]['serial'])) {
$input['serial'] = $a_inventory[$a_inventory['itemtype']]['serial'];
}
if ($a_inventory['itemtype'] == 'NetworkEquipment') {
if (!empty($a_inventory[$a_inventory['itemtype']]['mac'])) {
$input['mac'][] = $a_inventory[$a_inventory['itemtype']]['mac'];
}
$input['itemtype'] = "NetworkEquipment";
} else if ($a_inventory['itemtype'] == 'Printer') {
$input['itemtype'] = "Printer";
if (isset($a_inventory['networkport'])) {
$a_ports = [];
if (is_int(key($a_inventory['networkport']))) {
$a_ports = $a_inventory['networkport'];
} else {
$a_ports[] = $a_inventory['networkport'];
}
foreach ($a_ports as $port) {
if (!empty($port['mac'])) {
$input['mac'][] = $port['mac'];
}
if (!empty($port['ip'])) {
$input['ip'][] = $port['ip'];
}
}
}
}
if (!empty($a_inventory[$a_inventory['itemtype']]['networkequipmentmodels_id'])) {
$input['model'] = $a_inventory[$a_inventory['itemtype']]['networkequipmentmodels_id'];
}
if (!empty($a_inventory[$a_inventory['itemtype']]['name'])) {
$input['name'] = $a_inventory[$a_inventory['itemtype']]['name'];
}
$_SESSION['plugin_fusinvsnmp_datacriteria'] = serialize($input);
$_SESSION['plugin_fusioninventory_classrulepassed'] =
"PluginFusioninventoryCommunicationNetworkInventory";
$rule = new PluginFusioninventoryInventoryRuleImportCollection();
PluginFusioninventoryConfig::logIfExtradebug("pluginFusioninventory-rules",
"Input data : ".print_r($input, true));
$data = $rule->processAllRules($input, []);
PluginFusioninventoryConfig::logIfExtradebug("pluginFusioninventory-rules",
$data);
if (isset($data['action'])
&& ($data['action'] == PluginFusioninventoryInventoryRuleImport::LINK_RESULT_DENIED)) {
$a_text = [];
foreach ($input as $key=>$data) {
if (is_array($data)) {
$a_text[] = "[".$key."]:".implode(", ", $data);
} else {
$a_text[] = "[".$key."]:".$data;
}
}
$_SESSION['plugin_fusinvsnmp_taskjoblog']['comment'] = '==importdenied== '.
implode(", ", $a_text);
$this->addtaskjoblog();
$pfIgnoredimportdevice = new PluginFusioninventoryIgnoredimportdevice();
$inputdb = [];
if (isset($input['name'])) {
$inputdb['name'] = $input['name'];
}
$inputdb['date'] = date("Y-m-d H:i:s");
$inputdb['itemtype'] = $input['itemtype'];
if (isset($input['serial'])) {
$input['serialnumber'] = $input['serial'];
}
if (isset($input['ip'])) {
$inputdb['ip'] = exportArrayToDB($input['ip']);
}
if (isset($input['mac'])) {
$inputdb['mac'] = exportArrayToDB($input['mac']);
}
$inputdb['rules_id'] = $_SESSION['plugin_fusioninventory_rules_id'];
$inputdb['method'] = 'networkinventory';
$pfIgnoredimportdevice->add($inputdb);
unset($_SESSION['plugin_fusioninventory_rules_id']);
}
if (isset($data['_no_rule_matches']) AND ($data['_no_rule_matches'] == '1')) {
if (isset($input['itemtype'])
&& isset($data['action'])
&& ($data['action'] == PluginFusioninventoryInventoryRuleImport::LINK_RESULT_CREATE)) {
$errors .= $this->rulepassed(0, $input['itemtype']);
} else if (isset($input['itemtype'])
AND !isset($data['action'])) {
$id_xml = $a_inventory[$a_inventory['itemtype']]['id'];
$classname = $input['itemtype'];
$class = new $classname;
if ($class->getFromDB($id_xml)) {
$errors .= $this->rulepassed($id_xml, $input['itemtype']);
} else {
$errors .= $this->rulepassed(0, $input['itemtype']);
}
} else {
$errors .= $this->rulepassed(0, "PluginFusioninventoryUnmanaged");
}
}
return $errors;
}
/**
* After rules import device
*
* @param integer $items_id id of the device in GLPI DB (0 = created,
* other = merge)
* @param string $itemtype itemtype of the device
* @return string errors or empty string
*/
function rulepassed($items_id, $itemtype, $ports_id = 0) {
$no_history = false;
PluginFusioninventoryLogger::logIfExtradebug(
"pluginFusioninventory-rules",
"Rule passed : ".$items_id.", ".$itemtype."\n"
);
PluginFusioninventoryLogger::logIfExtradebugAndDebugMode(
'fusioninventorycommunication',
'Function PluginFusinvsnmpCommunicationSNMPQuery->rulepassed().'
);
$_SESSION["plugin_fusioninventory_entity"] = 0;
PluginFusioninventoryConfig::logIfExtradebug("pluginFusioninventory-rules",
"Rule passed : ".$items_id.", ".$itemtype."\n");
PluginFusioninventoryCommunication::addLog(
'Function PluginFusioninventoryCommunicationNetworkInventory->rulepassed().');
$a_inventory = $_SESSION['SOURCE_XMLDEVICE'];
$errors = '';
$class = new $itemtype;
if ($items_id == "0") {
$input = [];
$input['date_mod'] = date("Y-m-d H:i:s");
if ($class->getFromDB($a_inventory[$a_inventory['itemtype']]['id'])) {
$input['entities_id'] = $class->fields['entities_id'];
} else {
$input['entities_id'] = 0;
}
if (!isset($_SESSION['glpiactiveentities_string'])) {
$_SESSION['glpiactiveentities_string'] = "'".$input['entities_id']."'";
}
$_SESSION["plugin_fusioninventory_entity"] = $input['entities_id'];
//Add defaut status if there's one defined in the configuration
$input = PluginFusioninventoryToolbox::addDefaultStateIfNeeded('snmp', $input);
$items_id = $class->add($input);
$no_history = true;
if (isset($_SESSION['plugin_fusioninventory_rules_id'])) {
$pfRulematchedlog = new PluginFusioninventoryRulematchedlog();
$inputrulelog = [];
$inputrulelog['date'] = date('Y-m-d H:i:s');
$inputrulelog['rules_id'] = $_SESSION['plugin_fusioninventory_rules_id'];
if (isset($_SESSION['plugin_fusioninventory_agents_id'])) {
$inputrulelog['plugin_fusioninventory_agents_id'] =
$_SESSION['plugin_fusioninventory_agents_id'];
}
$inputrulelog['items_id'] = $items_id;
$inputrulelog['itemtype'] = $itemtype;
$inputrulelog['method'] = 'networkinventory';
$inputrulelog['criteria'] = exportArrayToDB(unserialize($_SESSION['plugin_fusinvsnmp_datacriteria']));
$pfRulematchedlog->add($inputrulelog);
$pfRulematchedlog->cleanOlddata($items_id, $itemtype);
unset($_SESSION['plugin_fusioninventory_rules_id']);
}
}
if ($itemtype == "PluginFusioninventoryUnmanaged") {
$class->getFromDB($items_id);
$input = [];
$input['id'] = $class->fields['id'];
if (!empty($a_inventory[$a_inventory['itemtype']]['name'])) {
$input['name'] = $a_inventory[$a_inventory['itemtype']]['name'];
}
if (!empty($a_inventory[$a_inventory['itemtype']]['serial'])) {
$input['serial'] = $a_inventory[$a_inventory['itemtype']]['serial'];
}
if (!empty($a_inventory['itemtype'])) {
$input['itemtype'] = $a_inventory['itemtype'];
}
// TODO : add import ports
PluginFusioninventoryToolbox::writeXML($items_id,
serialize($_SESSION['SOURCE_XMLDEVICE']),
'PluginFusioninventoryUnmanaged');
$class->update($input);
$_SESSION['plugin_fusinvsnmp_taskjoblog']['comment'] =
'[==detail==] ==updatetheitem== Update '.
PluginFusioninventoryUnmanaged::getTypeName().
' [[PluginFusioninventoryUnmanaged::'.$items_id.']]';
$this->addtaskjoblog();
} else {
$_SESSION['plugin_fusinvsnmp_taskjoblog']['comment'] =
'[==detail==] Update '.$class->getTypeName().' [['.$itemtype.'::'.$items_id.']]';
$this->addtaskjoblog();
$errors .= $this->importDevice($itemtype, $items_id, $a_inventory, $no_history);
}
return $errors;
}
/**
* Add log in the taskjob
*/
function addtaskjoblog() {
if (!isset($_SESSION['plugin_fusinvsnmp_taskjoblog']['taskjobs_id'])) {
return;
}
$pfTaskjoblog = new PluginFusioninventoryTaskjoblog();
$pfTaskjoblog->addTaskjoblog(
$_SESSION['plugin_fusinvsnmp_taskjoblog']['taskjobs_id'],
$_SESSION['plugin_fusinvsnmp_taskjoblog']['items_id'],
$_SESSION['plugin_fusinvsnmp_taskjoblog']['itemtype'],
$_SESSION['plugin_fusinvsnmp_taskjoblog']['state'],
$_SESSION['plugin_fusinvsnmp_taskjoblog']['comment']);
}
/**
* Get method name linked to this class
*
* @return string
*/
static function getMethod() {
return 'networkinventory';
}
/**
* Detect if the device is a stacked switch.
* We use the level / dependencies of the components from root level
*
* case 1 :
* * type stack
* * type chassis with serial number (minimum of 2 chassis)
*
* case 2 :
* * type chassis with serial number (minimum of 2 chassis)
*
*/
function is_stacked_switch($a_inventory, $parent_index = 0) {
if (count($a_inventory['components']) == 0) {
return false;
}
$stack_chassis = 0;
foreach ($a_inventory['components'] as $component) {
if ($parent_index == 0
&& !isset($component['parent_index'])
&& $component['type'] == 'stack') {
$stack_chassis += $this->is_stacked_switch($a_inventory, $component['index']);
} else if ($component['type'] == 'chassis'
&& isset($component['serial'])) {
$stack_chassis++;
}
}
if ($stack_chassis >= 2) {
return true;
}
return false;
}
/**
* We split stacked switches to manage them individually
*
* the ports field ifname has the number of the switch, for example:
* - Gi1/0/1 (switch 1)
* - Gi2/0/1 (swicth 2)
*
* @param type $a_inventory
*/
function split_stacked_switch($a_inventory) {
$xml_devices = $this->get_stacked_switches_information($a_inventory);
ksort($xml_devices);
$devices = [];
// split the switch
// create new inventory for each switch
$portswitchid = 1;
$num = 0;
foreach ($xml_devices as $xml_device) {
$devices[$num] = [
'NetworkEquipment' => $a_inventory['NetworkEquipment'],
'itemtype' => 'NetworkEquipment',
'PluginFusioninventoryNetworkEquipment' => $a_inventory['PluginFusioninventoryNetworkEquipment'],
'firmwares' => $a_inventory['firmwares'],
'internalport' => $a_inventory['internalport'],
'networkport' => [],
'connection-lldp' => $a_inventory['connection-lldp'],
'connection-mac' => $a_inventory['connection-mac'],
'components' => []
];
// Overwrite couple of information
$devices[$num]['firmwares'][0]['version'] = $xml_device['version'];
$devices[$num]['NetworkEquipment']['serial'] = $xml_device['serial'];
$devices[$num]['NetworkEquipment']['networkequipmentmodels_id'] = $xml_device['model'];
$devices[$num]['NetworkEquipment']['name'] .= " - ".$xml_device['name'];
// TODO: mettre les sous-composants ici
// ports
foreach ($a_inventory['networkport'] as $port) {
$matches = [];
preg_match('/([\w-]+)(\d+)\/(\d+)\/(\d+)/', $port['name'], $matches);
if (count($matches) == 5) {
if ($portswitchid != $matches[2]) {
continue;
}
$devices[$num]['networkport'][] = $port;
} else {
// Generic port, so add in all devices
$devices[$num]['networkport'][] = $port;
}
}
$num++;
$portswitchid++;
}
return $devices;
}
function get_stacked_switches_information($a_inventory, $parent_index = 0) {
if (count($a_inventory['components']) == 0) {
return [];
}
$switches = [];
foreach ($a_inventory['components'] as $component) {
if ($parent_index == 0
&& (!isset($component['parent_index'])
|| !empty($component['parent_index']))
&& $component['type'] == 'stack') {
$switches += $this->get_stacked_switches_information($a_inventory, $component['index']);
} else if ($component['type'] == 'chassis'
&& isset($component['serial'])) {
$switches[$component['index']] = $component;
}
}
return $switches;
}
function is_wireless_controller($a_inventory, $parent_index = 0) {
if (count($a_inventory['components']) == 0) {
return false;
}
$accesspoint = false;
foreach ($a_inventory['components'] as $component) {
if (!empty($component['ip'])
&& !empty($component['mac'])) {
$accesspoint = true;
return $accesspoint;
}
}
return $accesspoint;
}
function get_wireless_controller_access_points($a_inventory) {
$accesspoints = [];
$num = 0;
foreach ($a_inventory['components'] as $component) {
if (!empty($component['ip'])
&& !empty($component['mac'])) {
$accesspoints[$num] = [
'NetworkEquipment' => [
'id' => 0,
'locations_id' => '',
'mac' => $component['mac'],
'manufacturers_id' => '',
'networkequipmentmodels_id' => $component['model'],
'name' => $component['name'],
'serial' => $component['serial'],
'memory' => 0,
'ram' => 0,
'is_dynamic' => 1
],
'itemtype' => 'NetworkEquipment',
'PluginFusioninventoryNetworkEquipment' => [
'last_fusioninventory_update' => $a_inventory['PluginFusioninventoryNetworkEquipment']['last_fusioninventory_update']
],
'firmwares' => [
[
'description' => $component['comment'],
'manufacturers_id' => '',
'name' => $component['model'],
'devicefirmwaretypes_id' => 'device',
'version' => $component['version']
]
],
'internalport' => [$component['ip']],
'networkport' => [],
'components' => []
];
$num++;
}
}
return $accesspoints;
}
}

View File

@@ -0,0 +1,308 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the communication in REST with the agents.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author Vincent Mazzoni
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the communication in REST with the agents.
*/
class PluginFusioninventoryCommunicationRest {
/**
* Manage communication between agent and server
*
* @param array $params
* @return array|false array return jobs ready for the agent
*/
static function communicate($params = []) {
$response = [];
if (isset ($params['action']) && isset($params['machineid'])) {
if (PluginFusioninventoryAgent::getByDeviceID($params['machineid'])) {
switch ($params['action']) {
case 'getConfig':
$response = self::getConfigByAgent($params);
break;
case 'getJobs':
$response = self::getJobsByAgent($params);
break;
case 'wait':
break;
}
} else {
$response = false;
}
} else {
$response = false;
}
return $response;
}
/**
* Get configuration for an agent and for modules requested
*
* @param array $params
* @return array
*/
static function getConfigByAgent($params = []) {
$schedule = [];
if (isset($params['task'])) {
$pfAgentModule = new PluginFusioninventoryAgentmodule();
$a_agent = PluginFusioninventoryAgent::getByDeviceID($params['machineid']);
foreach (array_keys($params['task']) as $task) {
foreach (PluginFusioninventoryStaticmisc::getmethods() as $method) {
switch (strtolower($task)) {
case 'deploy':
$classname = 'PluginFusioninventoryDeployPackage';
break;
case 'esx':
$classname = 'PluginFusioninventoryCredentialIp';
break;
case 'collect':
$classname = 'PluginFusioninventoryCollect';
break;
default:
$classname = '';
}
$taskname = $method['method'];
if (strstr($taskname, 'deploy')) {
$taskname = $method['task'];
}
$class = PluginFusioninventoryStaticmisc::getStaticMiscClass($method['module']);
if ((isset($method['task']) && strtolower($method['task']) == strtolower($task))
&& (isset($method['use_rest']) && $method['use_rest'])
&& method_exists($class, self::getMethodForParameters($task))
&& $pfAgentModule->isAgentCanDo($taskname, $a_agent['id'])
&& countElementsInTable('glpi_plugin_fusioninventory_taskjobstates',
[
'plugin_fusioninventory_agents_id' => $a_agent['id'],
'itemtype' => $classname,
'state' => 0,
]) > 0) {
/*
* Since migration, there is only one plugin in one directory
* It's maybe time to redo this function -- kiniou
*/
$schedule[]
= call_user_func([$class, self::getMethodForParameters($task)],
$a_agent['entities_id']);
break; //Stop the loop since we found the module corresponding to the asked task
}
}
}
}
return ['configValidityPeriod' => 600, 'schedule' => $schedule];
}
/**
* Get jobs for an agent
* TODO: This methods must be used inplace of other methods in order to mutualize code and
* to fully support FusionInventory REST API for every task's types
* -- kiniou
*
* @param array $params
* @return false
*/
static function getJobsByAgent($params = []) {
// $jobs = [];
// $methods = PluginFusioninventoryStaticmisc::getmethods();
// if (isset($params['task'])) {
// foreach (array_keys($params['task']) as $task) {
//
// }
// }
return false;
}
/**
* Send to the agent an OK code
*/
static function sendOk() {
header("HTTP/1.1 200", true, 200);
}
/**
* Send to the agent an error code
* when the request sent by the agent is invalid
*/
static function sendError() {
header("HTTP/1.1 400", true, 400);
}
/**
* Generate the function name related to the module to get parameters
*
* @param string $task
* @return string
*/
static function getMethodForParameters($task) {
return "task_".strtolower($task)."_getParameters";
}
/**
* Update agent status for a taskjob
*
* @global object $DB
* @param array $params
*/
static function updateLog($params = []) {
global $DB;
$p = [];
$p['machineid'] = ''; //DeviceId
$p['uuid'] = ''; //Task uuid
$p['msg'] = 'ok'; //status of the task
$p['code'] = ''; //current step of processing
$p['sendheaders'] = true;
foreach ($params as $key => $value) {
$p[$key] = $value;
}
//Get the agent ID by its deviceid
$agent = PluginFusioninventoryAgent::getByDeviceID($p['machineid']);
//No need to continue since the requested agent doesn't exists in database
if ($agent === false) {
if ($p['sendheaders']) {
self::sendError();
}
return;
}
$taskjobstate = new PluginFusioninventoryTaskjobstate();
//Get task job status : identifier is the uuid given by the agent
$params = ['FROM' => getTableForItemType("PluginFusioninventoryTaskjobstate"),
'FIELDS' => 'id',
'WHERE' => ['uniqid' => $p['uuid']]
];
foreach ($DB->request($params) as $jobstate) {
$taskjobstate->getFromDB($jobstate['id']);
//Get taskjoblog associated
$taskjoblog = new PluginFusioninventoryTaskjoblog();
switch ($p['code']) {
case 'running':
$taskjoblog->addTaskjoblog(
$taskjobstate->fields['id'],
$taskjobstate->fields['items_id'],
$taskjobstate->fields['itemtype'],
PluginFusioninventoryTaskjoblog::TASK_RUNNING,
$p['msg']
);
break;
case 'ok':
case 'ko':
$taskjobstate->changeStatusFinish(
$taskjobstate->fields['id'],
$taskjobstate->fields['items_id'],
$taskjobstate->fields['itemtype'],
($p['code'] == 'ok'?0:1),
$p['msg']
);
break;
}
}
if ($p['sendheaders']) {
self::sendOk();
}
}
/**
* Test a given url
*
* @param string $url
* @return boolean
*/
static function testRestURL($url) {
//If fopen is not allowed, we cannot check and then return true...
if (!ini_get('allow_url_fopen')) {
return true;
}
$handle = fopen($url, 'rb');
if (!$handle) {
return false;
} else {
fclose($handle);
return true;
}
}
/**
* Manage REST parameters
**/
static function handleFusionCommunication() {
$response = PluginFusioninventoryCommunicationRest::communicate($_GET);
if ($response) {
echo json_encode($response);
} else {
PluginFusioninventoryCommunicationRest::sendError();
}
}
}

View File

@@ -0,0 +1,215 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the search in groups (static and dynamic).
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the search in groups (static and dynamic).
*/
class PluginFusioninventoryComputer extends Computer {
/**
* The right name for this class
*
* @var string
*/
static $rightname = "plugin_fusioninventory_group";
function rawSearchOptions() {
$computer = new Computer();
$options = $computer->rawSearchOptions();
$plugin = new Plugin();
if ($plugin->isInstalled('fields')) {
if ($plugin->isActivated('fields')) {
// Include Fields hook from correct installation folder (marketplace or plugins)
include_once(Plugin::GetPhpDir("fields") . "/hook.php");
$options['fields_plugin'] = [
'id' => 'fields_plugin',
'name' => __('Plugin fields')
];
$fieldsoptions = plugin_fields_getAddSearchOptions('Computer');
foreach ($fieldsoptions as $id=>$data) {
$data['id'] = $id;
$options[$id] = $data;
}
}
}
return $options;
}
/**
* Get the massive actions for this object
*
* @param object|null $checkitem
* @return array list of actions
*/
function getSpecificMassiveActions($checkitem = null) {
$actions = [];
if (strstr(filter_input(INPUT_SERVER, "PHP_SELF"), '/report.dynamic.php')) {
// In case we export list (CSV, PDF...) we do not have massive actions.
return $actions;
}
if (isset($_GET['id'])) {
$id = $_GET['id'];
} else {
$id = $_POST['id'];
}
$group = new PluginFusioninventoryDeployGroup();
$group->getFromDB($id);
//There's no massive action associated with a dynamic group !
if ($group->isDynamicGroup() || !$group->canEdit($group->getID())) {
return [];
}
if (!isset($_POST['custom_action'])) {
$actions['PluginFusioninventoryComputer'.MassiveAction::CLASS_ACTION_SEPARATOR.'add']
= _x('button', 'Add to associated items of the group');
$actions['PluginFusioninventoryComputer'.MassiveAction::CLASS_ACTION_SEPARATOR.'deleteitem']
= _x('button', 'Remove from associated items of the group');
} else {
if ($_POST['custom_action'] == 'add_to_group') {
$actions['PluginFusioninventoryComputer'.MassiveAction::CLASS_ACTION_SEPARATOR.'add']
= _x('button', 'Add to associated items of the group');
} else if ($_POST['custom_action'] == 'delete_from_group') {
$actions['PluginFusioninventoryComputer'.MassiveAction::CLASS_ACTION_SEPARATOR.'deleteitem']
= _x('button', 'Remove from associated items of the group');
}
}
return $actions;
}
/**
* Define the standard massive actions to hide for this class
*
* @return array list of massive actions to hide
*/
function getForbiddenStandardMassiveAction() {
$forbidden = parent::getForbiddenStandardMassiveAction();
$forbidden[] = 'update';
$forbidden[] = 'add';
$forbidden[] = 'delete';
return $forbidden;
}
/**
* Execution code for massive action
*
* @param object $ma MassiveAction instance
* @param object $item item on which execute the code
* @param array $ids list of ID on which execute the code
*/
static function processMassiveActionsForOneItemtype(MassiveAction $ma, CommonDBTM $item, array $ids) {
$group_item = new PluginFusioninventoryDeployGroup_Staticdata();
switch ($ma->getAction()) {
case 'add' :
foreach ($ids as $key) {
if ($item->can($key, UPDATE)) {
if (!countElementsInTable($group_item->getTable(),
[
'plugin_fusioninventory_deploygroups_id' => $_POST['id'],
'itemtype' => 'Computer',
'items_id' => $key,
])) {
$group_item->add([
'plugin_fusioninventory_deploygroups_id'
=> $_POST['id'],
'itemtype' => 'Computer',
'items_id' => $key]);
$ma->itemDone($item->getType(), $key, MassiveAction::ACTION_OK);
} else {
$ma->itemDone($item->getType(), $key, MassiveAction::ACTION_KO);
}
} else {
$ma->itemDone($item->getType(), $key, MassiveAction::ACTION_NORIGHT);
$ma->addMessage($item->getErrorMessage(ERROR_RIGHT));
}
}
return;
case 'deleteitem':
foreach ($ids as $key) {
if ($group_item->deleteByCriteria(['items_id' => $key,
'itemtype' => 'Computer',
'plugin_fusioninventory_deploygroups_id'
=> $_POST['id']])) {
$ma->itemDone($item->getType(), $key, MassiveAction::ACTION_OK);
} else {
$ma->itemDone($item->getType(), $key, MassiveAction::ACTION_KO);
}
}
}
}
/**
* Display form related to the massive action selected
*
* @param object $ma MassiveAction instance
* @return boolean
*/
static function showMassiveActionsSubForm(MassiveAction $ma) {
if ($ma->getAction() == 'add') {
echo "<br><br>".Html::submit(_x('button', 'Add'),
['name' => 'massiveaction']);
return true;
}
return parent::showMassiveActionsSubForm($ma);
}
}

View File

@@ -0,0 +1,310 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the software licenses found on the computer.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author Gonéri Le Bouder
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the software licenses found on the computer.
*/
class PluginFusioninventoryComputerLicenseInfo extends CommonDBTM {
/**
* The right name for this class
*
* @var string
*/
static $rightname = 'license';
/**
* Get name of this type by language of the user connected
*
* @param integer $nb number of elements
* @return string name of this type
*/
static function getTypeName($nb = 0) {
return __('FusionInventory', 'fusioninventory')
.' - '._n('License', 'Licenses', $nb);
}
/**
* Display form
*
* @global array $CFG_GLPI
* @param integer $computers_id id of the computer
* @return true
*/
function showForm($computers_id) {
global $CFG_GLPI, $DB;
$iterator = $DB->request('glpi_plugin_fusioninventory_computerlicenseinfos',
['computers_id' => $computers_id]);
if ($iterator->numrows()) {
echo '<div align="center">';
echo "<form method='POST' action='".self::getFormURL()."'>";
echo '<table class="tab_cadre_fixe">';
echo '<tr>';
echo '<th colspan="4">'.self::getTypeName($iterator->numrows()).'</th>';
echo '</tr>';
foreach ($iterator as $licenseInfo) {
$is_linked = (!empty($licenseInfo['softwarelicenses_id']));
echo "<tr class='tab_bg_1'>";
echo "<td>".__('Name')."</td>";
$license_options = '';
if ($licenseInfo['is_update']
|| $licenseInfo['is_trial']
|| $licenseInfo['is_oem']) {
$options = [];
$fields = ['is_update' => _sx('name', 'Update'),
'is_trial' => __('Trial', 'fusioninventory'),
'is_oem' => __('OEM', 'fusioninventory')];
foreach ($fields as $field => $label) {
if ($licenseInfo[$field]) {
array_push($options, $label);
}
}
$license_options = __('Option', 'fusioninventory')
."&nbsp;(".implode(', ', $options).")";
}
echo "<td>";
if (!empty($licenseInfo['fullname'])) {
echo $licenseInfo['fullname'];
} else {
echo $licenseInfo['name'];
}
echo $license_options."</td>";
echo "<td>".__('Serial number')."</td>";
echo "<td>".$licenseInfo['serial']."</td>";
echo "</tr>";
echo "<tr class='tab_bg_1'>";
echo "<td>".__('Linked to')."</td>";
echo "<td colspan='3'>";
if ($is_linked) {
$license = new SoftwareLicense();
$license->getFromDB($licenseInfo['softwarelicenses_id']);
echo Html::hidden('computers_id',
['value' => $licenseInfo['computers_id']]);
echo $license->getLink(['comments' => true,
'completename' => true]);
echo "&nbsp;";
echo Html::submit(_sx('button', 'Dissociate'),
['name' => "dissociate[".$licenseInfo['id']."]='1'",
'image' => $CFG_GLPI['root_doc'].'/pics/delete.png',
'class' => '',
]);
} else {
echo Html::hidden('computers_id',
['value' => $licenseInfo['computers_id']]);
$rand = mt_rand();
$pfComputerLicenseInfo = new self();
$params = ['softwarelicenses_id' => $licenseInfo['softwarelicenses_id'],
'name' => $licenseInfo['name'],
'fullname' => $licenseInfo['fullname'],
'serial' => $licenseInfo['serial'],
'licenseid' => $licenseInfo['id']
];
$pfComputerLicenseInfo->dropdownSoftwareLicenses($params);
}
echo "</td>";
echo "</tr>";
}
echo '<tr><th colspan="4"></th></tr>';
echo '</table>';
Html::closeForm();
echo '</div>';
}
return true;
}
/**
* Dropdown of software licenses found with information given
*
* @global object $DB
* @param array $params
*/
function dropdownSoftwareLicenses($params) {
global $DB, $CFG_GLPI;
$query = "SELECT `glpi_softwares`.`name` as sname,
`glpi_softwarelicenses`.`name` as lname,
`glpi_softwarelicenses`.`id` as lid,
`glpi_softwarelicenses`.`serial` FROM `glpi_softwarelicenses`
LEFT JOIN `glpi_softwares`
ON `glpi_softwarelicenses`.`softwares_id` = `glpi_softwares`.`id`
WHERE ((`glpi_softwarelicenses`.`name` LIKE '%".$params['name']."%'
OR `glpi_softwarelicenses`.`name` LIKE '%".$params['fullname']."%'
OR `glpi_softwares`.`name` LIKE '%".$params['name']."%'
OR `glpi_softwares`.`name` LIKE '%".$params['fullname']."%')
AND `serial` = '".$params['serial']."')
OR (`glpi_softwarelicenses`.`name` = '".$params['serial']."'
OR `serial` = '".$params['serial']."')";
$licenses = [];
foreach ($DB->request($query) as $data) {
$licenses[$data['lid']] = $data['sname']." (".$data['serial'].")";
}
if (!empty($licenses)) {
Dropdown::showFromArray('softwarelicenses_id', $licenses,
['value' => $params['softwarelicenses_id']]);
echo "&nbsp;";
echo Html::submit(_sx('button', 'Associate'),
['name' => "associate[".$params['licenseid']."]='1'",
'image' => $CFG_GLPI['root_doc'].'/pics/add_dark.png',
'class' => ''
]);
} else {
echo __("No item found");
}
}
/**
* Associate a license found on computer and a license managed in GLPI
*
* @param array $params
*/
function associate($params) {
if (isset($params['computers_id']) && is_array($params['associate'])) {
$computer_slicense = new Item_SoftwareLicense();
$pfLicenseInfo = new self();
foreach ($params['associate'] as $key => $value) {
$computer_slicense->add([
'itemtype' => 'Computer',
'items_id' => $params['computers_id'],
'softwarelicenses_id' => $params['softwarelicenses_id'],
'is_deleted' => 0,
'is_dynamic' => 1
]);
$pfLicenseInfo->update([
'id' => $key,
'softwarelicenses_id' => $params['softwarelicenses_id']
]);
}
}
}
/**
* Dissociate a license found on computer and a license managed in GLPI
*
* @param array $params
*/
function dissociate($params) {
if (isset($params['computers_id']) && is_array($params['dissociate'])) {
$pfLicenseInfo = new self();
$computer_slicense = new Item_SoftwareLicense();
foreach ($params['dissociate'] as $key => $value) {
$pfLicenseInfo->getFromDB($key);
$computer_slicense->deleteByCriteria([
'itemtype' => 'Computer',
'items_id' => $params['computers_id'],
'softwarelicenses_id' => $pfLicenseInfo->fields['softwarelicenses_id']], true);
$pfLicenseInfo->update(['id' => $key,
'softwarelicenses_id' => 0]);
}
}
}
/**
* Delete all licenses linked to the computer (most cases when delete a
* computer)
*
* @param integer $computers_id
*/
static function cleanComputer($computers_id) {
$license = new self();
$license->deleteByCriteria(['computers_id' => $computers_id]);
}
/**
* Delete all licenses linked to the computer (most cases when delete a
* computer)
*
* @param integer $computers_id
*/
static function cleanLicense(Item_SoftwareLicense $license) {
$licenses = getAllDataFromTable('glpi_plugin_fusioninventory_computerlicenseinfos',
[
'softwarelicenses_id' => $license->fields['softwarelicenses_id'],
'computers_id' => $license->fields['computers_id'],
]);
if (!empty($licenses)) {
$lic = current($licenses);
$pfLicenseInfo = new self();
$pfLicenseInfo->update(['id' => $lic['id'], 'softwarelicenses_id' => 0]);
}
}
}

View File

@@ -0,0 +1,123 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the remote management information of
* softwares installed on computer.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the remote management information of softwares installed on computer.
*/
class PluginFusioninventoryComputerRemoteManagement extends CommonDBTM {
/**
* The right name for this class
*
* @var string
*/
static $rightname = 'computer';
/**
* Get name of this type by language of the user connected
*
* @param integer $nb number of elements
* @return string name of this type
*/
static function getTypeName($nb = 0) {
return __('Remote management', 'fusioninventory');
}
/**
* Display remote management information
*
* @param integer $computers_id
* @return true
*/
function showInformation($computers_id) {
$pfRemoteManagement = new self();
$a_remotemanagement = $pfRemoteManagement->find(['computers_id' => $computers_id]);
if (count($a_remotemanagement)) {
echo '<tr>';
echo '<th colspan="4">'.__('Remote management', 'fusioninventory').'</th>';
echo '</tr>';
foreach ($a_remotemanagement as $remotemanagement) {
echo "<tr class='tab_bg_1'>";
echo "<td>".$remotemanagement['type']."</td>";
if ($remotemanagement['type'] == "teamviewer") {
echo "<td><a href='https://start.teamviewer.com/".$remotemanagement['number']."'>".$remotemanagement['number']."</a></td>";
} else {
echo "<td>".$remotemanagement['number']."</td>";
}
echo "<td colspan='2'>";
echo "</tr>";
}
}
return true;
}
/**
* Delete all remote management information linked to the computer
* (most cases when delete a computer)
*
* @param integer $computers_id
*/
static function cleanComputer($computers_id) {
$pfComputerRemoteManagement = new self();
$pfComputerRemoteManagement->deleteByCriteria(['computers_id' => $computers_id]);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,255 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the configuration of logs of network
* inventory (network equipment and printer).
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access this file directly");
}
/**
* Manage the configuration of logs of network inventory (network equipment
* and printer).
*/
class PluginFusioninventoryConfigLogField extends CommonDBTM {
/**
* Init config log fields : add default values in table
*
* @global object $DB
*/
function initConfig() {
global $DB;
$NOLOG = '-1';
$logs = [
'NetworkEquipment' => [
'ifdescr' => $NOLOG,
'ifIndex' => $NOLOG,
'ifinerrors' => $NOLOG,
'ifinoctets' => $NOLOG,
'ifinternalstatus' => $NOLOG,
'iflastchange' => $NOLOG,
'ifmtu' => $NOLOG,
'ifName' => $NOLOG,
'ifouterrors' => $NOLOG,
'ifoutoctets' => $NOLOG,
'ifspeed' => $NOLOG,
'ifstatus' => $NOLOG,
'macaddr' => $NOLOG,
'portDuplex' => $NOLOG,
'trunk' => $NOLOG
],
'Printer' => [
'ifIndex' => $NOLOG,
'ifName' => $NOLOG
]
];
$mapping = new PluginFusioninventoryMapping();
foreach ($logs as $itemtype=>$fields) {
foreach ($fields as $name=>$value) {
$input = [];
$mapfields = $mapping->get($itemtype, $name);
if ($mapfields != false) {
if (!$this->getValue($mapfields['id'])) {
$input['plugin_fusioninventory_mappings_id'] = $mapfields['id'];
$input['days'] = $value;
$this->add($input);
} else {
// On old version, can have many times same value in DB
$query = "SELECT * FROM `glpi_plugin_fusioninventory_configlogfields`
WHERE `plugin_fusioninventory_mappings_id` = '".$mapfields['id']."'
LIMIT 1,1000";
$result=$DB->query($query);
$delete = $DB->buildDelete(
'glpi_plugin_fusioninventory_configlogfields', [
'id' => new \QueryParam()
]
);
$stmt = $DB->prepare($delete);
while ($data=$DB->fetchArray($result)) {
$stmt->bind_param('s', $data['id']);
$stmt->execute();
}
mysqli_stmt_close($stmt);
}
}
}
}
}
/**
* Get the value of a field in configlog
*
* @global object $DB
* @param string $field
* @return string|false
*/
function getValue($field) {
global $DB;
$query = "SELECT days
FROM ".$this->getTable()."
WHERE `plugin_fusioninventory_mappings_id`='".$field."'
LIMIT 1;";
$result = $DB->query($query);
if ($result) {
$fields = $DB->fetchRow($result);
if ($fields) {
$this->fields = $fields;
return $this->fields['0'];
}
}
return false;
}
/**
* Display form
*
* @global object $DB
* @param array $options
* @return true
*/
function showForm($options = []) {
global $DB;
$mapping = new PluginFusioninventoryMapping();
echo "<form name='form' method='post' action='".$options['target']."'>";
echo "<div class='center' id='tabsbody'>";
echo "<table class='tab_cadre_fixe'>";
echo "<tr>";
echo "<th colspan='2'>";
echo __('History configuration', 'fusioninventory');
echo "</th>";
echo "</tr>";
echo "<tr>";
echo "<th>";
echo __('List of fields for which to keep history', 'fusioninventory');
echo "</th>";
echo "<th>";
echo __('Retention in days', 'fusioninventory');
echo "</th>";
echo "</tr>";
$days = [];
$days[-1] = __('Never');
$days[0] = __('Always');
for ($i = 1; $i < 366; $i++) {
$days[$i] = "$i";
}
$query = "SELECT `".$this->getTable()."`.`id`, `locale`, `days`, `itemtype`, `name`
FROM `".$this->getTable()."`, `glpi_plugin_fusioninventory_mappings`
WHERE `".$this->getTable()."`.`plugin_fusioninventory_mappings_id`=
`glpi_plugin_fusioninventory_mappings`.`id`
ORDER BY `itemtype`, `name`;";
$result=$DB->query($query);
if ($result) {
while ($data=$DB->fetchArray($result)) {
echo "<tr class='tab_bg_1'>";
echo "<td align='left'>";
echo $mapping->getTranslation($data);
echo "</td>";
echo "<td align='center'>";
Dropdown::showFromArray('field-'.$data['id'], $days,
['value'=>$data['days']]);
echo "</td>";
echo "</tr>";
}
}
if (Session::haveRight('plugin_fusioninventory_configuration', UPDATE)) {
echo "<tr class='tab_bg_2'><td align='center' colspan='4'>
<input type='hidden' name='tabs' value='history'/>
<input class='submit' type='submit' name='update'
value='" . __('Update') . "'></td></tr>";
}
echo "</table>";
echo "<br/>";
echo "<table class='tab_cadre_fixe' cellpadding='2'>";
echo "<tr class='tab_bg_2'>";
echo "<td colspan='1' class='center' height='30'>";
if (Session::haveRight('plugin_fusioninventory_configuration', UPDATE)) {
echo "<input type='submit' class=\"submit\" name='Clean_history' ".
"value='"._x('button', 'Clean')."' >";
}
echo "</td>";
echo "</tr>";
echo "</table></div>";
Html::closeForm();
return true;
}
/**
* Update data in database
*
* @param array $p_post
*/
function putForm($p_post) {
foreach ($p_post as $field=>$log) {
if (substr($field, 0, 6) == 'field-') {
$input = [];
$input['id'] = substr($field, 6);
$input['days'] = $log;
$this->update($input);
}
}
}
}

View File

@@ -0,0 +1,409 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage SNMP credentials: v1, v2c and v3
* support.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access this file directly");
}
/**
* Manage SNMP credentials: v1, v2c and v3 support.
*/
class PluginFusioninventoryConfigSecurity extends CommonDBTM {
/**
* We activate the history.
*
* @var boolean
*/
public $dohistory = true;
/**
* The right name for this class
*
* @var string
*/
static $rightname = 'plugin_fusioninventory_configsecurity';
/**
* Define tabs to display on form page
*
* @param array $options
* @return array containing the tabs name
*/
function defineTabs($options = []) {
$ong = [];
$this->addStandardTab('Log', $ong, $options);
return $ong;
}
/**
* Display form
*
* @param integer $id
* @param array $options
* @return true
*/
function showForm($id, $options = []) {
Session::checkRight('plugin_fusioninventory_configsecurity', READ);
$this->initForm($id, $options);
$this->showFormHeader($options);
echo "<tr class='tab_bg_1'>";
echo "<td align='center' colspan='2'>" . __('Name') . "</td>";
echo "<td align='center' colspan='2'>";
Html::autocompletionTextField($this, 'name');
echo "</td>";
echo "</tr>";
echo "<tr class='tab_bg_1'>";
echo "<td align='center' colspan='2'>" . __('SNMP version', 'fusioninventory') . "</td>";
echo "<td align='center' colspan='2'>";
$this->showDropdownSNMPVersion($this->fields["snmpversion"]);
echo "</td>";
echo "</tr>";
echo "<tr class='tab_bg_1'>";
echo "<th colspan='2'>v 1 & v 2c</th>";
echo "<th colspan='2'>v 3</th>";
echo "</tr>";
echo "<tr class='tab_bg_1'>";
echo "<td align='center'>" . __('Community', 'fusioninventory') . "</td>";
echo "<td align='center'>";
Html::autocompletionTextField($this, 'community');
echo "</td>";
echo "<td align='center'>" . __('User') . "</td>";
echo "<td align='center'>";
// FIXME This is a credential field so it is not in autocomplete whitelist.
// Replace with a simple text input.
Html::autocompletionTextField($this, 'username');
echo "</td>";
echo "</tr>";
echo "<tr class='tab_bg_1'>";
echo "<td colspan='2'></td>";
echo "<td align='center'>".__('Encryption protocol for authentication ', 'fusioninventory').
"</td>";
echo "<td align='center'>";
$this->showDropdownSNMPAuth($this->fields["authentication"]);
echo "</td>";
echo "</tr>";
echo "<tr class='tab_bg_1'>";
echo "<td colspan='2'></td>";
echo "<td align='center'>" . __('Password') . "</td>";
echo "<td align='center'>";
// FIXME This is a credential field so it is not in autocomplete whitelist.
// Replace with a password text input, crypt it, and handle ability to "blank" it.
Html::autocompletionTextField($this, 'auth_passphrase');
echo "</td>";
echo "</tr>";
echo "<tr class='tab_bg_1'>";
echo "<td colspan='2'></td>";
echo "<td align='center'>" . __('Encryption protocol for data', 'fusioninventory') . "</td>";
echo "<td align='center'>";
$this->showDropdownSNMPEncryption($this->fields["encryption"]);
echo "</td>";
echo "</tr>";
echo "<tr class='tab_bg_1'>";
echo "<td colspan='2'></td>";
echo "<td align='center'>" . __('Password') . "</td>";
echo "<td align='center'>";
// FIXME This is a credential field so it is not in autocomplete whitelist.
// Replace with a password text input, crypt it, and handle ability to "blank" it.
Html::autocompletionTextField($this, 'priv_passphrase');
echo "</td>";
echo "</tr>";
$this->showFormButtons($options);
echo "<div id='tabcontent'></div>";
echo "<script type='text/javascript'>loadDefaultTab();</script>";
return true;
}
/**
* Display SNMP version (dropdown)
*
* @param null|string $p_value
*/
function showDropdownSNMPVersion($p_value = null) {
$snmpVersions = [0 => '-----', '1', '2c', '3'];
$options = [];
if (!is_null($p_value)) {
$options = ['value' => $p_value];
}
Dropdown::showFromArray("snmpversion", $snmpVersions, $options);
}
/**
* Get real version of SNMP
*
* @param integer $id
* @return string
*/
function getSNMPVersion($id) {
switch ($id) {
case '1':
return '1';
case '2':
return '2c';
case '3':
return '3';
}
return '';
}
/**
* Display SNMP encryption protocols dropdown
*
* @param null|string $p_value
*/
function showDropdownSNMPAuth($p_value = null) {
$authentications = [0=>'-----', 'MD5', 'SHA'];
$options = [];
if (!is_null($p_value)) {
$options = ['value'=>$p_value];
}
Dropdown::showFromArray("authentication", $authentications, $options);
}
/**
* Get SNMP authentication protocol
*
* @param integer $id
* @return string
*/
function getSNMPAuthProtocol($id) {
switch ($id) {
case '1':
return 'MD5';
case '2':
return 'SHA';
}
return '';
}
/**
* Display SNMP encryption protocols dropdown
*
* @param string $p_value
*/
function showDropdownSNMPEncryption($p_value = null) {
$encryptions = [0 => Dropdown::EMPTY_VALUE, 'DES', 'AES128', 'Triple-DES'];
$options = [];
if (!is_null($p_value)) {
$options = ['value' => $p_value];
}
Dropdown::showFromArray("encryption", $encryptions, $options);
}
/**
* Get SNMP encryption protocol
*
* @param integer $id
* @return string
*/
function getSNMPEncryption($id) {
switch ($id) {
case '1':
return 'DES';
case '2':
return 'AES';
case '5':
return '3DES';
}
return '';
}
/**
* Display SNMP credentials dropdown
*
* @param string $selected
*/
static function authDropdown($selected = "") {
Dropdown::show("PluginFusioninventoryConfigSecurity",
['name' => "plugin_fusioninventory_configsecurities_id",
'value' => $selected,
'comment' => false]);
}
/**
* Display form related to the massive action selected
*
* @param object $ma MassiveAction instance
* @return boolean
*/
static function showMassiveActionsSubForm(MassiveAction $ma) {
if ($ma->getAction() == 'assign_auth') {
PluginFusioninventoryConfigSecurity::authDropdown();
echo Html::submit(_x('button', 'Post'), ['name' => 'massiveaction']);
return true;
}
return false;
}
/**
* Execution code for massive action
*
* @param object $ma MassiveAction instance
* @param object $item item on which execute the code
* @param array $ids list of ID on which execute the code
*/
static function processMassiveActionsForOneItemtype(MassiveAction $ma, CommonDBTM $item,
array $ids) {
$itemtype = $item->getType();
switch ($ma->getAction()) {
case "assign_auth" :
switch ($itemtype) {
case 'NetworkEquipment':
$equipement = new PluginFusioninventoryNetworkEquipment();
break;
case 'Printer':
$equipement = new PluginFusioninventoryPrinter();
break;
case 'PluginFusioninventoryUnmanaged':
$equipement = new PluginFusioninventoryUnmanaged();
break;
}
$fk = getForeignKeyFieldForItemType($itemtype);
foreach ($ids as $key) {
$found = $equipement->find([$fk => $key]);
$input = [];
if (count($found) > 0) {
$current = current($found);
$equipement->getFromDB($current['id']);
$input['id'] = $equipement->fields['id'];
$input['plugin_fusioninventory_configsecurities_id'] =
$_POST['plugin_fusioninventory_configsecurities_id'];
$return = $equipement->update($input);
} else {
$input[$fk] = $key;
$input['plugin_fusioninventory_configsecurities_id'] =
$_POST['plugin_fusioninventory_configsecurities_id'];
$return = $equipement->add($input);
}
if ($return) {
//set action massive ok for this item
$ma->itemDone($item->getType(), $key, MassiveAction::ACTION_OK);
} else {
// KO
$ma->itemDone($item->getType(), $key, MassiveAction::ACTION_KO);
}
}
break;
}
}
function rawSearchOptions() {
$tab = [];
$tab[] = [
'id' => 'common',
'name' => __('Characteristics')
];
$tab[] = [
'id' => '1',
'table' => $this->getTable(),
'field' => 'name',
'name' => __('Name'),
'datatype' => 'itemlink',
'autocomplete' => true,
];
$tab[] = [
'id' => '2',
'table' => $this->getTable(),
'field' => 'community',
'name' => __('Community', 'fusioninventory'),
'datatype' => 'string',
'massiveaction' => false,
'autocomplete' => true,
];
return $tab;
}
}

View File

@@ -0,0 +1,110 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the general configuration tabs (display) in
* plugin Fusioninventory.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author Vincent Mazzoni
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the general configuration tabs (display) in plugin Fusioninventory.
*/
class PluginFusioninventoryConfiguration extends CommonDBTM {
/**
* The right name for this class
*
* @var string
*/
static $rightname = "plugin_fusioninventory_configuration";
/**
* Define tabs to display on form page
*
* @param array $options
* @return array containing the tabs name
*/
function defineTabs($options = []) {
$tabs = [];
$moduleTabs = [];
$tabs[1]=__('General setup');
$tabs[2]=__('Agents modules', 'fusioninventory');
if (isset($_SESSION['glpi_plugin_fusioninventory']['configuration']['moduletabforms'])) {
$fusionTabs = $tabs;
$moduleTabForms =
$_SESSION['glpi_plugin_fusioninventory']['configuration']['moduletabforms'];
if (count($moduleTabForms)) {
foreach ($moduleTabForms as $module=>$form) {
$plugin = new Plugin;
if ($plugin->isActivated($module)) {
$tabs[] = key($form);
}
}
$moduleTabs = array_diff($tabs, $fusionTabs);
}
$_SESSION['glpi_plugin_fusioninventory']['configuration']['moduletabs'] = $moduleTabs;
}
return $tabs;
}
/**
* Display configuration form
*
* @param array $options
* @return true
*/
function showForm($options = []) {
$this->initForm($options);
return true;
}
}

View File

@@ -0,0 +1,426 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the credentials for inventory VMWARE ESX.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the credentials for inventory VMWARE ESX.
*/
class PluginFusioninventoryCredential extends CommonDropdown {
/**
* Define first level menu name
*
* @var string
*/
public $first_level_menu = "admin";
/**
* Define second level menu name
*
* @var string
*/
public $second_level_menu = "pluginfusioninventorymenu";
/**
* Define third level menu name
*
* @var string
*/
public $third_level_menu = "credential";
/**
* The right name for this class
*
* @var string
*/
static $rightname = 'plugin_fusioninventory_credential';
/**
* Get name of this type by language of the user connected
*
* @param integer $nb number of elements
* @return string name of this type
*/
static function getTypeName($nb = 0) {
return __('Authentication for remote devices (VMware)', 'fusioninventory');
}
/**
* Fields added to this class
*
* @return array
*/
function getAdditionalFields() {
return [['name' => 'itemtype',
'label' => __('Type'),
'type' => 'credential_itemtype'],
['name' => 'username',
'label' => __('Login'),
'type' => 'text'],
['name' => 'password',
'label' => __('Password'),
'type' => 'password']];
}
/**
* Display specific fields
*
* @param integer $ID
* @param array $field
*/
function displaySpecificTypeField($ID, $field = []) {
switch ($field['type']) {
case 'credential_itemtype' :
$this->showItemtype($ID);
break;
}
}
/**
* DIsplay the credential itemtype
*
* @param integer $ID
*/
function showItemtype($ID) {
//Criteria already added : only display the selected itemtype
if ($ID > 0) {
$label = self::getLabelByItemtype($this->fields['itemtype']);
if ($label) {
echo $label;
echo "<input type='hidden' name='itemtype' value='".$this->fields['itemtype']."'";
}
} else {
//Add criteria : display dropdown
$options = self::getCredentialsItemTypes();
$options[''] = Dropdown::EMPTY_VALUE;
asort($options);
Dropdown::showFromArray('itemtype', $options);
}
}
/**
* Define more tabs to display
*
* @param array $options
* @return array
*/
function defineMoreTabs($options = []) {
return [];
}
/**
* Display more tabs
*
* @param array $tab
*/
function displayMoreTabs($tab) {
}
/**
* Get search function for the class
*
* @return array
*/
function rawSearchOptions() {
$tab = [];
$tab[] = [
'id' => 'common',
'name' => __('Authentication for remote devices (VMware)', 'fusioninventory'),
];
$tab[] = [
'id' => '1',
'table' => $this->getTable(),
'field' => 'name',
'name' => __('Name'),
'datatype' => 'itemlink',
];
$tab[] = [
'id' => '2',
'table' => 'glpi_entities',
'field' => 'completename',
'name' => Entity::getTypeName(1),
'datatype' => 'dropdown',
];
$tab[] = [
'id' => '3',
'table' => $this->getTable(),
'field' => 'itemtype',
'name' => __('Type'),
'massiveaction' => false,
];
$tab[] = [
'id' => '4',
'table' => $this->getTable(),
'field' => 'username',
'name' => __('Login'),
];
return $tab;
}
/**
* Perform checks to be sure that an itemtype and at least a field are
* selected
*
* @param array $input the values to insert in DB
* @return array
*/
static function checkBeforeInsert($input) {
if ($input['password'] == '') {
unset($input['password']);
}
if (!$input['itemtype']) {
Session::addMessageAfterRedirect(
__('It\'s mandatory to select a type and at least one field'), true, ERROR);
$input = [];
}
return $input;
}
/**
* Prepare data before add to database
*
* @param array $input
* @return array
*/
function prepareInputForAdd($input) {
return self::checkBeforeInsert($input);
}
/**
* Prepare data before update in database
*
* @param array $input
* @return array
*/
function prepareInputForUpdate($input) {
return $input;
}
/**
* Get an itemtype label by the credential itemtype
*
* @param string $credential_itemtype for example PluginFusioninventoryInventoryComputerESX
* @return string|false
*/
static function getLabelByItemtype($credential_itemtype) {
$credentialtypes = self::findItemtypeType($credential_itemtype);
if (!empty($credentialtypes)) {
return $credentialtypes['name'];
}
return false;
}
/**
* Find a credential by his itemtype
*
* @param string $credential_itemtype for example PluginFusioninventoryInventoryComputerESX
* @return array
*/
static function findItemtypeType($credential_itemtype) {
$credential = ['itemtype' => 'PluginFusioninventoryInventoryComputerESX', //Credential itemtype
'name' => __('VMware host', 'fusioninventory'), //Label
'targets' => ['Computer']];
if ($credential['itemtype'] == $credential_itemtype) {
return $credential;
}
return [];
}
/**
* Get all credentials itemtypes
*
* @return array
*/
static function getCredentialsItemTypes() {
return ['PluginFusioninventoryInventoryComputerESX' =>
__('VMware host', 'fusioninventory')];
}
/**
* Get credential types
*
* @param string $itemtype
* @return array
*/
static function getForItemtype($itemtype) {
$itemtypes = [];
foreach (PluginFusioninventoryModule::getAll() as $data) {
$class= PluginFusioninventoryStaticmisc::getStaticMiscClass($data['directory']);
if (is_callable([$class, 'credential_types'])) {
foreach (call_user_func([$class, 'credential_types']) as $credential) {
if (in_array($itemtype, $credential['targets'])) {
$itemtypes[$credential['itemtype']] = $credential['name'];
}
}
}
}
return $itemtypes;
}
/**
* Display dropdown with credentials
*
* @global array $CFG_GLPI
* @param array $params
*/
static function dropdownCredentials($params = []) {
global $CFG_GLPI;
$p = [];
if ($params['id'] == -1) {
$p['value'] = '';
$p['itemtype'] = '';
$p['id'] = 0;
} else {
$credential = new PluginFusioninventoryCredential();
$credential->getFromDB($params['id']);
if ($credential->getFromDB($params['id'])) {
$p = $credential->fields;
} else {
$p['value'] = '';
$p['itemtype'] = '';
$p['id'] = 0;
}
}
$types = self::getCredentialsItemTypes();
$types[''] = Dropdown::EMPTY_VALUE;
$rand = Dropdown::showFromArray('plugin_fusioninventory_credentials_id', $types,
['value' => $p['itemtype']]);
$ajparams = ['itemtype' => '__VALUE__',
'id' => $p['id']];
$url = Plugin::getWebDir('fusioninventory')."/ajax/dropdownCredentials.php";
Ajax::updateItemOnSelectEvent("dropdown_plugin_fusioninventory_credentials_id$rand",
"span_credentials", $url, $ajparams);
echo "&nbsp;<span name='span_credentials' id='span_credentials'>";
if ($p['id']) {
self::dropdownCredentialsForItemtype($p);
}
echo "</span>";
}
/**
* Display dropdown of credentials for itemtype
*
* @param array $params
*/
static function dropdownCredentialsForItemtype($params = []) {
if (empty($params['itemtype'])) {
return;
}
// params
// Array([itemtype] => PluginFusioninventoryInventoryComputerESX [id] => 0)
if ($params['itemtype'] == 'PluginFusioninventoryInventoryComputerESX') {
$params['itemtype'] = 'PluginFusioninventoryCredential';
}
$value = 0;
if (isset($params['id'])) {
$value = $params['id'];
}
Dropdown::show($params['itemtype'], ['entity_sons' => true,
'value' => $value]);
}
/**
* Check if there's at least one credential itemetype
*
* @return boolean
*/
static function hasAlLeastOneType() {
$types = self::getCredentialsItemTypes();
return (!empty($types));
}
/**
* Display a specific header
*/
function displayHeader() {
//Common dropdown header
parent::displayHeader();
//Fusioninventory menu
PluginFusioninventoryMenu::displayMenu("mini");
}
}

View File

@@ -0,0 +1,197 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the IP of VMWARE ESX and link to
* credentials to be able to inventory these specific systems througth the
* webservice.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the IP of VMWARE ESX and link to credentials to be able to inventory
* these specific systems througth the webservice.
*/
class PluginFusioninventoryCredentialIp extends CommonDropdown {
/**
* Define first level menu name
*
* @var string
*/
public $first_level_menu = "admin";
/**
* Define second level menu name
*
* @var string
*/
public $second_level_menu = "pluginfusioninventorymenu";
/**
* Define third level menu name
*
* @var string
*/
public $third_level_menu = "credentialip";
/**
* The right name for this class
*
* @var string
*/
static $rightname = 'plugin_fusioninventory_credentialip';
/**
* Get name of this type by language of the user connected
*
* @param integer $nb number of elements
* @return string name of this type
*/
static function getTypeName($nb = 0) {
return __('Remote device inventory', 'fusioninventory');
}
/**
* Add more fields
*
* @return array
*/
function getAdditionalFields() {
return [['name' => 'itemtype',
'label' => __('Type'),
'type' => 'credentials'],
['name' => 'ip',
'label' => __('IP'),
'type' => 'text']];
}
/**
* Display specific fields
*
* @param integer $ID
* @param array $field
*/
function displaySpecificTypeField($ID, $field = []) {
switch ($field['type']) {
case 'credentials' :
if ($ID > 0) {
$field['id'] = $this->fields['plugin_fusioninventory_credentials_id'];
} else {
$field['id'] = -1;
}
PluginFusioninventoryCredential::dropdownCredentials($field);
break;
}
}
/**
* Get search function for the class
*
* @return array
*/
function rawSearchOptions() {
$tab = [];
$tab[] = [
'id' => 'common',
'name' => __('Authentication for remote devices (VMware)', 'fusioninventory'),
];
$tab[] = [
'id' => '1',
'table' => $this->getTable(),
'field' => 'name',
'name' => __('Name'),
'datatype' => 'itemlink',
];
$tab[] = [
'id' => '2',
'table' => 'glpi_entities',
'field' => 'completename',
'name' => Entity::getTypeName(1),
'datatype' => 'dropdown',
];
$tab[] = [
'id' => '3',
'table' => $this->getTable(),
'field' => 'name',
'name' => __('Authentication for remote devices (VMware)', 'fusioninventory'),
'datatype' => 'itemlink',
'itemlink_type' => 'PluginFusioninventoryCredential',
];
$tab[] = [
'id' => '4',
'table' => $this->getTable(),
'field' => 'ip',
'name' => __('IP'),
'datatype' => 'string',
];
return $tab;
}
/**
* Display a specific header
*/
function displayHeader() {
//Common dropdown header
parent::displayHeader();
//Fusioninventory menu
PluginFusioninventoryMenu::displayMenu("mini");
}
}

View File

@@ -0,0 +1,165 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage lock during inventory.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author Walid Nouh
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage db locks during inventory.
*/
class PluginFusioninventoryDBLock {
//Number of milliseconds to wait each time we check if the lock is set
const MILLISECOND_LOCK_WAIT = 100000;
//Number of second to wait before forcing release of the lock
const SECONDS_TO_RELEASE_LOCK = 600;
//Number of second that is supposed to be the maximum to send to an agent
//an error message explaining that a lock is still in place
const SECONDS_BEFORE_SENDING_ERROR = 5;
/**
* Put a lock to prevent import of software/software version
* @since 9.2+2.0
*
* @param string $type type of lock ('software' or 'softwareversion')
* @param string callback_method the name of the method to call when checking the lock
* @return boolean the result of the lock
*/
function setLock($type, $value = '1', $callback_method = false) {
global $DB, $CFG_GLPI;
$result = true;
$table = "glpi_plugin_fusioninventory_dblock".$type;
if ($DB->tableExists($table)) {
$start_time = date('U');
//Set a lock for softwares to prevent new software import
$CFG_GLPI["use_log_in_files"] = false;
$query = $DB->buildInsert(
$table, [
'value' => $value
]
);
while (!$DB->query($query)) {
usleep(self::MILLISECOND_LOCK_WAIT);
if ($callback_method) {
$result = $this->checkLockForAgents($start_time);
if (!$result) {
break;
}
}
}
$CFG_GLPI["use_log_in_files"] = true;
}
return $result;
}
/**
* Check if a lock error message should be sent an agent
* @since 9.2+2.0
*
* @param string $start_time the time where we start trying to set the lock
* @return boolean true if no error message should
*/
function checkLockForAgents($start_time) {
if ((date('U') - $start_time) > self::SECONDS_BEFORE_SENDING_ERROR) {
$communication = new PluginFusioninventoryCommunication();
$communication->setMessage("<?xml version='1.0' encoding='UTF-8'?>
<REPLY>
<ERROR>ERROR: Timeout for DB lock based on name</ERROR>
</REPLY>");
$communication->sendMessage($_SESSION['plugin_fusioninventory_compressmode']);
return false;
}
return true;
}
/**
* Put a lock to prevent import of software/software version
* @since 9.2+2.0
*
* @param string $type type of lock ('software' or 'softwareversion')
* @param string $where the SQL where clause to use to release lock (default '')
*/
function releaseLock($type, $where = []) {
global $DB;
if (empty($where)) {
$where = ['value' => '1'];
}
$table = "glpi_plugin_fusioninventory_dblock".$type;
if ($DB->tableExists($table)) {
//Release the lock
$DB->delete(
$table,
$where
);
}
}
/**
* Clean all locks lasting more than 10 minutes
* @since 9.2+2.0
*
*/
function releaseAllLocks() {
$where = ['date' => ['<', new \QueryExpression("CURRENT_TIMESTAMP() - ".self::SECONDS_TO_RELEASE_LOCK)]];
$tables = [
'inventorynames',
'inventories',
'softwares',
'softwareversions'
];
foreach ($tables as $table) {
$this->releaseLock($table, $where);
}
}
}

View File

@@ -0,0 +1,539 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the actions in package for deploy system.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author Alexandre Delaunay
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the actions in package for deploy system.
*/
class PluginFusioninventoryDeployAction extends PluginFusioninventoryDeployPackageItem {
public $shortname = 'actions';
public $json_name = 'actions';
/**
* Get list of return actions available
*
* @return array
*/
function getReturnActionNames() {
return [
0 => Dropdown::EMPTY_VALUE,
'okCode' => __("Return code is equal to", 'fusioninventory'),
'errorCode' => __("Return code is not equal to", 'fusioninventory'),
'okPattern' => __("Command output contains", 'fusioninventory'),
'errorPattern' => __("Command output does not contains", 'fusioninventory')
];
}
/**
* Get types of actions with name => description
*
* @return array
*/
function getTypes() {
return [
'cmd' => __('Command', 'fusioninventory'),
'move' => __('Move', 'fusioninventory'),
'copy' => __('Copy', 'fusioninventory'),
'delete' => __('Delete directory', 'fusioninventory'),
'mkdir' => __('Create directory', 'fusioninventory')
];
}
/**
* Get description of the type name
*
* @param string $type name of the type
* @return string mapped with the type
*/
function getLabelForAType($type) {
$a_types = $this->getTypes();
if (isset($a_types[$type])) {
return $a_types[$type];
}
return $type;
}
/**
* Display form
*
* @param object $package PluginFusioninventoryDeployPackage instance
* @param array $request_data
* @param string $rand unique element id used to identify/update an element
* @param string $mode possible values: init|edit|create
*/
function displayForm(PluginFusioninventoryDeployPackage $package, $request_data, $rand, $mode) {
/*
* Get element config in 'edit' mode
*/
$config = null;
if ($mode === self::EDIT && isset($request_data['index'])) {
/*
* Add an hidden input about element's index to be updated
*/
echo "<input type='hidden' name='index' value='".$request_data['index']."' />";
$element = $package->getSubElement($this->shortname, $request_data['index']);
if (is_array($element) && count($element) == 1) {
reset($element);
$type = key($element);
$config = ['type' => $type, 'data' => $element[$type]];
}
}
/*
* Display start of div form
*/
if (in_array($mode, [self::INIT], true)) {
echo "<div id='actions_block$rand' style='display:none'>";
}
/*
* Display element's dropdownType in 'create' or 'edit' mode
*/
if (in_array($mode, [self::CREATE, self::EDIT], true)) {
$this->displayDropdownType($package, $config, $rand, $mode);
}
/*
* Display element's values in 'edit' mode only.
* In 'create' mode, those values are refreshed with dropdownType 'change'
* javascript event.
*/
if (in_array($mode, [self::CREATE, self::EDIT], true)) {
echo "<span id='show_actions_value{$rand}'>";
if ($mode === self::EDIT) {
$this->displayAjaxValues($config, $request_data, $rand, $mode);
}
echo "</span>";
}
/*
* Close form div
*/
if (in_array($mode, [self::INIT], true)) {
echo "</div>";
}
}
/**
* Display list of actions
*
* @global array $CFG_GLPI
* @param object $package PluginFusioninventoryDeployPackage instance
* @param array $data array converted of 'json' field in DB where stored actions
* @param string $rand unique element id used to identify/update an element
*/
function displayList(PluginFusioninventoryDeployPackage $package, $data, $rand) {
global $CFG_GLPI;
$canedit = $package->canUpdateContent();
$package_id = $package->getID();
echo "<table class='tab_cadrehov package_item_list' id='table_action_$rand'>";
$i=0;
foreach ($data['jobs'][$this->json_name] as $action) {
echo Search::showNewLine(Search::HTML_OUTPUT, ($i%2));
if ($canedit) {
echo "<td class='control'>";
Html::showCheckbox(['name' => 'actions_entries['.$i.']']);
echo "</td>";
}
$keys = array_keys($action);
$action_type = array_shift($keys);
echo "<td>";
if ($canedit) {
echo "<a class='edit'
onclick=\"edit_subtype('action', $package_id, $rand ,this)\">";
}
echo $this->getLabelForAType($action_type);
if ($canedit) {
echo "</a>";
}
echo "<br />";
foreach ($action[$action_type] as $key => $value) {
if (is_array($value)) {
if ($key === "list") {
foreach ($value as $list) {
echo $list;
echo " ";
}
}
} else {
echo "<b>";
if ($key == 'exec') {
echo __('Command to execute', 'fusioninventory');
} else {
echo $key;
}
echo "</b>";
if ($key ==="exec") {
echo "<pre style='border-left:solid lightgrey 3px;margin-left: 5px;".
"padding-left:2px;white-space: pre-wrap;'>$value</pre>";
} else {
echo " $value ";
}
}
}
if (isset($action[$action_type]['retChecks'])) {
echo "<br><b>".__("return codes saved for this command", 'fusioninventory').
"</b> : <ul class='retChecks'>";
foreach ($action[$action_type]['retChecks'] as $retCheck) {
echo "<li>";
$getReturnActionNames = $this->getReturnActionNames();
echo $getReturnActionNames[$retCheck['type']]." ".array_shift($retCheck['values']);
echo "</li>";
}
echo "</ul>";
}
echo "</td>";
echo "</td>";
if ($canedit) {
echo "<td class='rowhandler control' title='".__('drag', 'fusioninventory').
"'><div class='drag row'></div></td>";
}
echo "</tr>";
$i++;
}
if ($canedit) {
echo "<tr><th>";
echo Html::getCheckAllAsCheckbox("actionsList$rand", mt_rand());
echo "</th><th colspan='3' class='mark'></th></tr>";
}
echo "</table>";
if ($canedit) {
echo "&nbsp;&nbsp;<img src='".$CFG_GLPI["root_doc"]."/pics/arrow-left.png' alt=''>";
echo "<input type='submit' name='delete' value=\"".
__('Delete', 'fusioninventory')."\" class='submit'>";
}
}
/**
* Display different fields relative the action selected (cmd, move...)
*
* @param array $config
* @param array $request_data
* @param string $mode mode in use (create, edit...)
* @return boolean
*/
function displayAjaxValues($config, $request_data, $rand, $mode) {
global $CFG_GLPI;
$mandatory_mark = $this->getMandatoryMark();
$pfDeployPackage = new PluginFusioninventoryDeployPackage();
if (isset($request_data['packages_id'])) {
$pfDeployPackage->getFromDB($request_data['packages_id']);
} else {
$pfDeployPackage->getEmpty();
}
/*
* Get type from request params
*/
$type = null;
if ($mode === self::CREATE) {
$type = $request_data['value'];
} else {
$type = $config['type'];
$config_data = $config['data'];
}
/*
* Set default values
*/
$value_type_1 = "input";
$value_1 = "";
$value_2 = "";
$retChecks = null;
$name_label = __('Action label', 'fusioninventory');
$name_value = (isset($config_data['name']))?$config_data['name']:"";
$name_type = "input";
$logLineLimit = (isset($config_data['logLineLimit']))?$config_data['logLineLimit']:100;
/*
* set values from element's config in 'edit' mode
*/
switch ($type) {
case 'move':
case 'copy':
$value_label_1 = __("From", 'fusioninventory');
$name_label_1 = "from";
$value_label_2 = __("To", 'fusioninventory');
$name_label_2 = "to";
if ($mode === self::EDIT) {
$value_1 = $config_data['from'];
$value_2 = $config_data['to'];
}
break;
case 'cmd':
$value_label_1 = __("exec", 'fusioninventory');
$name_label_1 = "exec";
$value_label_2 = false;
$value_type_1 = "textarea";
if ($mode === self::EDIT) {
$value_1 = $config_data['exec'];
if (isset($config_data['retChecks'])) {
$retChecks = $config_data['retChecks'];
}
}
break;
case 'delete':
case 'mkdir':
$value_label_1 = __("path", 'fusioninventory');
$name_label_1 = "list[]";
$value_label_2 = false;
if ($mode === self::EDIT) {
/*
* TODO : Add list input like `retChecks` on `mkdir` and `delete`
* because those methods are defined as list in specification
*/
$value_1 = array_shift($config_data['list']);
}
break;
default:
return false;
}
echo "<table class='package_item'>";
echo "<tr>";
echo "<th>".__('Action label', 'fusioninventory')."</th>";
echo "<td><input type='text' name='name' id='check_name' value=\"{$name_value}\" /></td>";
echo "</tr>";
echo "<tr>";
echo "<th>$value_label_1&nbsp;".$mandatory_mark."</th>";
echo "<td>";
switch ($value_type_1) {
case "input":
echo "<input type='text' name='$name_label_1' value='$value_1' />";
break;
case "textarea":
echo "<textarea name='$name_label_1' rows='3' style='width: 760px;'>$value_1</textarea>";
break;
}
echo "</td>";
echo "</tr>";
if ($value_label_2 !== false) {
echo "<tr>";
echo "<th>".$value_label_2."&nbsp;".$mandatory_mark."</th>";
echo "<td><input type='text' name='$name_label_2' value='$value_2'/></td>";
echo "</tr>";
}
//specific case for cmd : add retcheck form
if ($type == "cmd") {
echo "<tr>";
echo "<th>".__("Execution checks", 'fusioninventory');
PluginFusioninventoryDeployPackage::plusButton("retchecks", ".table_retchecks.template");
echo "</th>";
echo "<td>";
echo "<span id='retchecks' style='display:block'>";
if (is_array($retChecks)
&& count($retChecks)) {
foreach ($retChecks as $retcheck) {
echo "<table class='table_retchecks'>";
echo "<tr>";
echo "<td>";
Dropdown::showFromArray('retchecks_type[]', self::getReturnActionNames(),
[ 'value' => $retcheck['type'],
'width' => '200px'
]
);
echo "</td>";
echo "<td>";
echo "<input type='text' name='retchecks_value[]' value='".
$retcheck['values'][0]."' />";
echo "</td>";
echo "<td><a class='edit' onclick='removeLine(this)'><img src='".
$CFG_GLPI["root_doc"]."/pics/delete.png' /></a></td>";
echo "</tr>";
echo "</table>";
}
}
echo "<table class='table_retchecks template' style='display:none'>";
echo "<tr>";
echo "<td>";
Dropdown::showFromArray('retchecks_type[]', $this->getReturnActionNames(),
['width' => '200px']);
echo "</td>";
echo "<td><input type='text' name='retchecks_value[]' /></td>";
echo "<td><a class='edit' onclick='removeLine(this)'><img src='".
$CFG_GLPI["root_doc"]."/pics/delete.png' /></a></td>";
echo "</tr>";
echo "</span>";
echo "</td>";
echo "</tr>";
echo "</table>";
}
if ($type == 'cmd') {
echo "<tr>";
echo "<th>".__('Number of output lines to retrieve', 'fusioninventory')."</th>";
echo "<td>";
$options = ['min' => 0,
'max' => 5000,
'step' => 10,
'toadd' => [0 => __('None'), -1 => __('All')],
'value' => (isset($config_data['logLineLimit']))?$config_data['logLineLimit']:10
];
Dropdown::showNumber('logLineLimit', $options);
echo "&nbsp;<span class='red'><i>";
echo __('Fusioninventory-Agent 2.3.20 or higher mandatory');
echo "</i></span></td>";
echo "</tr>";
}
$this->addOrSaveButton($pfDeployPackage, $mode);
echo "<script type='text/javascript'>
function removeLine(item) {
var tag_table = item.parentNode.parentNode.parentNode.parentNode;
var parent = tag_table.parentNode;
parent.removeChild(tag_table);
}
</script>";
}
/**
* Add a new item in actions of the package
*
* @param array $params list of fields with value of the action
*/
function add_item($params) {
//prepare new action entry to insert in json
$fields = ['list', 'from', 'to', 'exec', 'name', 'logLineLimit'];
foreach ($fields as $field) {
if (isset($params[$field])) {
$tmp[$field] = $params[$field];
}
}
//process ret checks
if (isset($params['retchecks_type'])
&& !empty($params['retchecks_type'])) {
foreach ($params['retchecks_type'] as $index => $type) {
if ($type !== '0') {
$tmp['retChecks'][] = [
'type' => $type,
'values' => [$params['retchecks_value'][$index]]
];
}
}
}
//append prepared data to new entry
$new_entry[$params['actionstype']] = $tmp;
//get current order json
$data = json_decode($this->getJson($params['id']), true);
//add new entry
$data['jobs'][$this->json_name][] = $new_entry;
//update order
$this->updateOrderJson($params['id'], $data);
}
/**
* Save the item in actions
*
* @param array $params list of fields with value of the action
*/
function save_item($params) {
$tmp = [];
$fields = ['list', 'from', 'to', 'exec', 'name', 'logLineLimit'];
foreach ($fields as $field) {
if (isset($params[$field])) {
$tmp[$field] = $params[$field];
}
}
//process ret checks
if (isset($params['retchecks_type']) && !empty($params['retchecks_type'])) {
foreach ($params['retchecks_type'] as $index => $type) {
//if type == '0', this means nothing is selected
if ($type !== '0') {
$tmp['retChecks'][] = [
'type' => $type,
'values' => [$params['retchecks_value'][$index]]
];
}
}
}
//append prepared data to new entry
$entry[$params['actionstype']] = $tmp;
//update order
$this->updateOrderJson($params['id'],
$this->prepareDataToSave($params, $entry));
}
}

View File

@@ -0,0 +1,685 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the checks before deploy a package.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author Walid Nouh
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the checks before deploy a package.
*/
class PluginFusioninventoryDeployCheck extends PluginFusioninventoryDeployPackageItem {
public $shortname = 'checks';
public $json_name = 'checks';
/**
* Get types of checks with name => description
*
* @return array
*/
function getTypes() {
return [
__('Registry', 'fusioninventory') => [
'winkeyExists' => __("Registry key exists", 'fusioninventory'),
'winvalueExists' => __("Registry value exists", 'fusioninventory'),
'winkeyMissing' => __("Registry key missing", 'fusioninventory'),
'winvalueMissing' => __("Registry value missing", 'fusioninventory'),
'winkeyEquals' => __("Registry value equals to", 'fusioninventory'),
'winkeyNotEquals' => __("Registry value not equals to", 'fusioninventory'),
'winvalueType' => __("Type of registry value equals to", 'fusioninventory')
],
__('File') => [
'fileExists' => __("File exists", 'fusioninventory'),
'fileMissing' => __("File is missing", 'fusioninventory'),
'fileSizeGreater' => __("File size is greater than", 'fusioninventory'),
'fileSizeEquals' => __("File size is equal to", 'fusioninventory'),
'fileSizeLower' => __("File size is lower than", 'fusioninventory'),
'fileSHA512' => __("SHA-512 hash value matches", 'fusioninventory'),
'fileSHA512mismatch' => __("SHA-512 hash value mismatch", 'fusioninventory'),
],
__('Directory') => [
'directoryExists' => __("Directory exists", 'fusioninventory'),
'directoryMissing' => __("Directory is missing", 'fusioninventory'),
],
__('Other') => [
'freespaceGreater' => __("Free space is greater than", 'fusioninventory')
]
];
}
/**
* Get label for a type
* @param the type value
* @return the type label
*/
function getLabelForAType($type) {
$alltypes = [];
foreach ($this->getTypes() as $label => $types) {
$alltypes+= $types;
}
if (isset($alltypes[$type])) {
return $alltypes[$type];
} else {
return '';
}
}
/**
* Get Unit name
*
* @return array
*/
function getUnitLabel() {
return [
"B" => __('o'),
"KB" => __('Kio'),
"MB" => __('Mio'),
"GB" => __('Gio')
];
}
function getAuditDescription($type, $return) {
$return_string = $this->getLabelForAType($type);
//The skip case is a litte bit different. So we notice to the user
//that if audit is successful, the the audit check process continue
if ($return == 'skip') {
$return_string.=' : '.__('continue', 'fusioninventory');
} else {
$return_string.=' : '.__('passed', 'fusioninventory');
}
$return_string.= ', '.__('otherwise', 'fusioninventory').' : ';
$return_string.= $this->getValueForReturn($return);
return $return_string;
}
/**
* Get the number to multiply to have in B relative to the unit
*
* @param string $unit the unit of number
* @return integer the number to multiply
*/
function getUnitSize($unit) {
$units = [ "B" => 1,
"KB" => 1024,
"MB" => 1024 * 1024,
"GB" => 1024 * 1024 * 1024
];
if (array_key_exists($unit, $units)) {
return $units[$unit];
} else {
return 1;
}
}
/**
* Get all registry value types handled by the agent
*
* @since 9.2
* @return an array of registry values types
*/
function getRegistryTypes() {
return [
'REG_SZ' => 'REG_SZ',
'REG_DWORD' => 'REG_DWORD',
'REG_BINARY' => 'REG_BINARY',
'REG_EXPAND_SZ' => 'REG_EXPAND_SZ',
'REG_MULTI_SZ' => 'REG_MULTI_SZ',
'REG_LINK' => 'REG_LINK',
'REG_DWORD_BIG_ENDIAN' => 'REG_DWORD_BIG_ENDIAN',
'REG_NONE' => 'REG_NONE'
];
}
function dropdownRegistryTypes($value = 'REG_SZ') {
return Dropdown::showFromArray('value', $this->getRegistryTypes(),
['value' => $value]);
}
/**
* Display list of checks
*
* @global array $CFG_GLPI
* @param object $package PluginFusioninventoryDeployPackage instance
* @param array $data array converted of 'json' field in DB where stored checks
* @param string $rand unique element id used to identify/update an element
*/
function displayList(PluginFusioninventoryDeployPackage $package, $data, $rand) {
global $CFG_GLPI;
$checks_types = $this->getTypes();
$package_id = $package->getID();
$canedit = $package->canUpdateContent();
echo "<table class='tab_cadrehov package_item_list' id='table_checks_$rand'>";
$i = 0;
foreach ($data['jobs']['checks'] as $check) {
switch ($check['type']) {
case 'freespaceGreater':
$check['value'] = $check['value'] * 1024 * 1024;
case 'fileSizeLower':
case 'fileSizeGreater':
case 'fileSizeEquals':
$check['value'] = $this->processFilesize($check['value']);
break;
}
echo Search::showNewLine(Search::HTML_OUTPUT, ($i%2));
if ($canedit) {
echo "<td class='control'>";
Html::showCheckbox(['name' => 'checks_entries['.$i.']']);
echo "</td>";
}
//Get the audit full description (with type and return value)
//to be displayed in the UI
$text = $this->getAuditDescription($check['type'], $check['return']);
if (isset($check['name']) && !empty($check['name'])) {
$check_label = $check['name'].' ('.$text.')';
} else {
$check_label = $text;
}
echo "<td>";
if ($canedit) {
echo "<a class='edit'
onclick=\"edit_subtype('check', $package_id, $rand ,this)\">";
}
echo $check_label;
if ($canedit) {
echo "</a>";
}
if ($check['return'] === 'startnow') {
echo "<br />";
$warning = sprintf(__('Fusioninventory-Agent %1s or higher mandatory'), '2.4.2');
echo "<img src='".$CFG_GLPI['root_doc']."/pics/warning_min.png'>";
echo "<span class='red'><i>".$warning."</i></span>";
}
echo "<br />";
$type_values = $this->getLabelsAndTypes($check['type'], false);
if (isset($type_values['path_label'])) {
echo $type_values['path_label'].': '.$check['path'];
}
if (!empty($check['value']) && $check['value'] != NOT_AVAILABLE) {
echo "&nbsp;&nbsp;&nbsp;<b>";
switch ($check['type']) {
case 'freespaceGreater':
case 'fileSizeGreater':
echo "&gt;";
break;
case 'fileSizeLower':
echo "&lt;";
break;
default:
echo "=";
break;
}
echo "</b>&nbsp;&nbsp;&nbsp;";
echo $check['value'];
}
echo "</td>";
if ($canedit) {
echo "<td class='rowhandler control' title='".__('drag', 'fusioninventory').
"'><div class='drag row'></div></td>";
}
echo "</tr>";
$i++;
}
if ($canedit) {
echo "<tr><th>";
echo Html::getCheckAllAsCheckbox("checksList$rand", mt_rand());
echo "</th><th colspan='3' class='mark'></th></tr>";
}
echo "</table>";
if ($canedit) {
echo "&nbsp;&nbsp;<img src='".$CFG_GLPI["root_doc"]."/pics/arrow-left.png' alt='' />";
echo "<input type='submit' name='delete' value=\"".
__('Delete', 'fusioninventory')."\" class='submit' />";
}
}
/**
* Get fields for the check type requested
*
* @param string $type the type of check
* @param array $data fields yet defined in edit mode
* @param string $mode mode in use (create, edit...)
*
* @return string|false
*/
function getValues($type, $data, $mode) {
$values = [
'warning_message' => false,
'name_value' => "",
'name_label' => __('Audit label', 'fusioninventory'),
'name_type' => "input",
'path_label' => "",
'path_value' => "",
'path_comment'=> "",
'value_type' => "input",
'value_label' => "",
'value' => "",
'return' => "error"
];
if ($mode === self::EDIT) {
$values['name_value'] = isset($data['name'])?$data['name']:"";
$values['path_value'] = isset($data['path'])?$data['path']:"";
$values['value'] = isset($data['value'])?$data['value']:"";
$values['return'] = isset($data['return'])?$data['return']:"error";
}
$type_values = $this->getLabelsAndTypes($type, true);
foreach ($type_values as $key => $value) {
$values[$key] = $value;
}
if ($type == 'freespaceGreater' && !is_numeric($values['value'])) {
$values['value'] = 0;
}
return $values;
}
/**
* Get labels and type for a check
* @param check_type the type of check
* @param mandatory indicates if mandatory mark must be added to the label
* @return the labels and type for a check
*/
function getLabelsAndTypes($check_type, $mandatory = false) {
$values = [];
$mandatory_mark = ($mandatory?$this->getMandatoryMark():'');
switch ($check_type) {
case "winkeyExists":
case "winkeyMissing":
$values['path_label'] = __("Path to the key", 'fusioninventory').$mandatory_mark;
$values['value_label'] = false;
$values['path_comment'] = __('Example of registry key').': HKEY_LOCAL_MACHINE\SOFTWARE\Fusioninventory-Agent\\';
$values['warning_message'] = sprintf(__('Fusioninventory-Agent %1s or higher recommended'), '2.3.20');
break;
case "winvalueExists":
case "winvalueMissing":
$values['path_label'] = __("Path to the value", 'fusioninventory').$mandatory_mark;
$values['value_label'] = false;
$values['path_comment'] = __('Example of registry value').': HKEY_LOCAL_MACHINE\SOFTWARE\Fusioninventory-Agent\server';
$values['warning_message'] = sprintf(__('Fusioninventory-Agent %1s or higher mandatory'), '2.3.20');
break;
case "winkeyEquals":
case "winkeyNotEquals":
$values['path_label'] = __("Path to the value", 'fusioninventory').$mandatory_mark;
$values['value_label'] = __('Value', 'fusioninventory');
$values['path_comment'] = __('Example of registry value').': HKEY_LOCAL_MACHINE\SOFTWARE\Fusioninventory-Agent\server';
if ($check_type == 'winkeyEquals') {
$values['warning_message'] = sprintf(__('Fusioninventory-Agent %1s or higher recommended'), '2.3.20');
} else {
$values['warning_message'] = sprintf(__('Fusioninventory-Agent %1s or higher mandatory'), '2.3.21');
}
break;
case "winvalueType":
$values['path_label'] = __("Path to the value", 'fusioninventory').$mandatory_mark;
$values['value_label'] = __('Type of value', 'fusioninventory').$mandatory_mark;
$values['value_type'] = 'registry_type';
$values['path_comment'] = __('Example of registry value').': HKEY_LOCAL_MACHINE\SOFTWARE\Fusioninventory-Agent\server';
$values['warning_message'] = sprintf(__('Fusioninventory-Agent %1s or higher mandatory'), '2.3.20'); break;
case "fileExists":
case "fileMissing":
$values['path_label'] = __("File", 'fusioninventory').$mandatory_mark;
$values['value_label'] = false;
break;
case "directoryExists":
case "directoryMissing":
$values['path_label'] = __("Directory", 'fusioninventory').$mandatory_mark;
$values['value_label'] = false;
break;
case "fileSizeGreater":
case "fileSizeEquals":
case "fileSizeLower":
$values['path_label'] = __("File", 'fusioninventory').$mandatory_mark;
$values['value_label'] = __('Value', 'fusioninventory').$mandatory_mark;
$values['value_type'] = "input+unit";
break;
case "fileSHA512":
case "fileSHA512mismatch":
$values['path_label'] = __("File", 'fusioninventory').$mandatory_mark;
$values['value_label'] = __('Value', 'fusioninventory').$mandatory_mark;
$values['value_type'] = "textarea";
break;
case "freespaceGreater":
$values['path_label'] = __("Disk or directory", 'fusioninventory').$mandatory_mark;
$values['value_label'] = __('Value', 'fusioninventory').$mandatory_mark;
$values['value_type'] = "input+unit";
break;
default:
break;
}
return $values;
}
/**
* Display different fields relative the check selected
*
* @param array $config
* @param array $request_data
* @param string $rand unique element id used to identify/update an element
* @param string $mode mode in use (create, edit...)
* @return boolean
*/
function displayAjaxValues($config, $request_data, $rand, $mode) {
global $CFG_GLPI;
$pfDeployPackage = new PluginFusioninventoryDeployPackage();
if (isset($request_data['packages_id'])) {
$pfDeployPackage->getFromDB($request_data['orders_id']);
} else {
$pfDeployPackage->getEmpty();
}
/*
* Get type from request params
*/
$type = null;
if ($mode === self::CREATE) {
$type = $request_data['value'];
$config_data = null;
} else {
$type = $config['type'];
$config_data = $config['data'];
}
$values = $this->getValues($type, $config_data, $mode);
if ($values === false) {
return false;
}
echo "<table class='package_item'>";
echo "<tr>";
echo "<th>".__('Audit label', 'fusioninventory')."</th>";
echo "<td><input type='text' name='name' id='check_name{$rand}' value=\"{$values['name_value']}\" /></td>";
echo "</tr>";
echo "<th>{$values['path_label']}</th>";
echo "<td><input type='text' name='path' id='check_path{$rand}' value=\"{$values['path_value']}\" />";
if ($values['path_comment']) {
echo "<br/><i>".$values['path_comment']."</i>";
}
echo "</td>";
echo "</tr>";
if ($values['value_label'] !== false) {
echo "<tr>";
echo "<th>{$values['value_label']}</th>";
switch ($values['value_type']) {
case "textarea":
echo "<td><textarea name='value' id='check_value{$rand}' rows='5'>".
$values['value']."</textarea></td>";
break;
case "input":
echo "<td><input type='text' name='value' id='check_value{$rand}' value='".
$values['value']."' /></td>";
break;
case 'registry_type':
echo "<td>";
$this->dropdownRegistryTypes($values['value']);
echo "</td>";
break;
case "input+unit":
$value = $values['value'];
// freespaceGreater check is saved as MiB
if ($type == 'freespaceGreater') {
$value = $value * 1024 * 1024;
}
$options['value'] = 'KB';
if ($mode === 'edit') {
if ($value >= $this->getUnitSize('GB')) {
$value = $value / ($this->getUnitSize('GB'));
$options['value'] = 'GB';
} else if ($value >= ($this->getUnitSize('MB'))) {
$value = $value/ ($this->getUnitSize('MB'));
$options['value'] = 'MB';
} else if ($value >= ($this->getUnitSize('KB'))) {
$value = $value/ ($this->getUnitSize('KB'));
$options['value'] = 'KB';
} else {
$options['value'] = 'B';
}
}
echo "<td>";
echo "<input type='text' name='value' id='check_value{$rand}' "
. "value='{$value}' />";
echo "</td>";
echo "</tr><tr>";
echo "<th>".__("Unit", 'fusioninventory')."</th>";
echo "<td>";
$unit_labels = $this->getUnitLabel();
/*
* The freespaceGreater check does not need to propose KiB or B
* because its value is based on MiB according to REST API.
* -- Kevin 'kiniou' Roy
*/
if ($type == 'freespaceGreater') {
unset($unit_labels['KB']);
unset($unit_labels['B']);
}
Dropdown::showFromArray('unit', $unit_labels, $options);
echo "</td>";
break;
}
echo "</tr>";
}
echo "<tr>";
echo "<th>".__("If not successful", 'fusioninventory')."</th>";
echo "<td>";
Dropdown::showFromArray('return', $this->getAllReturnValues(),
['value' => $values['return']]);
echo "</td>";
echo "</tr>";
if ($values['warning_message']) {
echo "<tr>";
echo "<td></td>";
echo "<td>";
echo "<img src='".$CFG_GLPI['root_doc']."/pics/warning_min.png'>";
echo "<span class='red'><i>".$values['warning_message']."</i></span></td>";
echo "</tr>";
}
$this->addOrSaveButton($pfDeployPackage, $mode);
echo "</table>";
}
/**
* Get all possible return values for a check
* @return an array of return values and their labels
*/
function getAllReturnValues() {
return ["error" => __('abort job', 'fusioninventory'),
"skip" => __("skip job", 'fusioninventory'),
"startnow" => __("start job now", 'fusioninventory'),
"info" => __("report info", 'fusioninventory'),
"warning" => __("report warning", 'fusioninventory')
];
}
/**
* Get the label for a return value
* @param the check return value
* @return the label for the return value
*/
function getValueForReturn($value) {
$values = $this->getAllReturnValues();
if (isset($values[$value])) {
return $values[$value];
} else {
return '';
}
}
/**
* Return an array corresponding to a check, ready to be serialized
* @param params the check's parameters
* @return array the array to be encoded in json and serialized
*/
static function formatCheckForJson($params) {
if (!isset($params['value'])) {
$params['value'] = "";
}
if (!isset($params['name'])) {
$params['name'] = "";
}
if (!empty($params['unit'])) {
$params['value'] = str_replace(",", ".", $params['value']);
if (!empty($params['value']) && is_numeric($params['value'])) {
//Make an exception for freespaceGreater check which is saved as MiB
if ($params['checkstype'] == "freespaceGreater") {
$params['value'] = $params['value'] / (1024 * 1024);
} else {
$params['value'] = $params['value'] * self::getUnitSize($params['unit']);
}
}
}
//prepare updated check entry to insert in json
$entry = [
'name' => $params['name'],
'type' => $params['checkstype'],
'path' => $params['path'],
'value' => strval($params['value']),
'return' => $params['return']
];
return $entry;
}
/**
* Add a new item in checks of the package
*
* @param array $params list of fields with value of the check
*/
function add_item($params) {
$entry = self::formatCheckForJson($params);
//get current order json
$datas = json_decode(
$this->getJson($params['id']),
true
);
//add new entry
$datas['jobs']['checks'][] = $entry;
//Add to package defintion
$this->addToPackage($params['id'], $entry, 'checks');
}
/**
* Save the item in checks
*
* @param array $params list of fields with value of the check
*/
function save_item($params) {
$entry = self::formatCheckForJson($params);
//get current order json
$datas = json_decode($this->getJson($params['id']), true);
//unset index
unset($datas['jobs']['checks'][$params['index']]);
//add new datas at index position
//(array_splice for insertion, ex : http://stackoverflow.com/a/3797526)
array_splice($datas['jobs']['checks'], $params['index'], 0, [$entry]);
//update order
$this->updateOrderJson($params['id'], $datas);
}
}

View File

@@ -0,0 +1,405 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the prepare task job and give the data to
* the agent when request what to deploy.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author Alexandre Delaunay
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the prepare task job and give the data to the agent when request what
* to deploy.
*/
class PluginFusioninventoryDeployCommon extends PluginFusioninventoryCommunication {
/**
* Check if definition_type is present in definitions_filter array.
* This function returns true if the definition_type is not in
* definitions_filter array.
* If definitions_filter is NULL, this check is inhibited and return false.
*
* @param string $definition_type
* @param null|array $definitions_filter
* @return boolean
*/
public function definitionFiltered($definition_type, $definitions_filter) {
if (!is_null($definitions_filter)
&& is_array($definitions_filter)
&& count($definitions_filter) > 0
&& !in_array($definition_type, $definitions_filter)) {
return true;
}
return false;
}
/**
* Prepare a takjob, get all devices and put in taskjobstate each task
* for each device for each agent
*
* @global object $DB
* @param integer $taskjob_id id of the taskjob
* @param null|array $definitions_filter
*/
function prepareRun($taskjob_id, $definitions_filter = null) {
global $DB;
$task = new PluginFusioninventoryTask();
$job = new PluginFusioninventoryTaskjob();
$joblog = new PluginFusioninventoryTaskjoblog();
$jobstate = new PluginFusioninventoryTaskjobstate();
$agent = new PluginFusioninventoryAgent();
$agentmodule= new PluginFusioninventoryAgentmodule();
$job->getFromDB($taskjob_id);
$task->getFromDB($job->fields['plugin_fusioninventory_tasks_id']);
$communication= $task->fields['communication'];
$actions = importArrayFromDB($job->fields['action']);
$definitions = importArrayFromDB($job->fields['definition']);
$taskvalid = 0;
$computers = [];
foreach ($actions as $action) {
$itemtype = key($action);
$items_id = current($action);
switch ($itemtype) {
case 'Computer':
if ($this->definitionFiltered("Computer", $definitions_filter)) {
break;
}
$computers[] = $items_id;
break;
case 'Group':
if ($this->definitionFiltered("Group", $definitions_filter)) {
break;
}
$computer_object = new Computer();
//find computers by user associated with this group
$group_users = new Group_User();
$group = new Group();
$group->getFromDB($items_id);
$computers_a_1 = [];
$computers_a_2 = [];
$members = $group_users->getGroupUsers($items_id);
foreach ($members as $member) {
$computers = $computer_object->find(
['users_id' => $member['id'],
'is_deleted' => 0,
'is_template' => 0]);
foreach ($computers as $computer) {
$computers_a_1[] = $computer['id'];
}
}
//find computers directly associated with this group
$computers = $computer_object->find(
['groups_id' => $items_id,
'is_deleted' => 0,
'is_template' => 0]);
foreach ($computers as $computer) {
$computers_a_2[] = $computer['id'];
}
//merge two previous array and deduplicate entries
$computers = array_unique(array_merge($computers_a_1, $computers_a_2));
break;
case 'PluginFusioninventoryDeployGroup':
$group = new PluginFusioninventoryDeployGroup;
$group->getFromDB($items_id);
switch ($group->getField('type')) {
case 'STATIC':
if ($this->definitionFiltered("PluginFusioninventoryDeployGroupStatic", $definitions_filter)) {
break;
}
$query = "SELECT items_id
FROM glpi_plugin_fusioninventory_deploygroups_staticdatas
WHERE groups_id = '$items_id'
AND itemtype = 'Computer'";
$res = $DB->query($query);
while ($row = $DB->fetchAssoc($res)) {
$computers[] = $row['items_id'];
}
break;
case 'DYNAMIC':
if ($this->definitionFiltered("PluginFusioninventoryDeployGroupDynamic", $definitions_filter)) {
break;
}
//$definitions_filter is NULL = update by crontask !
if ($definitions_filter != null) {
$where = " AND `can_update_group`='1'";
} else {
$where = "";
}
$query = "SELECT fields_array
FROM glpi_plugin_fusioninventory_deploygroups_dynamicdatas
WHERE groups_id = '$items_id' $where
LIMIT 1";
$res = $DB->query($query);
$row = $DB->fetchAssoc($res);
//No dynamic groups have been found : break
if ($DB->numrows($res) == 0) {
break;
}
if (isset($_GET)) {
$get_tmp = $_GET;
}
if (isset($_SESSION["glpisearchcount"]['Computer'])) {
unset($_SESSION["glpisearchcount"]['Computer']);
}
if (isset($_SESSION["glpisearchcount2"]['Computer'])) {
unset($_SESSION["glpisearchcount2"]['Computer']);
}
$_GET = importArrayFromDB($row['fields_array']);
$_GET["glpisearchcount"] = count($_GET['field']);
if (isset($_GET['field2'])) {
$_GET["glpisearchcount2"] = count($_GET['field2']);
}
$pfSearch = new PluginFusioninventorySearch();
Search::manageParams('Computer');
$glpilist_limit = $_SESSION['glpilist_limit'];
$_SESSION['glpilist_limit'] = 999999999;
$result = $pfSearch->constructSQL('Computer', $_GET);
$_SESSION['glpilist_limit'] = $glpilist_limit;
while ($data=$DB->fetchArray($result)) {
$computers[] = $data['id'];
}
if (count($get_tmp) > 0) {
$_GET = $get_tmp;
}
break;
}
break;
}
}
//Remove duplicatas from array
//We are using isset for faster processing than array_unique because we might have many
//entries in this list.
$tmp_computers = [];
foreach ($computers as $computer) {
if (!isset($tmp_computers[$computer])) {
$tmp_computers[$computer] = 1;
}
}
$computers = array_keys($tmp_computers);
$c_input= [];
$c_input['plugin_fusioninventory_taskjobs_id'] = $job->fields['id'];
$c_input['state'] = 0;
$c_input['plugin_fusioninventory_agents_id'] = 0;
$c_input['execution_id'] = $task->fields['execution_id'];
$package = new PluginFusioninventoryDeployPackage();
foreach ($computers as $computer_id) {
//Unique Id match taskjobstatuses for an agent(computer)
foreach ($definitions as $definition) {
$uniqid = uniqid();
$package->getFromDB($definition['PluginFusioninventoryDeployPackage']);
$c_input['state'] = 0;
$c_input['itemtype'] = 'PluginFusioninventoryDeployPackage';
$c_input['items_id'] = $package->fields['id'];
$c_input['date'] = date("Y-m-d H:i:s");
$c_input['uniqid'] = $uniqid;
//get agent for this computer
$agents_id = $agent->getAgentWithComputerid($computer_id);
if ($agents_id === false) {
$jobstates_id = $jobstate->add($c_input);
$jobstate->changeStatusFinish($jobstates_id,
0,
'',
1,
"No agent found for [[Computer::".$computer_id."]]");
} else {
if ($agentmodule->isAgentCanDo('DEPLOY', $agents_id)) {
$c_input['plugin_fusioninventory_agents_id'] = $agents_id;
$jobstates_running = $jobstate->find(
['itemtype' => 'PluginFusioninventoryDeployPackage',
'items_id' => $package->fields['id'],
'state' => ['!=', PluginFusioninventoryTaskjobstate::FINISHED],
'plugin_fusioninventory_agents_id' => $agents_id
]);
if (count($jobstates_running) == 0) {
// Push the agent, in the stack of agent to awake
if ($communication == "push") {
$_SESSION['glpi_plugin_fusioninventory']['agents'][$agents_id] = 1;
}
$jobstates_id= $jobstate->add($c_input);
//Add log of taskjob
$c_input['plugin_fusioninventory_taskjobstates_id'] = $jobstates_id;
$c_input['state']= PluginFusioninventoryTaskjoblog::TASK_PREPARED;
$taskvalid++;
$joblog->add($c_input);
unset($c_input['state']);
unset($c_input['plugin_fusioninventory_agents_id']);
}
}
}
}
}
if ($taskvalid > 0) {
$job->fields['status']= 1;
$job->update($job->fields);
} else {
$job->reinitializeTaskjobs($job->fields['plugin_fusioninventory_tasks_id']);
}
}
/**
* run function, so return data to send to the agent for deploy
*
* @param object $taskjobstate PluginFusioninventoryTaskjobstate instance
* @return array
*/
function run($taskjobstate) {
//Check if the job has been postponed
if (!is_null($taskjobstate->fields['date_start'])
&& $taskjobstate->fields['date_start'] > $_SESSION['glpi_currenttime']) {
//If the job is postponed and the execution date is in the future,
//skip the job for now
return false;
}
//get order by type and package id
$pfDeployPackage = new PluginFusioninventoryDeployPackage();
$pfDeployPackage->getFromDB($taskjobstate->fields['items_id']);
//decode order data
$order_data = json_decode($pfDeployPackage->fields['json'], true);
/* TODO:
* This has to be done properly in each corresponding classes.
* Meanwhile, I just split the data to rebuild a proper and compliant JSON
*/
$order_job = $order_data['jobs'];
//add uniqid to response data
$order_job['uuid'] = $taskjobstate->fields['uniqid'];
/* TODO:
* Orders should only contain job data and associatedFiles should be retrieved from the
* list inside Orders data like the following :
*
* $order_files = []
* foreach ($order_job["associatedFiles"] as $hash) {
* if (!isset($order_files[$hash]) {
* $order_files[$hash] = PluginFusioninventoryDeployFile::getByHash($hash);
* $order_files[$hash]['mirrors'] = $mirrors
* }
* }
*/
$order_files = $order_data['associatedFiles'];
//Add mirrors to associatedFiles
$mirrors = PluginFusioninventoryDeployMirror::getList(
$taskjobstate->fields['plugin_fusioninventory_agents_id']
);
foreach ($order_files as $hash => $params) {
$order_files[$hash]['mirrors'] = $mirrors;
$manifest = PLUGIN_FUSIONINVENTORY_MANIFESTS_DIR.$hash;
$order_files[$hash]['multiparts'] = [];
if (file_exists($manifest)) {
$handle = fopen($manifest, "r");
if ($handle) {
while (($buffer = fgets($handle)) !== false) {
$order_files[$hash]['multiparts'][] = trim($buffer);
}
fclose($handle);
}
}
}
//Send an empty json dict instead of empty json list
if (count($order_files) == 0) {
$order_files = (object)[];
}
// Fix some command like : echo "write in file" >> c:\TEMP\HELLO.txt
if (isset($order_job['actions'])) {
foreach ($order_job['actions'] as $key => $value) {
if (isset($value['cmd']) && isset($value['cmd']['exec'])) {
$order_job['actions'][$key]['cmd']['exec']= Toolbox::unclean_cross_side_scripting_deep($value['cmd']['exec']);
}
}
}
$order = [
"job" => $order_job,
"associatedFiles" => $order_files
];
return $order;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,105 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to get the deploy file in many parts.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author Anthony Hebert
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Used to get the deploy file in many parts.
*/
class PluginFusioninventoryDeployFilepart {
/**
* Send file to agent
*
* @param string $file
*/
static function httpSendFile($file) {
if (empty($file)) {
header("HTTP/1.1 500");
exit;
}
$matches = [];
preg_match('/.\/..\/([^\/]+)/', $file, $matches);
$sha512 = $matches[1];
// $short_sha512 = substr($sha512, 0, 6);
$repoPath = GLPI_PLUGIN_DOC_DIR."/fusioninventory/files/repository/";
$pfDeployFile = new PluginFusioninventoryDeployFile();
$filePath = $repoPath.$pfDeployFile->getDirBySha512($sha512).'/'.$sha512;
if (!is_file($filePath)) {
header("HTTP/1.1 404");
print "\n".$filePath."\n\n";
exit;
} else if (!is_readable($filePath)) {
header("HTTP/1.1 403");
exit;
}
error_reporting(0);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$sha512);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filePath));
if (ob_get_level() > 0) {
ob_clean();
}
flush();
readfile($filePath);
exit;
}
}

View File

@@ -0,0 +1,691 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the deploy groups.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author Alexandre Delaunay
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the deploy groups.
*/
class PluginFusioninventoryDeployGroup extends CommonDBTM {
/**
* Define constant name of static group
*
* @var string
*/
const STATIC_GROUP = 'STATIC';
/**
* Define constant name of dynamic group
*
* @var string
*/
const DYNAMIC_GROUP = 'DYNAMIC';
/**
* The right name for this class
*
* @var string
*/
static $rightname = "plugin_fusioninventory_group";
/**
* Define the array of itemtype allowed in static groups
*
* @var type
*/
protected $static_group_types = ['Computer'];
/**
* We activate the history.
*
* @var boolean
*/
public $dohistory = true;
/**
* __contruct function used to define the 2 types of groups
*/
public function __construct() {
$this->grouptypes = [
self::STATIC_GROUP => __('Static group', 'fusioninventory'),
self::DYNAMIC_GROUP => __('Dynamic group', 'fusioninventory')
];
}
/**
* Get name of this type by language of the user connected
*
* @param integer $nb number of elements
* @return string name of this type
*/
static function getTypeName($nb = 0) {
return __('FusionInventory group', 'fusioninventory');
}
/**
* Define tabs to display on form page
*
* @param array $options
* @return array containing the tabs name
*/
function defineTabs($options = []) {
$ong = [];
$this->addDefaultFormTab($ong);
$count = self::getMatchingItemsCount("PluginFusionInventoryTaskjob");
$ong[$this->getType().'$task'] = self::createTabEntry(_n('Associated task', 'Associated tasks', $count), $count);
$this->addStandardTab('Log', $ong, $options);
return $ong;
}
function getMatchingItemsCount($itemtype) {
$count = 0;
if ($itemtype == 'PluginFusionInventoryTaskjob'
&& is_numeric($_GET['id'])) {
$pfTaskjob = new PluginFusioninventoryTaskjob();
$data = $pfTaskjob->find(['actors' => ['LIKE', '%"PluginFusioninventoryDeployGroup":"'.$_GET['id'].'"%']]);
$count = count($data);
}
return $count;
}
/**
* Display the content of the tab
*
* @param object $item
* @param integer $tabnum number of the tab to display
* @param integer $withtemplate 1 if is a template form
* @return boolean
*/
static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) {
global $DB;
if ($tabnum == 'task') {
echo "<table width='950' class='tab_cadre_fixe'>";
echo "<tr>";
echo "<th>";
echo __('Task');
echo "</th>";
echo "<th>";
echo __('Active');
echo "</th>";
echo "<th>";
echo __('Module method');
echo "</th>";
echo "</tr>";
$modules_methods = PluginFusioninventoryStaticmisc::getModulesMethods();
$link = Toolbox::getItemTypeFormURL("PluginFusioninventoryTask");
$query = "SELECT
glpi_plugin_fusioninventory_tasks.id as id,
glpi_plugin_fusioninventory_tasks.name as tname,
glpi_plugin_fusioninventory_tasks.is_active,
glpi_plugin_fusioninventory_taskjobs.method
FROM glpi_plugin_fusioninventory_taskjobs
LEFT JOIN glpi_plugin_fusioninventory_tasks on plugin_fusioninventory_tasks_id=glpi_plugin_fusioninventory_tasks.id
WHERE `actors` LIKE '%\"PluginFusioninventoryDeployGroup\":\"".$_GET['id']."\"%'
ORDER BY glpi_plugin_fusioninventory_tasks.name";
$res = $DB->query($query);
while ($row = $DB->fetchAssoc($res)) {
echo "<tr class='tab_bg_1'>";
echo "<td>";
echo "<a href='".$link."?id=".$row['id']."'>".$row['tname']."</a>";
echo "</td>";
echo "<td>";
echo Dropdown::getYesNo($row['is_active']);
echo "</td>";
echo "<td>";
echo $modules_methods[$row['method']];
echo "</td>";
echo "</tr>";
}
echo "</table>";
return true;
}
return false;
}
/**
* Get the massive actions for this object
*
* @param object|null $checkitem
* @return array list of actions
*/
function getSpecificMassiveActions($checkitem = null) {
$actions = [];
$actions[__CLASS__.MassiveAction::CLASS_ACTION_SEPARATOR.'targettask'] = __('Target a task', 'fusioninventory');
$actions[__CLASS__.MassiveAction::CLASS_ACTION_SEPARATOR.'duplicate'] = _sx('button', 'Duplicate');
return $actions;
}
/**
* Display form related to the massive action selected
*
* @param object $ma MassiveAction instance
* @return boolean
*/
static function showMassiveActionsSubForm(MassiveAction $ma) {
switch ($ma->getAction()) {
case 'add_to_static_group':
Dropdown::show('PluginFusioninventoryDeployGroup',
['condition' => ['type' => PluginFusioninventoryDeployGroup::STATIC_GROUP]]);
echo Html::submit(_x('button', 'Post'), ['name' => 'massiveaction']);
return true;
case 'duplicate':
echo Html::submit(_x('button', 'Post'), ['name' => 'massiveaction']);
return true;
}
return parent::showMassiveActionsSubForm($ma);
}
/**
* Execution code for massive action
*
* @param object $ma MassiveAction instance
* @param object $item item on which execute the code
* @param array $ids list of ID on which execute the code
*/
static function processMassiveActionsForOneItemtype(MassiveAction $ma, CommonDBTM $item,
array $ids) {
switch ($ma->getAction()) {
case 'add_to_static_group' :
if ($item->getType() == 'Computer') {
$group_item = new PluginFusioninventoryDeployGroup_Staticdata();
foreach ($ids as $id) {
if (!countElementsInTable($group_item->getTable(),
[
'plugin_fusioninventory_deploygroups_id' => $_POST['plugin_fusioninventory_deploygroups_id'],
'itemtype' => 'Computer',
'items_id' => $id,
])) {
$values = [
'plugin_fusioninventory_deploygroups_id' => $_POST['plugin_fusioninventory_deploygroups_id'],
'itemtype' => 'Computer',
'items_id' => $id];
$group_item->add($values);
$ma->itemDone($item->getType(), $id, MassiveAction::ACTION_OK);
} else {
$ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);
}
}
}
break;
case 'duplicate':
$pfGroup = new self();
foreach ($ids as $key) {
if ($pfGroup->getFromDB($key)) {
if ($pfGroup->duplicate($pfGroup->getID())) {
//set action massive ok for this item
$ma->itemDone($item->getType(), $key, MassiveAction::ACTION_OK);
} else {
// KO
$ma->itemDone($item->getType(), $key, MassiveAction::ACTION_KO);
}
}
}
break;
default:
parent::processMassiveActionsForOneItemtype($ma, $item, $ids);
break;
}
}
function duplicate($deploygroups_id) {
$result = true;
if ($this->getFromDB($deploygroups_id)) {
$input = $this->fields;
unset($input['id']);
$input['name'] = sprintf(__('Copy of %s'), $this->fields['name']);
$new_deploygroups_id = $this->add($input);
if ($new_deploygroups_id) {
if ($this->fields['type'] == self::STATIC_GROUP) {
$result
= PluginFusioninventoryDeployGroup_Staticdata::duplicate($deploygroups_id, $new_deploygroups_id);
} else {
$result
= PluginFusioninventoryDeployGroup_Dynamicdata::duplicate($deploygroups_id, $new_deploygroups_id);
}
} else {
$result = false;
}
} else {
$result = false;
}
return $result;
}
/**
* Display title of the page
*
* @global array $CFG_GLPI
*/
function title() {
global $CFG_GLPI;
$buttons = [];
$title = self::getTypeName();
if ($this->canCreate()) {
$buttons["group.form.php?new=1"] = __('Add group', 'fusioninventory');
$title = "";
}
Html::displayTitle($CFG_GLPI['root_doc']."/plugins/fusinvdeploy/pics/menu_group.png",
$title, $title, $buttons);
}
/**
* Display form
*
* @param integer $ID
* @param array $options
* @return true
*/
function showForm($ID, $options = []) {
$this->initForm($ID, $options);
$this->showFormHeader($options);
echo "<tr class='tab_bg_1'>";
echo "<td>".__('Name')."&nbsp;:</td>";
echo "<td align='center'>";
Html::autocompletionTextField($this, 'name', ['size' => 40]);
echo "</td>";
echo "<td rowspan='2'>".__('Comments')."&nbsp;:</td>";
echo "<td rowspan='2' align='center'>";
echo "<textarea cols='40' rows='6' name='comment' >".$this->fields["comment"]."</textarea>";
echo "</td>";
echo "</tr>";
echo "<tr class='tab_bg_1'>";
echo "<td>".__('Type')."&nbsp;:</td>";
echo "<td align='center'>";
self::dropdownGroupType('type', $this->fields['type']);
echo "</td>";
echo "</tr>";
$this->showFormButtons($options);
return true;
}
/**
* Get search function for the class
*
* @return array
*/
function rawSearchOptions() {
$tab = [];
$tab[] = [
'id' => 'common',
'name' => self::getTypeName(),
];
$tab[] = [
'id' => '1',
'table' => $this->getTable(),
'field' => 'name',
'name' => __('Name'),
'datatype' => 'itemlink',
'massiveaction' => false,
'autocomplete' => true,
];
$tab[] = [
'id' => '2',
'table' => $this->getTable(),
'field' => 'type',
'name' => __('Type'),
'datatype' => 'specific',
'massiveaction' => false,
'searchtype' => 'equals',
];
return $tab;
}
/**
* Check if this group is a dynamic group or not
*
* @return boolean
*/
function isDynamicGroup() {
return ($this->fields['type'] == self::DYNAMIC_GROUP);
}
/**
* Check if this group is a static group or not
*
* @return boolean
*/
function isStaticGroup() {
return ($this->fields['type'] == self::STATIC_GROUP);
}
/**
* Get a specific value to display
*
* @param string $field
* @param array $values
* @param array $options
* @return string
*/
static function getSpecificValueToDisplay($field, $values, array $options = []) {
$group = new self();
if (!is_array($values)) {
$values = [$field => $values];
}
if ($field == 'type') {
return $group->grouptypes[$values[$field]];
}
return '';
}
/**
* Display dropdown to select dynamic of static group
*
* @param string $name
* @param string $value
* @return string
*/
static function dropdownGroupType($name = 'type', $value = 'STATIC') {
$group = new self();
if ($name == 'type') {
return Dropdown::showFromArray($name, $group->grouptypes,
['value'=>$value, 'display'=>true]);
} else {
return Dropdown::showFromArray($name, $group->grouptypes,
['value'=>$value, 'display'=>false]);
}
}
/**
* Get specific value to select
*
* @param string $field
* @param string $name
* @param string|array $values
* @param array $options
* @return string
*/
static function getSpecificValueToSelect($field, $name = '', $values = '', array $options = []) {
if (!is_array($values)) {
$values = [$field => $values];
}
$options['display'] = false;
if ($field == 'type') {
return self::dropdownGroupType($name, $values[$field]);
}
return parent::getSpecificValueToSelect($field, $name, $values, $options);
}
/**
* Get the URL to pass to the search engine
* @since 9.2
*
* @param integer $deploygroup_id the ID of the group
* @param boolean $is_dynamic is the group dynamic or static
* @return string the target
*/
static function getSearchEngineTargetURL($deploygroup_id, $is_dynamic = false) {
$target = PluginFusioninventoryDeployGroup::getFormURLWithID($deploygroup_id);
if ($is_dynamic) {
$target .= "&_glpi_tab=PluginFusioninventoryDeployGroup_Dynamicdata$1";
} else {
$target.= "&_glpi_tab=PluginFusioninventoryDeployGroup_Staticdata$1";
}
$target.= "&plugin_fusioninventory_deploygroups_id=".$deploygroup_id;
return $target;
}
/**
* Show criteria to search computers
*
* @param object $item PluginFusioninventoryDeployGroup instance
* @param array $p
*/
static function showCriteria(PluginFusioninventoryDeployGroup $item, $p) {
$is_dynamic = $item->isDynamicGroup();
$itemtype = "PluginFusioninventoryComputer";
$can_update = $item->canEdit($item->getID());
$p['target'] = self::getSearchEngineTargetURL($item->getID(), $is_dynamic);
if ($can_update) {
$p['addhidden'] = [
'plugin_fusioninventory_deploygroups_id' => $item->getID(),
'id' => $item->getID(),
'start' => 0
];
}
if ($is_dynamic) {
$p['actionname'] = 'save';
$p['actionvalue'] = _sx('button', 'Save');
} else {
$p['actionname'] = 'preview';
$p['actionvalue'] = __('Preview');
}
$p['showbookmark'] = false;
Search::showGenericSearch($itemtype, $p);
}
/**
* Get targets for the group
*
* @param integer $groups_id id of the group
* @param bool $use_cache retrieve agents from cache or not (only for dynamic groups)
* @return array list of computers
*/
static function getTargetsForGroup($groups_id, $use_cache = false) {
$group = new self();
$group->getFromDB($groups_id);
$results = [];
if ($group->isStaticGroup()) {
$staticgroup = new PluginFusioninventoryDeployGroup_Staticdata();
foreach ($staticgroup->find(
['plugin_fusioninventory_deploygroups_id' => $groups_id,
'itemtype' => 'Computer']) as $tmpgroup) {
$results[$tmpgroup['items_id']] = $tmpgroup['items_id'];
}
} else {
$results = PluginFusioninventoryDeployGroup_Dynamicdata::getTargetsByGroup($group,
$use_cache);
}
return $results;
}
/**
* Get search parameters as an array
*
* @global object $DB
* @param object $group PluginFusioninventoryDeployGroup instance
* @param boolean $check_post_values
* @param boolean $getAll
* @return array
*/
static function getSearchParamsAsAnArray(PluginFusioninventoryDeployGroup $group, $check_post_values = false, $getAll = false) {
global $DB;
$computers_params = [];
//Check criteria from DB
if (!$check_post_values) {
if ($group->fields['type'] == PluginFusioninventoryDeployGroup::DYNAMIC_GROUP) {
unset($_SESSION['glpisearch']['PluginFusioninventoryComputer']);
$query = "SELECT `fields_array`
FROM `glpi_plugin_fusioninventory_deploygroups_dynamicdatas`
WHERE `plugin_fusioninventory_deploygroups_id`='".$group->getID()."'";
$result = $DB->query($query);
if ($DB->numrows($result) > 0) {
$fields_array = $DB->result($result, 0, 'fields_array');
$computers_params = unserialize($fields_array);
}
}
} else {
if ($group->fields['type'] == PluginFusioninventoryDeployGroup::STATIC_GROUP
&& isset($_SESSION['glpisearch']['PluginFusioninventoryComputer'])
&& !isset($_SESSION['glpisearch']['PluginFusioninventoryComputer']['show_results'])) {
$computers_params = $_SESSION['glpisearch']['PluginFusioninventoryComputer'];
} else {
unset($_SESSION['glpisearch']['PluginFusioninventoryComputer']);
$computers_params = $_GET;
}
}
if ($getAll) {
$computers_params['export_all'] = true;
}
return Search::manageParams('PluginFusioninventoryComputer', $computers_params);
}
/**
* Clean when purge a deploy group
*/
function cleanDBOnPurge() {
$dynamic_group = new PluginFusioninventoryDeployGroup_Dynamicdata();
$static_group = new PluginFusioninventoryDeployGroup_Staticdata();
$params = ['plugin_fusioninventory_deploygroups_id' => $this->getID()];
$dynamic_group->deleteByCriteria($params);
$static_group->deleteByCriteria($params);
}
/**
* Display for a computer the groups where it is
*
* @param integer $computers_id
*/
function showForComputer($computers_id) {
global $DB;
echo "<table width='950' class='tab_cadre_fixe'>";
echo "<tr>";
echo "<th>";
echo __('Group');
echo "</th>";
echo "<th>";
echo __('Type');
echo "</th>";
echo "</tr>";
$link = Toolbox::getItemTypeFormURL("PluginFusioninventoryDeployGroup");
$iterator = $DB->request([
'FROM' => PluginFusioninventoryDeployGroup_Staticdata::getTable(),
'WHERE' => [
'items_id' => $computers_id,
'itemtype' => 'Computer',
],
]);
while ($data = $iterator->next()) {
$this->getFromDB($data['plugin_fusioninventory_deploygroups_id']);
echo "<tr>";
echo "<td>";
echo "<a href='".$link."?id=".$this->fields['id']."'>".$this->fields['name']."</a>";
echo "</td>";
echo "<td>";
echo __('Static group', 'fusioninventory');
echo "</td>";
echo "</tr>";
}
$iterator = $DB->request([
'FROM' => PluginFusioninventoryDeployGroup_Dynamicdata::getTable(),
'WHERE' => [
'computers_id_cache' => ["LIKE", '%"'.$computers_id.'"%'],
],
]);
while ($data = $iterator->next()) {
$this->getFromDB($data['plugin_fusioninventory_deploygroups_id']);
echo "<tr>";
echo "<td>";
echo "<a href='".$link."?id=".$this->fields['id']."'>".$this->fields['name']."</a>";
echo "</td>";
echo "<td>";
echo __('Dynamic group', 'fusioninventory');
echo "</td>";
echo "</tr>";
}
echo "</table>";
}
}

View File

@@ -0,0 +1,384 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the dynamic groups (based on search engine
* of GLPI).
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author Alexandre Delaunay
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the dynamic groups (based on search engine of GLPI).
*/
class PluginFusioninventoryDeployGroup_Dynamicdata extends CommonDBChild {
/**
* The right name for this class
*
* @var string
*/
static $rightname = "plugin_fusioninventory_group";
/**
* Itemtype of the item linked
*
* @var string
*/
static public $itemtype = 'PluginFusioninventoryDeployGroup';
/**
* id field of the item linked
*
* @var string
*/
static public $items_id = 'plugin_fusioninventory_deploygroups_id';
/**
* Get the tab name used for item
*
* @param object $item the item object
* @param integer $withtemplate 1 if is a template form
* @return string name of the tab
*/
function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) {
if (!$withtemplate
&& $item->fields['type'] == PluginFusioninventoryDeployGroup::DYNAMIC_GROUP) {
$tabs[1] = _n('Criterion', 'Criteria', 2);
// Get the count of matching items
$count = self::getMatchingItemsCount($item);
if ($_SESSION['glpishow_count_on_tabs']) {
$tabs[2] = self::createTabEntry(_n('Associated item', 'Associated items', $count), $count);
} else {
$tabs[2] = _n('Associated item', 'Associated items', $count);
}
return $tabs;
}
return '';
}
/**
* Get the count of items matching the dynamic search criteria
*
* This function saves and restores the pagination parameters to avoid breaking the pagination in the
* query results.
*
* @param object $item the item object
* @param integer $withtemplate 1 if is a template form
* @return string name of the tab
*/
function getMatchingItemsCount(CommonGLPI $item) {
// Save pagination parameters
$pagination_params = [];
foreach (['sort', 'order', 'start'] as $field) {
if (isset($_SESSION['glpisearch']['PluginFusioninventoryComputer'][$field])) {
$pagination_params[$field] = $_SESSION['glpisearch']['PluginFusioninventoryComputer'][$field];
}
}
$params = PluginFusioninventoryDeployGroup::getSearchParamsAsAnArray($item, false);
$params['massiveactionparams']['extraparams']['id'] = $_GET['id'];
if (isset($params['metacriteria']) && !is_array($params['metacriteria'])) {
$params['metacriteria'] = [];
}
$params['target'] = PluginFusioninventoryDeployGroup::getSearchEngineTargetURL($_GET['id'], true);
$data = Search::prepareDatasForSearch('Computer', $params);
Search::constructSQL($data);
// Use our specific constructDatas function rather than Glpi function
PluginFusioninventorySearch::constructDatas($data);
// Restore pagination parameters
foreach ($pagination_params as $key => $value) {
$_SESSION['glpisearch']['PluginFusioninventoryComputer'][$field] = $pagination_params[$field];
}
return $data['data']['totalcount'];
}
/**
* Display the content of the tab
*
* @param object $item
* @param integer $tabnum number of the tab to display
* @param integer $withtemplate 1 if is a template form
* @return boolean
*/
static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) {
switch ($tabnum) {
case 1:
self::showCriteriaAndSearch($item);
return true;
case 2:
// Save pagination parameters
$pagination_params = [];
foreach (['sort', 'order', 'start'] as $field) {
if (isset($_SESSION['glpisearch']['PluginFusioninventoryComputer'][$field])) {
$pagination_params[$field] = $_SESSION['glpisearch']['PluginFusioninventoryComputer'][$field];
}
}
$params = PluginFusioninventoryDeployGroup::getSearchParamsAsAnArray($item, false);
$params['massiveactionparams']['extraparams']['id'] = $_GET['id'];
// Include pagination parameters in the provided parameters
foreach ($pagination_params as $key => $value) {
$params[$key] = $value;
}
if (isset($params['metacriteria']) && !is_array($params['metacriteria'])) {
$params['metacriteria'] = [];
}
$params['target'] = PluginFusioninventoryDeployGroup::getSearchEngineTargetURL($_GET['id'], true);
self::showList('PluginFusioninventoryComputer', $params, ['1', '2']);
return true;
}
return false;
}
/**
* Display criteria form + list of computers
*
* @param object $item PluginFusioninventoryDeployGroup instance
*/
static function showCriteriaAndSearch(PluginFusioninventoryDeployGroup $item) {
// Save pagination parameters
$pagination_params = [];
foreach (['sort', 'order', 'start'] as $field) {
if (isset($_SESSION['glpisearch']['PluginFusioninventoryComputer'][$field])) {
$pagination_params[$field] = $_SESSION['glpisearch']['PluginFusioninventoryComputer'][$field];
}
}
// WITHOUT checking post values
$search_params = PluginFusioninventoryDeployGroup::getSearchParamsAsAnArray($item, false);
//If metacriteria array is empty, remove it as it displays the metacriteria form,
//and it's is not we want !
if (isset($search_params['metacriteria']) && empty($search_params['metacriteria'])) {
unset($search_params['metacriteria']);
}
PluginFusioninventoryDeployGroup::showCriteria($item, $search_params);
/* Do not display the search result on the current tab
* @mohierf: I do not remove this code if this feature is intended to be reactivated...
* -----
// Include pagination parameters in the provided parameters
foreach ($pagination_params as $key => $value) {
$search_params[$key] = $value;
}
// Add extra parameters for massive action display : only the Add action should be displayed
$search_params['massiveactionparams']['extraparams']['id'] = $item->getID();
$search_params['massiveactionparams']['extraparams']['custom_action'] = 'add_to_group';
$search_params['massiveactionparams']['extraparams']['massive_action_fields'] = ['action', 'id'];
$data = Search::prepareDatasForSearch('PluginFusioninventoryComputer', $search_params);
Search::constructSQL($data);
Search::constructDatas($data);
$data['search']['target'] = PluginFusioninventoryDeployGroup::getSearchEngineTargetURL($item->getID(), false);
Search::displayDatas($data);
*/
}
/**
* Display list of computers in the group
*
* @param string $itemtype
* @param array $params
* @param array $forcedisplay
*/
static function showList($itemtype, $params, $forcedisplay) {
$data = Search::prepareDatasForSearch('Computer', $params, $forcedisplay);
Search::constructSQL($data);
// Use our specific constructDatas function rather than Glpi function
PluginFusioninventorySearch::constructDatas($data);
// Remove some fields from the displayed columns
if (Session::isMultiEntitiesMode()) {
// Remove entity and computer Id
unset($data['data']['cols'][1]);
unset($data['data']['cols'][2]);
} else {
// Remove computer Id
unset($data['data']['cols'][1]);
}
Search::displayData($data);
}
/**
* Get data, so computer list
*
* @param string $itemtype
* @param array $params
* @param array $forcedisplay
* @return array
*/
static function getDatas($itemtype, $params, array $forcedisplay = []) {
$data = Search::prepareDatasForSearch('Computer', $params, $forcedisplay);
Search::constructSQL($data);
Search::constructData($data);
return $data;
}
/**
* Get computers belonging to a dynamic group
*
* @since 0.85+1.0
*
* @param group the group object
* @param use_cache retrieve computers_id from cache (computers_id_cache field)
* @return an array of computer ids
*/
static function getTargetsByGroup(PluginFusioninventoryDeployGroup $group, $use_cache = false) {
$ids = [];
if (!$use_cache || !$ids = self::retrieveCache($group)) {
$search_params = PluginFusioninventoryDeployGroup::getSearchParamsAsAnArray($group, false, true);
if (isset($search_params['metacriteria']) && empty($search_params['metacriteria'])) {
unset($search_params['metacriteria']);
}
//force no sort (Search engine will sort by id) for better performance
$search_params['sort'] = '';
//Only retrieve computers IDs
$results = self::getDatas(
'PluginFusioninventoryComputer',
$search_params,
['2']
);
$results = Search::prepareDatasForSearch('Computer', $search_params, ['2']);
Search::constructSQL($results);
// Use our specific constructDatas function rather than Glpi function
PluginFusioninventorySearch::constructDatas($results);
foreach ($results['data']['rows'] as $id => $row) {
$ids[$row['id']] = $row['id'];
}
//store results in cache (for reusing on agent communication)
self::storeCache($group, $ids);
}
return $ids;
}
/**
* Store a set of computers id in db
* @param PluginFusioninventoryDeployGroup $group the instance of fi group
* @param array $ids the list of id to store
* @return bool
*/
static function storeCache(PluginFusioninventoryDeployGroup $group, $ids = []) {
global $DB;
$result = $DB->update(
self::getTable(), [
'computers_id_cache' => $DB->escape(json_encode($ids))
], [
'plugin_fusioninventory_deploygroups_id' => $group->getID()
]
);
return $result;
}
/**
* Retrieve the id of computer stored in db for a group
* @param PluginFusioninventoryDeployGroup $group the instance of the group
* @return array the list of compuers id
*/
static function retrieveCache(PluginFusioninventoryDeployGroup $group) {
global $DB;
$ids = false;
$data = getAllDataFromTable(self::getTable(),
['plugin_fusioninventory_deploygroups_id' => $group->getID()]);
if (count($data)) {
$first = array_shift($data);
$ids = json_decode($first['computers_id_cache'], true);
}
return $ids;
}
/**
* Duplicate entries from one group to another
* @param $source_deploygroups_id the source group ID
* @param $target_deploygroups_id the target group ID
* @return the duplication status, as a boolean
*/
static function duplicate($source_deploygroups_id, $target_deploygroups_id) {
$result = true;
$pfDynamicGroup = new self();
$groups = $pfDynamicGroup->find(['plugin_fusioninventory_deploygroups_id' => $source_deploygroups_id]);
foreach ($groups as $group) {
unset($group['id']);
$group['plugin_fusioninventory_deploygroups_id']
= $target_deploygroups_id;
if (!$pfDynamicGroup->add($group)) {
$result = false;
}
}
return $result;
}
}

View File

@@ -0,0 +1,313 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the static groups (add manually computers
* in the group).
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author Alexandre Delaunay
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the static groups (add manually computers in the group).
*/
class PluginFusioninventoryDeployGroup_Staticdata extends CommonDBRelation{
/**
* The right name for this class
*
* @var string
*/
static $rightname = "plugin_fusioninventory_group";
/**
* Itemtype for the first part of relation
*
* @var string
*/
static public $itemtype_1 = 'PluginFusioninventoryDeployGroup';
/**
* id field name for the first part of relation
*
* @var string
*/
static public $items_id_1 = 'groups_id';
/**
* Itemtype for the second part of relation
*
* @var string
*/
static public $itemtype_2 = 'itemtype';
/**
* id field name for the second part of relation
*
* @var string
*/
static public $items_id_2 = 'items_id';
/**
* Get the tab name used for item
*
* @param object $item the item object
* @param integer $withtemplate 1 if is a template form
* @return string|array name of the tab
*/
function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) {
if (!$withtemplate
&& ($item->getType() == 'PluginFusioninventoryDeployGroup')
&& $item->fields['type'] == PluginFusioninventoryDeployGroup::STATIC_GROUP) {
$tabs[1] = _n('Criterion', 'Criteria', 2);
$count = countElementsInTable(getTableForItemType(__CLASS__),
[
'itemtype' => 'Computer',
'plugin_fusioninventory_deploygroups_id' => $item->fields['id'],
]);
if ($_SESSION['glpishow_count_on_tabs']) {
$tabs[2] = self::createTabEntry(_n('Associated item', 'Associated items', $count), $count);
} else {
$tabs[2] = _n('Associated item', 'Associated items', $count);
}
$tabs[3] = __('CSV import', 'fusioninventory');
return $tabs;
}
return '';
}
/**
* Display the content of the tab
*
* @param object $item
* @param integer $tabnum number of the tab to display
* @param integer $withtemplate 1 if is a template form
* @return boolean
*/
static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) {
switch ($tabnum) {
case 1:
self::showCriteriaAndSearch($item);
return true;
case 2:
self::showResults();
return true;
case 3:
self::csvImportForm($item);
return true;
}
return false;
}
/**
* Display criteria form + list of computers
*
* @param object $item PluginFusioninventoryDeployGroup instance
*/
static function showCriteriaAndSearch(PluginFusioninventoryDeployGroup $item) {
// WITH checking post values
$search_params = PluginFusioninventoryDeployGroup::getSearchParamsAsAnArray($item, true);
//If metacriteria array is empty, remove it as it displays the metacriteria form,
//and it's is not we want !
if (isset($search_params['metacriteria']) && empty($search_params['metacriteria'])) {
unset($search_params['metacriteria']);
}
PluginFusioninventoryDeployGroup::showCriteria($item, $search_params);
//Add extra parameters for massive action display : only the Add action should be displayed
$search_params['massiveactionparams']['extraparams']['id'] = $item->getID();
$search_params['massiveactionparams']['extraparams']['custom_action'] = 'add_to_group';
$search_params['massiveactionparams']['extraparams']['massive_action_fields'] = ['action', 'id'];
$data = Search::prepareDatasForSearch('PluginFusioninventoryComputer', $search_params);
$data['itemtype'] = 'Computer';
Search::constructSQL($data);
// Use our specific constructDatas function rather than Glpi function
PluginFusioninventorySearch::constructDatas($data);
$data['search']['target'] = PluginFusioninventoryDeployGroup::getSearchEngineTargetURL($item->getID(), false);
$data['itemtype'] = 'PluginFusioninventoryComputer';
Search::displayData($data);
}
/**
* Display result, so list of computers
*/
static function showResults() {
if (isset($_SESSION['glpisearch']['PluginFusioninventoryComputer'])
&& isset($_SESSION['glpisearch']['PluginFusioninventoryComputer']['show_results'])) {
$computers_params = $_SESSION['glpisearch']['PluginFusioninventoryComputer'];
}
$computers_params['metacriteria'] = [];
$computers_params['criteria'][] = ['searchtype' => 'equals',
'value' => $_GET['id'],
'field' => 5171];
$search_params = Search::manageParams('PluginFusioninventoryComputer', $computers_params);
//Add extra parameters for massive action display : only the Delete action should be displayed
$search_params['massiveactionparams']['extraparams']['id'] = $_GET['id'];
$search_params['massiveactionparams']['extraparams']['custom_action'] = 'delete_from_group';
$search_params['massiveactionparams']['extraparams']['massive_action_fields'] = ['action', 'id'];
$data = Search::prepareDatasForSearch('PluginFusioninventoryComputer', $search_params);
$data['itemtype'] = 'Computer';
Search::constructSQL($data);
// Use our specific constructDatas function rather than Glpi function
PluginFusioninventorySearch::constructDatas($data);
$data['search']['target'] = PluginFusioninventoryDeployGroup::getSearchEngineTargetURL($_GET['id'], false);
$data['itemtype'] = 'PluginFusioninventoryComputer';
Search::displayData($data);
}
/**
* Duplicate entries from one group to another
* @param $source_deploygroups_id the source group ID
* @param $target_deploygroups_id the target group ID
* @return the duplication status, as a boolean
*/
static function duplicate($source_deploygroups_id, $target_deploygroups_id) {
$result = true;
$pfStaticGroup = new self();
$groups = $pfStaticGroup->find(['plugin_fusioninventory_deploygroups_id' => $source_deploygroups_id]);
foreach ($groups as $group) {
unset($group['id']);
$group['plugin_fusioninventory_deploygroups_id']
= $target_deploygroups_id;
if (!$pfStaticGroup->add($group)) {
$result |= false;
}
}
return $result;
}
/**
* Form to import computers ID in CSV file
*
* @since 9.2+2.0
*
* @param object $item it's an instance of PluginFusioninventoryDeployGroup class
*
* @return boolean
*/
static function csvImportForm(PluginFusioninventoryDeployGroup $item) {
echo "<form action='' method='post' enctype='multipart/form-data'>";
echo "<br>";
echo "<table class='tab_cadre_fixe' cellpadding='1' width='600'>";
echo "<tr>";
echo "<th>";
echo __('Import a list of computers from a CSV file (the first column must contain the computer ID)', 'fusioninventory')." :";
echo "</th>";
echo "</tr>";
echo "<tr class='tab_bg_1'>";
echo "<td align='center'>";
echo Html::hidden('groups_id', ['value' => $item->getID()]);
echo "<input type='file' name='importcsvfile' value=''/>";
echo "&nbsp;".Html::submit(__('Import'));;
echo "</td>";
echo "</tr>";
echo "</table>";
Html::closeForm();
return true;
}
/**
* Import into DB the computers ID
*
* @since 9.2+2.0
*
* @param array $post_data
* @param array $files_data array with information of $_FILE
*
* @return boolean
*/
static function csvImport($post_data, $files_data) {
$pfDeployGroup_static = new self();
$computer = new Computer();
$input = [
'plugin_fusioninventory_deploygroups_id' => $post_data['groups_id'],
'itemtype' => 'Computer'
];
if (isset($files_data['importcsvfile']['tmp_name'])) {
if (($handle = fopen($files_data['importcsvfile']['tmp_name'], "r")) !== false) {
while (($data = fgetcsv($handle, 1000, $_SESSION["glpicsv_delimiter"])) !== false) {
$input['items_id'] = str_replace(' ', '', $data[0]);
if ($computer->getFromDB($input['items_id'])) {
$pfDeployGroup_static->add($input);
}
}
Session::addMessageAfterRedirect(__('Computers imported successfully from CSV file', 'fusioninventory'), false, INFO);
fclose($handle);
} else {
Session::addMessageAfterRedirect(__('Impossible to read the CSV file', 'fusioninventory'), false, ERROR);
return false;
}
} else {
Session::addMessageAfterRedirect(sprintf( __('%1$s %2$s'), "File not found", $files_data['importcsvfile']['tmp_name']), false, ERROR);
return false;
}
return true;
}
}

View File

@@ -0,0 +1,419 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the deploy mirror depend on location of
* computer.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author Walid Nouh
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the deploy mirror depend on location of computer.
*/
class PluginFusioninventoryDeployMirror extends CommonDBTM {
const MATCH_LOCATION = 0;
const MATCH_ENTITY = 1;
const MATCH_BOTH = 2;
/**
* We activate the history.
*
* @var boolean
*/
public $dohistory = true;
/**
* The right name for this class
*
* @var string
*/
static $rightname = 'plugin_fusioninventory_deploymirror';
/**
* Get name of this type by language of the user connected
*
* @param integer $nb number of elements
* @return string name of this type
*/
static function getTypeName($nb = 0) {
return __('Mirror servers', 'fusioninventory');
}
/**
* Define tabs to display on form page
*
* @param array $options
* @return array containing the tabs name
*/
function defineTabs($options = []) {
$ong=[];
$this->addDefaultFormTab($ong)
->addStandardTab('Log', $ong, $options);
return $ong;
}
/**
* Get and filter mirrors list by computer agent and location.
* Location is retrieved from the computer data.
*
* @global array $PF_CONFIG
* @param integer $agents_id
* @return array
*/
static function getList($agents_id) {
global $PF_CONFIG, $DB;
if (is_null($agents_id)) {
return [];
}
$pfAgent = new PluginFusioninventoryAgent();
$pfAgent->getFromDB($agents_id);
$agent = $pfAgent->fields;
if (!isset($agent) || !isset($agent['computers_id'])) {
return [];
}
$computer = new Computer();
$computer->getFromDB($agent['computers_id']);
//If no configuration has been done in the plugin's configuration
//then use location for mirrors as default
//!!this should not happen!!
if (!isset($PF_CONFIG['mirror_match'])) {
$mirror_match = self::MATCH_LOCATION;
} else {
//Get mirror matching from plugin's general configuration
$mirror_match = $PF_CONFIG['mirror_match'];
}
//Get all mirrors for the agent's entity, or for entities above
//sorted by entity level in a descending way (going to the closest,
//deepest entity, to the highest)
$query = "SELECT `mirror`.*, `glpi_entities`.`level`
FROM `glpi_plugin_fusioninventory_deploymirrors` AS mirror
LEFT JOIN `glpi_entities`
ON (`mirror`.`entities_id`=`glpi_entities`.`id`)
WHERE `mirror`.`is_active`='1'";
$query .= getEntitiesRestrictRequest(' AND ',
'mirror',
'entities_id',
$agent['entities_id'],
true);
$query .= " ORDER BY `glpi_entities`.`level` DESC";
//The list of mirrors to return
$mirrors = [];
foreach ($DB->request($query) as $result) {
//First, check mirror by location
if (in_array($mirror_match, [self::MATCH_LOCATION, self::MATCH_BOTH])
&& $computer->fields['locations_id'] > 0
&& $computer->fields['locations_id'] == $result['locations_id']) {
$mirrors[] = $result['url'];
}
//Second, check by entity
if (in_array($mirror_match, [self::MATCH_ENTITY, self::MATCH_BOTH])) {
$entities = $result['entities_id'];
//If the mirror is visible in child entities then get all child entities
//and check it the agent's entity is one of it
if ($result['is_recursive']) {
$entities = getSonsOf('glpi_entities', $result['entities_id']);
}
$add_mirror = false;
if (is_array($entities)
&& in_array($computer->fields['entities_id'], $entities)) {
$add_mirror = true;
} else if ($computer->fields['entities_id'] == $result['entities_id']) {
$add_mirror = true;
}
if (!in_array($result['url'], $mirrors) && $add_mirror) {
$mirrors[] = $result['url'];
}
}
}
//add default mirror (this server) if enabled in config
$entities_id = 0;
if (isset($agent['entities_id'])) {
$entities_id = $agent['entities_id'];
}
//If option is set to yes in general plugin configuration
//Add the server's url as the last url in the list
if (isset($PF_CONFIG['server_as_mirror'])
&& $PF_CONFIG['server_as_mirror'] == true) {
$mirrors[] = PluginFusioninventoryAgentmodule::getUrlForModule('DEPLOY', $entities_id)
."?action=getFilePart&file=";
}
return $mirrors;
}
/**
* Display form
*
* @global array $CFG_GLPI
* @param integer $id
* @param array $options
* @return true
*/
function showForm($id, $options = []) {
global $CFG_GLPI;
$this->initForm($id, $options);
$this->showFormHeader($options);
echo "<tr class='tab_bg_1'>";
echo "<td>".__('Name')."</td>";
echo "<td align='center'>";
Html::autocompletionTextField($this, 'name', ['size' => 40]);
echo "</td>";
echo "<td rowspan='3' class='middle right'>".__('Comments')."&nbsp;: </td>";
echo "<td class='center middle' rowspan='2'><textarea cols='45'
rows='4' name='comment' >".$this->fields["comment"]."</textarea></td></tr>";
echo "<tr class='tab_bg_1'><td>".__('Active')."</td><td align='center'>";
Dropdown::showYesNo("is_active", $this->fields["is_active"]);
echo "</td></tr>";
echo "<tr class='tab_bg_1'>";
echo "<td>".__('Mirror server address', 'fusioninventory')."&nbsp;:</td>";
echo "<td align='center'>";
Html::autocompletionTextField($this, 'url', ['size' => 40]);
echo "</td></tr>";
echo "<tr class='tab_bg_1'>";
echo "<td>".__('Mirror location', 'fusioninventory')." (".__('Location').")"."&nbsp;:</td>";
echo "<td align='center'>";
//If
if ($this->can($id, UPDATE)) {
echo "<script type='text/javascript'>\n";
echo "document.getElementsByName('is_recursive')[0].id = 'is_recursive';\n";
echo "</script>";
$params = ['is_recursive' => '__VALUE__',
'id' => $id
];
Ajax::updateItemOnEvent('is_recursive', "displaydropdownlocation",
Plugin::getWebDir('fusioninventory')."/ajax/dropdownlocation.php", $params);
echo "<div id='displaydropdownlocation'>";
// Location option
Location::dropdown([ 'value' => $this->fields["locations_id"],
'entity' => $this->fields["entities_id"],
'entity_sons' => $this->isRecursive(),
'emptylabel' => __('None')
]);
echo "</div>";
} else {
echo Dropdown::getDropdownName('glpi_locations', $this->fields['locations_id']);
}
echo "</td></tr>";
$this->showFormButtons($options);
return true;
}
/**
* Get search function for the class
*
* @return array
*/
function rawSearchOptions() {
$tab = [];
$tab[] = [
'id' => 'common',
'name' => self::getTypeName(),
];
$tab[] = [
'id' => '1',
'table' => $this->getTable(),
'field' => 'name',
'name' => __('Name'),
'datatype' => 'itemlink',
'itemlink_type' => $this->getType(),
'autocomplete' => true,
];
$tab[] = [
'id' => '19',
'table' => $this->getTable(),
'field' => 'date_mod',
'name' => __('Last update'),
'datatype' => 'datetime',
];
$tab[] = [
'id' => '2',
'table' => $this->getTable(),
'field' => 'url',
'name' => __('Mirror server address', 'fusioninventory'),
'datatype' => 'string',
'autocomplete' => true,
];
$tab[] = [
'id' => '6',
'table' => $this->getTable(),
'field' => 'is_active',
'name' => __('Active'),
'datatype' => 'bool',
];
$tab[] = [
'id' => '16',
'table' => $this->getTable(),
'field' => 'comment',
'name' => __('Comments'),
'datatype' => 'text',
];
$tab[] = [
'id' => '80',
'table' => 'glpi_entities',
'field' => 'completename',
'name' => Entity::getTypeName(1),
'datatype' => 'dropdown',
];
$tab[] = [
'id' => '86',
'table' => $this->getTable(),
'field' => 'is_recursive',
'name' => __('Child entities'),
'datatype' => 'bool',
];
$name = _n('Volume', 'Volumes', Session::getPluralNumber());
$tab[] = [
'id' => 'disk',
'name' => $name
];
$tab = array_merge($tab, Location::rawSearchOptionsToAdd());
return $tab;
}
/**
* Get the massive actions for this object
*
* @param object|null $checkitem
* @return array list of actions
*/
function getSpecificMassiveActions($checkitem = null) {
return [__CLASS__.MassiveAction::CLASS_ACTION_SEPARATOR.'transfer'
=> __('Transfer')];
}
/**
* Display form related to the massive action selected
*
* @param object $ma MassiveAction instance
* @return boolean
*/
static function showMassiveActionsSubForm(MassiveAction $ma) {
if ($ma->getAction() == 'transfer') {
Dropdown::show('Entity');
echo Html::submit(_x('button', 'Post'), ['name' => 'massiveaction']);
return true;
}
return false;
}
/**
* Execution code for massive action
*
* @param object $ma MassiveAction instance
* @param object $item item on which execute the code
* @param array $ids list of ID on which execute the code
*/
static function processMassiveActionsForOneItemtype(MassiveAction $ma, CommonDBTM $item,
array $ids) {
$pfDeployMirror = new self();
switch ($ma->getAction()) {
case "transfer" :
foreach ($ids as $key) {
if ($pfDeployMirror->getFromDB($key)) {
$input = [];
$input['id'] = $key;
$input['entities_id'] = $_POST['entities_id'];
if ($pfDeployMirror->update($input)) {
//set action massive ok for this item
$ma->itemDone($item->getType(), $key, MassiveAction::ACTION_OK);
} else {
// KO
$ma->itemDone($item->getType(), $key, MassiveAction::ACTION_KO);
}
}
}
break;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,120 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the visibility of package by entity.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @author Alexandre Delaunay
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the visibility of package by entity.
*/
class PluginFusioninventoryDeployPackage_Entity extends CommonDBRelation {
/**
* Itemtype for the first part of relation
*
* @var string
*/
static public $itemtype_1 = 'PluginFusioninventoryDeployPackage';
/**
* id field name for the first part of relation
*
* @var string
*/
static public $items_id_1 = 'plugin_fusioninventory_deploypackages_id';
/**
* Itemtype for the second part of relation
*
* @var string
*/
static public $itemtype_2 = 'Entity';
/**
* id field name for the second part of relation
*
* @var string
*/
static public $items_id_2 = 'entities_id';
/**
* Set we don't check parent right of the second item
*
* @var integer
*/
static public $checkItem_2_Rights = self::DONT_CHECK_ITEM_RIGHTS;
/**
* Logs for the second item are disabled
*
* @var type
*/
static public $logs_for_item_2 = false;
/**
* Get entities for a deploypackage
*
* @global object $DB
* @param integer $deploypackages_id ID of the deploypackage
* @return array list of of entities linked to a deploypackage
**/
static function getEntities($deploypackages_id) {
global $DB;
$ent = [];
$query = "SELECT `glpi_plugin_fusioninventory_deploypackages_entities`.*
FROM `glpi_plugin_fusioninventory_deploypackages_entities`
WHERE `plugin_fusioninventory_deploypackages_id` = '$deploypackages_id'";
foreach ($DB->request($query) as $data) {
$ent[$data['entities_id']][] = $data;
}
return $ent;
}
}

View File

@@ -0,0 +1,120 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the visibility of package by group.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @author Alexandre Delaunay
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the visibility of package by group.
*/
class PluginFusioninventoryDeployPackage_Group extends CommonDBRelation {
/**
* Itemtype for the first part of relation
*
* @var string
*/
static public $itemtype_1 = 'PluginFusioninventoryDeployPackage';
/**
* id field name for the first part of relation
*
* @var string
*/
static public $items_id_1 = 'plugin_fusioninventory_deploypackages_id';
/**
* Itemtype for the second part of relation
*
* @var string
*/
static public $itemtype_2 = 'Group';
/**
* id field name for the second part of relation
*
* @var string
*/
static public $items_id_2 = 'groups_id';
/**
* Set we don't check parent right of the second item
*
* @var integer
*/
static public $checkItem_2_Rights = self::DONT_CHECK_ITEM_RIGHTS;
/**
* Logs for the second item are disabled
*
* @var type
*/
static public $logs_for_item_2 = false;
/**
* Get groups for a deploypackage
*
* @global object $DB
* @param integer $deploypackages_id ID of the deploypackage
* @return array list of groups linked to a deploypackage
**/
static function getGroups($deploypackages_id) {
global $DB;
$groups = [];
$query = "SELECT `glpi_plugin_fusioninventory_deploypackages_groups`.*
FROM `glpi_plugin_fusioninventory_deploypackages_groups`
WHERE plugin_fusioninventory_deploypackages_id = '$deploypackages_id'";
foreach ($DB->request($query) as $data) {
$groups[$data['groups_id']][] = $data;
}
return $groups;
}
}

View File

@@ -0,0 +1,120 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the visibility of package by profile.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @author Alexandre Delaunay
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the visibility of package by profile.
*/
class PluginFusioninventoryDeployPackage_Profile extends CommonDBRelation {
/**
* Itemtype for the first part of relation
*
* @var string
*/
static public $itemtype_1 = 'PluginFusioninventoryDeployPackage';
/**
* id field name for the first part of relation
*
* @var string
*/
static public $items_id_1 = 'plugin_fusioninventory_deploypackages_id';
/**
* Itemtype for the second part of relation
*
* @var string
*/
static public $itemtype_2 = 'Profile';
/**
* id field name for the second part of relation
*
* @var string
*/
static public $items_id_2 = 'profiles_id';
/**
* Set we don't check parent right of the second item
*
* @var integer
*/
static public $checkItem_2_Rights = self::DONT_CHECK_ITEM_RIGHTS;
/**
* Logs for the second item are disabled
*
* @var type
*/
static public $logs_for_item_2 = false;
/**
* Get profiles for a deploypackage
*
* @global object $DB
* @param integer $deploypackages_id ID of the deploypackage
* @return array list of profiles linked to a deploypackage
**/
static function getProfiles($deploypackages_id) {
global $DB;
$prof = [];
$query = "SELECT `glpi_plugin_fusioninventory_deploypackages_profiles`.*
FROM `glpi_plugin_fusioninventory_deploypackages_profiles`
WHERE `plugin_fusioninventory_deploypackages_id` = '$deploypackages_id'";
foreach ($DB->request($query) as $data) {
$prof[$data['profiles_id']][] = $data;
}
return $prof;
}
}

View File

@@ -0,0 +1,120 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the visibility of package by user.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @author Alexandre Delaunay
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the visibility of package by user.
*/
class PluginFusioninventoryDeployPackage_User extends CommonDBRelation {
/**
* Itemtype for the first part of relation
*
* @var string
*/
static public $itemtype_1 = 'PluginFusioninventoryDeployPackage';
/**
* id field name for the first part of relation
*
* @var string
*/
static public $items_id_1 = 'plugin_fusioninventory_deploypackages_id';
/**
* Itemtype for the second part of relation
*
* @var string
*/
static public $itemtype_2 = 'User';
/**
* id field name for the second part of relation
*
* @var string
*/
static public $items_id_2 = 'users_id';
/**
* Set we don't check parent right of the second item
*
* @var integer
*/
static public $checkItem_2_Rights = self::DONT_CHECK_ITEM_RIGHTS;
/**
* Logs for the second item are disabled
*
* @var type
*/
static public $logs_for_item_2 = false;
/**
* Get users for a deploypackage
*
* @global object $DB
* @param integer $deploypackages_id ID of the deploypackage
* @return array list of users linked to a deploypackage
**/
static function getUsers($deploypackages_id) {
global $DB;
$users = [];
$query = "SELECT `glpi_plugin_fusioninventory_deploypackages_users`.*
FROM `glpi_plugin_fusioninventory_deploypackages_users`
WHERE `plugin_fusioninventory_deploypackages_id` = '$deploypackages_id'";
foreach ($DB->request($query) as $data) {
$users[$data['users_id']][] = $data;
}
return $users;
}
}

View File

@@ -0,0 +1,455 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the deploy packages.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author Walid Nouh
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Abstract class to manage display, add, update, remove and move of items
* in a package
* @since 9.2
*/
class PluginFusioninventoryDeployPackageItem extends CommonDBTM {
//Display modes
const CREATE = 'create';
const EDIT = 'edit';
const INIT = 'init';
public $shortname = '';
//The section name in the JSON representation
public $json_name = '';
/**
* Get an event label by it's identifier
* @since 9.2
* @return array
*/
function getLabelForAType($type) {
$types = $this->getTypes();
if (isset($types[$type])) {
return $type[$type];
} else {
return false;
}
}
/**
* Get the types already in used, so they cannot be selected anymore
* @since 9.2
* @param $package the package to check
* @return the types already in used
*/
function getTypesAlreadyInUse(PluginFusioninventoryDeployPackage $package) {
return [];
}
/**
* Display the dropdown to select type of element
*
* @global array $CFG_GLPI
* @param object $package the package
* @param array $config order item configuration
* @param string $rand unique element id used to identify/update an element
* @param string $mode mode in use (create, edit...)
*/
function displayDropdownType(PluginFusioninventoryDeployPackage $package,
$config, $rand, $mode) {
global $CFG_GLPI;
//In case of a file item, there's no type, so don't display dropdown
//in edition mode
if (!isset($config['type']) && $mode == self::EDIT) {
return true;
}
/*
* Display dropdown html
*/
echo "<table class='package_item'>";
echo "<tr>";
echo "<th>"._n("Type", "Types", 1)."</th>";
echo "<td>";
$type_field = $this->shortname."type";
if ($mode === self::CREATE) {
$types = $this->getTypes();
array_unshift($types, Dropdown::EMPTY_VALUE);
Dropdown::showFromArray($type_field, $types,
['rand' => $rand,
'used' => $this->getTypesAlreadyInUse($package)
]);
$params = [
'value' => '__VALUE__',
'rand' => $rand,
'myname' => 'method',
'type' => $this->shortname,
'class' => get_class($this),
'mode' => $mode
];
Ajax::updateItemOnEvent(
"dropdown_".$type_field.$rand,
"show_".$this->shortname."_value$rand",
Plugin::getWebDir('fusioninventory').
"/ajax/deploy_displaytypevalue.php",
$params,
["change", "load"]
);
} else {
echo Html::hidden($type_field, ['value' => $config['type']]);
echo $this->getLabelForAType($config['type']);
}
echo "</td>";
echo "</tr></table>";
}
/**
* Create a configuration request data
*
* @since 9.2
*/
public function getItemConfig(PluginFusioninventoryDeployPackage $package, $request_data) {
$config = [];
$element = $package->getSubElement($this->json_name, $request_data['index']);
if (is_array($element) && count($element)) {
$config = [ 'type' => $element['type'],
'data' => $element];
}
return $config;
}
/**
* Display form
*
* @param object $package PluginFusioninventoryDeployPackage instance
* @param array $request_data
* @param string $rand unique element id used to identify/update an element
* @param string $mode possible values: init|edit|create
*/
function displayForm(PluginFusioninventoryDeployPackage $package,
$request_data, $rand, $mode) {
/*
* Get element config in 'edit' mode
*/
$config = null;
if ($mode === self::EDIT && isset($request_data['index'])) {
/*
* Add an hidden input about element's index to be updated
*/
echo Html::hidden('index', ['value' => $request_data['index']]);
$config = $this->getItemConfig($package, $request_data);
}
/*
* Display start of div form
*/
if (in_array($mode, [self::INIT], true)) {
echo "<div id='".$this->shortname."_block$rand' style='display:none'>";
}
/*
* Display element's dropdownType in 'create' or 'edit' mode
*/
if (in_array($mode, [self::CREATE, self::EDIT], true)) {
$this->displayDropdownType($package, $config, $rand, $mode);
}
/*
* Display element's values in 'edit' mode only.
* In 'create' mode, those values are refreshed with dropdownType 'change'
* javascript event.
*/
if (in_array($mode, [self::CREATE, self::EDIT], true)) {
echo "<span id='show_".$this->shortname."_value{$rand}'>";
if ($mode === self::EDIT) {
$this->displayAjaxValues($config, $request_data, $rand, $mode);
}
echo "</span>";
}
/*
* Close form div
*/
if (in_array($mode, [self::INIT], true)) {
echo "</div>";
}
}
/**
* Get an HTML mandatory mark (a red star)
* @since 9.2
* @return the html code for a red star
*/
function getMandatoryMark() {
return "&nbsp;<span class='red'>*</span>";
}
/**
* Common method to add an item to the package JSON definition
*
* @since 9.2
* @param id the package ID
* @param item the item to add to the package definition
*/
function addToPackage($id, $item, $order) {
//get current json package defintion
$data = json_decode($this->getJson($id), true);
//add new entry
$data['jobs'][$order][] = $item;
//Update package
$this->updateOrderJson($id, $data);
}
/**
* Get the json
*
* @param integer $packages_id id of the order
* @return boolean|string the string is in json format
*/
function getJson($packages_id) {
$pfDeployPackage = new PluginFusioninventoryDeployPackage();
$pfDeployPackage->getFromDB($packages_id);
if (!empty($pfDeployPackage->fields['json'])) {
return $pfDeployPackage->fields['json'];
} else {
return false;
}
}
function prepareDataToSave($params, $entry) {
//get current order json
$data = json_decode($this->getJson($params['id']), true);
//unset index
unset($data['jobs'][$this->json_name][$params['index']]);
//add new data at index position
//(array_splice for insertion, ex : http://stackoverflow.com/a/3797526)
array_splice($data['jobs'][$this->json_name],
$params['index'], 0, [$entry]);
return $data;
}
/**
* Update the order json
*
* @param integer $packages_id
* @param array $data
* @return integer error number
*/
function updateOrderJson($packages_id, $data) {
$pfDeployPackage = new PluginFusioninventoryDeployPackage();
$options = JSON_UNESCAPED_SLASHES;
$json = json_encode($data, $options);
$json_error_consts = [
JSON_ERROR_NONE => "JSON_ERROR_NONE",
JSON_ERROR_DEPTH => "JSON_ERROR_DEPTH",
JSON_ERROR_STATE_MISMATCH => "JSON_ERROR_STATE_MISMATCH",
JSON_ERROR_CTRL_CHAR => "JSON_ERROR_CTRL_CHAR",
JSON_ERROR_SYNTAX => "JSON_ERROR_SYNTAX",
JSON_ERROR_UTF8 => "JSON_ERROR_UTF8"
];
$error_json = json_last_error();
$error_json_message = json_last_error_msg();
$error = 0;
if ($error_json != JSON_ERROR_NONE) {
$error_msg = $json_error_consts[$error_json];
Session::addMessageAfterRedirect(
__("The modified JSON contained a syntax error :", "fusioninventory") . "<br/>" .
$error_msg . "<br/>". $error_json_message, false, ERROR, false
);
$error = 1;
} else {
$error = $pfDeployPackage->update(['id' => $packages_id,
'json' => Toolbox::addslashes_deep($json)]);
}
return $error;
}
/**
* Remove an item
*
* @param array $params
* @return boolean
*/
function remove_item($params) {
if (!isset($params[$this->shortname.'_entries'])) {
return false;
}
//get current order json
$data = json_decode($this->getJson($params['packages_id']), true);
//remove selected checks
foreach ($params[$this->shortname.'_entries'] as $index => $checked) {
if ($checked >= "1" || $checked == "on") {
unset($data['jobs'][$this->shortname][$index]);
}
}
//Ensure actions list is an array and not a dictionnary
//Note: This happens when removing an array element from the begining
$data['jobs'][$this->shortname] = array_values($data['jobs'][$this->shortname]);
//update order
$this->updateOrderJson($params['packages_id'], $data);
}
/**
* Move an item
*
* @param array $params
*/
function move_item($params) {
//get current order json
$data = json_decode($this->getJson($params['id']), true);
//get data on old index
$moved_check = $data['jobs'][$this->json_name][$params['old_index']];
//remove this old index in json
unset($data['jobs'][$this->json_name][$params['old_index']]);
//insert it in new index (array_splice for insertion, ex : http://stackoverflow.com/a/3797526)
array_splice($data['jobs'][$this->json_name], $params['new_index'], 0, [$moved_check]);
//update order
$this->updateOrderJson($params['id'], $data);
}
/**
* Get the size of file
*
* @param integer $filesize
* @return string
*/
function processFilesize($filesize) {
if (is_numeric($filesize)) {
if ($filesize >= (1024 * 1024 * 1024)) {
$filesize = round($filesize / (1024 * 1024 * 1024), 1)."GiB";
} else if ($filesize >= 1024 * 1024) {
$filesize = round($filesize / (1024 * 1024), 1)."MiB";
} else if ($filesize >= 1024) {
$filesize = round($filesize / 1024, 1)."KB";
} else {
$filesize = $filesize."B";
}
return $filesize;
} else {
return NOT_AVAILABLE;
}
}
/**
* Display a add or save button
* @since 9.2
*
* @param pfDeployPackage the package in use
* @param mode the mode (edit or create)
*/
function addOrSaveButton(PluginFusioninventoryDeployPackage $pfDeployPackage, $mode) {
echo "<tr>";
echo "<td>";
echo "</td>";
echo "<td>";
if ($pfDeployPackage->can($pfDeployPackage->getID(), UPDATE)) {
if ($mode === self::EDIT) {
echo "<input type='submit' name='save_item' value=\"".
_sx('button', 'Save')."\" class='submit' >";
} else {
echo "<input type='submit' name='add_item' value=\"".
_sx('button', 'Add')."\" class='submit' >";
}
}
echo "</td>";
echo "</tr>";
}
public function getItemValues($packages_id) {
$data = json_decode($this->getJson($packages_id), true);
if ($data) {
return $data['jobs'][$this->json_name];
} else {
return [];
}
}
function displayAjaxValues($config, $request_data, $rand, $mode) {
return true;
}
function getTypes() {
return [];
}
}

View File

@@ -0,0 +1,275 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the deploy task.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author Alexandre Delaunay
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
include_once(PLUGIN_FUSIONINVENTORY_DIR . "/inc/taskjobview.class.php");
include_once(PLUGIN_FUSIONINVENTORY_DIR . "/inc/taskview.class.php");
include_once(PLUGIN_FUSIONINVENTORY_DIR . "/inc/task.class.php");
/**
* Manage the deploy task.
*/
class PluginFusioninventoryDeployTask extends PluginFusioninventoryTask {
/**
* Get name of this type by language of the user connected
*
* @param integer $nb number of elements
* @return string name of this type
*/
static function getTypeName($nb = 0) {
if ($nb > 1) {
return PluginFusioninventoryDeployGroup::getTypeName();
}
return __('Task', 'fusioninventory');
}
/**
* Is this use can create a deploy task
*
* @return boolean
*/
static function canCreate() {
return true;
}
/**
* Is this use can view a deploy task
*
* @return boolean
*/
static function canView() {
return true;
}
/**
* Define tabs to display on form page
*
* @param array $options
* @return array containing the tabs name
*/
function defineTabs($options = []) {
$ong = [];
if ($this->fields['id'] > 0) {
$this->addStandardTab(__CLASS__, $ong, $options);
}
return $ong;
}
/**
* Get the tab name used for item
*
* @param object $item the item object
* @param integer $withtemplate 1 if is a template form
* @return string name of the tab
*/
function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) {
switch (get_class($item)) {
case __CLASS__:
return __('Order list', 'fusioninventory');
}
return '';
}
/**
* Display the content of the tab
*
* @param object $item
* @param integer $tabnum number of the tab to display
* @param integer $withtemplate 1 if is a template form
* @return boolean
*/
static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) {
switch (get_class($item)) {
case __CLASS__:
$obj = new self;
$obj->showActions($_POST["id"]);
return true;
}
return false;
}
/**
* Show list of deploy tasks
*/
function showList() {
self::title();
Search::show('PluginFusioninventoryDeployTask');
}
/**
* Display the title of the page
*
* @global array $CFG_GLPI
*/
function title() {
global $CFG_GLPI;
$buttons = [];
$title = __('Task', 'fusioninventory');
if ($this->canCreate()) {
$buttons["task.form.php?new=1"] = __('Add task', 'fusioninventory');
$title = "";
}
Html::displayTitle($CFG_GLPI["root_doc"] . "/plugins/fusinvdeploy/pics/task.png",
$title, $title, $buttons);
}
/**
* Show actions of the deploy task
*
* @param integer $id
*/
function showActions($id) {
//load extjs plugins library
echo "<script type='text/javascript'>";
require_once GLPI_ROOT."/plugins/fusinvdeploy/lib/extjs/Spinner.js";
require_once GLPI_ROOT."/plugins/fusinvdeploy/lib/extjs/SpinnerField.js";
echo "</script>";
$this->getFromDB($id);
if ($this->getField('is_active') == 1) {
echo "<div class='box' style='margin-bottom:20px;'>";
echo "<div class='box-tleft'><div class='box-tright'><div class='box-tcenter'>";
echo "</div></div></div>";
echo "<div class='box-mleft'><div class='box-mright'><div class='box-mcenter'>";
echo __('Edit impossible, this task is active', 'fusioninventory');
echo "</div></div></div>";
echo "<div class='box-bleft'><div class='box-bright'><div class='box-bcenter'>";
echo "</div></div></div>";
echo "</div>";
}
echo "<table class='deploy_extjs'>
<tbody>
<tr>
<td id='TaskJob'>
</td>
</tr>
</tbody>
</table>";
// Include JS
require GLPI_ROOT."/plugins/fusinvdeploy/js/task_job.front.php";
}
/**
* Do this before delete a deploy task
*
* @global array $CFG_GLPI
* @return boolean
*/
function pre_deleteItem() {
global $CFG_GLPI;
//if task active, delete denied
if ($this->getField('is_active') == 1) {
Session::addMessageAfterRedirect(
__('This task is active. delete denied', 'fusioninventory'));
Html::redirect($CFG_GLPI["root_doc"]."/plugins/fusinvdeploy/front/task.form.php?id=".
$this->getField('id'));
return false;
}
$task_id = $this->getField('id');
$job = new PluginFusioninventoryTaskjob();
$status = new PluginFusioninventoryTaskjobstate();
$log = new PluginFusioninventoryTaskjoblog();
// clean all sub-tables
$a_taskjobs = $job->find(['plugin_fusioninventory_tasks_id' => $task_id]);
foreach ($a_taskjobs as $a_taskjob) {
$a_taskjobstatuss = $status->find(['plugin_fusioninventory_taskjobs_id' => $a_taskjob['id']]);
foreach ($a_taskjobstatuss as $a_taskjobstatus) {
$a_taskjoblogs = $log->find(['plugin_fusioninventory_taskjobstates_id' => $a_taskjobstatus['id']]);
foreach ($a_taskjoblogs as $a_taskjoblog) {
$log->delete($a_taskjoblog, 1);
}
$status->delete($a_taskjobstatus, 1);
}
$job->delete($a_taskjob, 1);
}
return true;
}
/**
* Do this after added an item
*/
function post_addItem() {
$options = [
'id' => $this->getField('id'),
'date_creation' => date("Y-m-d H:i:s")
];
$this->update($options);
}
}

View File

@@ -0,0 +1,309 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the deploy task job.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @author Alexandre Delaunay
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the deploy task job.
*
* @todo This class should inherit the PluginFusioninventoryTaskjob
*/
class PluginFusioninventoryDeployTaskjob extends CommonDBTM {
/**
* Is this use can create a deploy task job
*
* @return boolean
*/
static function canCreate() {
return true;
}
/**
* Is this use can view a deploy task job
*
* @return boolean
*/
static function canView() {
return true;
}
/**
* Get all data
*
* @global object $DB
* @param array $params
* @return string in JSON format
*/
function getAllDatas($params) {
global $DB;
$tasks_id = $params['tasks_id'];
$sql = " SELECT *
FROM `".$this->getTable()."`
WHERE `plugin_fusioninventory_deploytasks_id` = '$tasks_id'
AND method = 'deployinstall'";
$res = $DB->query($sql);
$json = [];
$temp_tasks = [];
while ($row = $DB->fetchAssoc($res)) {
$row['packages'] = importArrayFromDB($row['definition']);
$row['actions'] = importArrayFromDB($row['action']);
$temp_tasks[] = $row;
}
$i = 0;
foreach ($temp_tasks as $task) {
foreach ($task['actions'] as $action) {
foreach ($task['packages'] as $package) {
$tmp = array_keys($action);
$action_type = $tmp[0];
$json['tasks'][$i]['package_id'] = $package['PluginFusioninventoryDeployPackage'];
$json['tasks'][$i]['method'] = $task['method'];
$json['tasks'][$i]['comment'] = $task['comment'];
$json['tasks'][$i]['retry_nb'] = $task['retry_nb'];
$json['tasks'][$i]['retry_time'] = $task['retry_time'];
$json['tasks'][$i]['action_type'] = $action_type;
$json['tasks'][$i]['action_selection'] = $action[$action_type];
$obj_action = new $action_type();
$obj_action->getFromDB($action[$action_type]);
$json['tasks'][$i]['action_name'] = $obj_action->getField('name');
$i++;
}
}
}
return json_encode($json);
}
/**
* Save data
*
* @global object $DB
* @param array $params
*/
function saveDatas($params) {
global $DB;
$tasks_id = $params['tasks_id'];
$tasks = json_decode($params['tasks']);
//remove old jobs from task
$this->deleteByCriteria(['plugin_fusioninventory_deploytasks_id' => $tasks_id], true);
//get plugin id
$plug = new Plugin();
$plug->getFromDBbyDir('fusinvdeploy');
$plugins_id = $plug->getField('id');
//insert new rows
$sql_tasks = [];
$i = 0;
$qparam = new QueryParam();
$query = $DB::buildInsert(
$this->getTable(), [
'plugin_fusioninventory_deploytasks_id' => $qparam,
'name' => $qparam,
'date_creation' => $qparam,
'entities_id' => $qparam,
'plugins_id' => $qparam,
'method' => $qparam,
'definition' => $qparam,
'action' => $qparam,
'retry_nb' => $qparam,
'retry_time' => $qparam,
'periodicity_type' => $qparam,
'periodicity_count' => $qparam
]
);
$stmt = $DB->prepare($query);
foreach ($tasks as $task) {
$task = get_object_vars($task);
//encode action and definition
//$action = exportArrayToDB(array(array(
// $task['action_type'] => $task['action_selection'])));
$action = exportArrayToDB($task['action']);
$definition = exportArrayToDB([[
'PluginFusioninventoryDeployPackage' => $task['package_id']]]);
$stmt->bind_param(
'ssssssssssss',
$tasks_id,
"job_".$tasks_id."_".$i,
'NOW()',
'0',
$plugins_id,
$task['method'],
$definition,
$action,
$task['retry_nb'],
$task['retry_time'],
'minutes',
'0'
);
$stmt->execute();
}
mysqli_stmt_close($stmt);
}
/**
* Get the different type of task job actions
*
* @return array
*/
static function getActionTypes() {
return [
[
'name' => __('Computers'),
'value' => 'Computer',
],
[
'name' => __('Group'),
'value' => 'Group',
],
[
'name' => __('Groups of computers', 'fusioninventory'),
'value' => 'PluginFusioninventoryDeployGroup',
]
];
}
/**
* Get actions
*
* @global object $DB
* @param array $params
* @return string in JSON format
*/
static function getActions($params) {
global $DB;
$res = '';
if (!isset($params['get'])) {
exit;
}
switch ($params['get']) {
case "type";
$res = json_encode([
'action_types' =>self::getActionTypes()
]);
break;
case "selection";
switch ($params['type']) {
case 'Computer':
$query = "SELECT id, name FROM glpi_computers";
if (isset($params['query'])) {
$like = $DB->escape($params['query']);
$query .= " WHERE name LIKE '%$like'";
}
$query .= " ORDER BY name ASC";
$query_res = $DB->query($query);
$i = 0;
while ($row = $DB->fetchArray($query_res)) {
$res['action_selections'][$i]['id'] = $row['id'];
$res['action_selections'][$i]['name'] = $row['name'];
$i++;
}
$res = json_encode($res);
break;
case 'Group':
$like = [];
if (isset($params['query'])) {
$like += ['name' => ['LIKE', '%'.$DB->escape($params['query'])]];
}
$group = new Group;
$group_datas = $group->find($like);
$i=0;
foreach ($group_datas as $group_data) {
$res['action_selections'][$i]['id'] = $group_data['id'];
$res['action_selections'][$i]['name'] = $group_data['name'];
$i++;
}
$res = json_encode($res);
break;
case 'PluginFusioninventoryDeployGroup':
$res = PluginFusioninventoryDeployGroup::getAllDatas('action_selections');
break;
}
break;
case "oneSelection":
break;
default:
$res = '';
}
return $res;
}
}

View File

@@ -0,0 +1,482 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the actions in package for deploy system.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author Walid Nouh
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage user interactions.
* @since 9.2
*/
class PluginFusioninventoryDeployUserinteraction extends PluginFusioninventoryDeployPackageItem {
public $shortname = 'userinteractions';
public $json_name = 'userinteractions';
//--------------- Events ---------------------------------------//
//Audits are all been executed successfully, just before download
const EVENT_BEFORE_DOWNLOAD = 'before';
//File download has been done, just before actions execution
const EVENT_AFTER_DOWNLOAD = 'after_download';
//Actions have been executed, deployement is finished
const EVENT_AFTER_ACTIONS = 'after';
//At least one downlod has failed
const EVENT_DOWNLOAD_FAILURE = 'after_download_failure';
//At least one action has failed
const EVENT_ACTION_FAILURE = 'after_failure';
//--------------- Responses ---------------------------------------//
//The agent notice that the job must continue
const RESPONSE_CONTINUE = 'continue';
//The agent notice that the job must be postponed
const RESPONSE_POSTPONE = 'postpone';
//The agent notice that the job must be canceled
const RESPONSE_STOP = 'stop';
//The agent recieved a malformed or non existing event
const RESPONSE_BAD_EVENT = 'error_bad_event';
//String to replace a \r\n, to avoid stripcslashes issue
const RN_TRANSFORMATION = "$#r$#n";
/**
* Get name of this type by language of the user connected
*
* @param integer $nb number of elements
* @return string name of this type
*/
static function getTypeName($nb = 0) {
return _n('User interaction',
'User interactions', $nb, 'fusioninventory');
}
/**
* Get events with name => description
* @since 9.2
* @return array
*/
function getTypes() {
return [self::EVENT_BEFORE_DOWNLOAD => __("Before download", 'fusioninventory'),
self::EVENT_AFTER_DOWNLOAD => __("After download", 'fusioninventory'),
self::EVENT_AFTER_ACTIONS => __("After actions", 'fusioninventory'),
self::EVENT_DOWNLOAD_FAILURE => __("On download failure", 'fusioninventory'),
self::EVENT_ACTION_FAILURE => __("On actions failure", 'fusioninventory')
];
}
/**
* Get an event label by it's identifier
* @since 9.2
* @return array
*/
function getLabelForAType($event) {
$events = $this->getTypes();
if (isset($events[$event])) {
return $events[$event];
} else {
return false;
}
}
/**
* Display different fields relative the check selected
*
* @param array $config
* @param array $request_data
* @param string $rand unique element id used to identify/update an element
* @param string $mode mode in use (create, edit...)
* @return boolean
*/
function displayAjaxValues($config, $request_data, $rand, $mode) {
global $CFG_GLPI;
$pfDeployPackage = new PluginFusioninventoryDeployPackage();
if (isset($request_data['packages_id'])) {
$pfDeployPackage->getFromDB($request_data['orders_id']);
} else {
$pfDeployPackage->getEmpty();
}
/*
* Get type from request params
*/
$type = null;
if ($mode === self::CREATE) {
$type = $request_data['value'];
$config_data = null;
} else {
$type = $config['type'];
$config_data = $config['data'];
}
$values = $this->getValues($type, $config_data, $mode);
if ($values === false) {
return false;
}
echo "<table class='package_item'>";
echo "<tr>";
echo "<th>{$values['name_label']}</th>";
echo "<td><input type='text' name='name' id='userinteraction_name{$rand}' value=\"{$values['name_value']}\" /></td>";
echo "</tr>";
echo "<tr>";
echo "<th>{$values['title_label']}</th>";
echo "<td><input type='text' name='title' id='userinteraction_title{$rand}' value=\"{$values['title_value']}\" />";
echo "</td>";
echo "</tr>";
echo "<tr>";
echo "<th>{$values['description_label']}</th>";
echo "<td><textarea name='text' id='userinteraction_description{$rand}' rows='5'>{$values['description_value']}</textarea>";
echo "</td>";
echo "</tr>";
echo "<tr>";
echo "<th>{$values['template_label']}</th>";
echo "<td>";
Dropdown::show('PluginFusioninventoryDeployUserinteractionTemplate',
['value' => $values['template_value'], 'name' => 'template']);
echo "</td>";
echo "</tr>";
$this->addOrSaveButton($pfDeployPackage, $mode);
echo "</table>";
}
/**
* Get fields for the check type requested
*
* @param string $type the type of check
* @param array $data fields yet defined in edit mode
* @param string $mode mode in use (create, edit...)
*
* @return string|false
*/
function getValues($type, $data, $mode) {
$values = [
'name_value' => "",
'name_label' => __('Interaction label', 'fusioninventory'),
'name_type' => "input",
'title_label' => __('Title').$this->getMandatoryMark(),
'title_value' => "",
'title_type' => "input",
'description_label' => __('Message'),
'description_type' => "text",
'description_value' => "",
'template_label'
=> PluginFusioninventoryDeployUserinteractionTemplate::getTypeName(1)
.$this->getMandatoryMark(),
'template_value' => "",
'template_type' => "dropdown",
];
if ($mode === self::EDIT) {
$values['name_value'] = isset($data['name'])?$data['name']:"";
$values['title_value'] = isset($data['title'])?$data['title']:"";
$values['description_value'] = isset($data['text'])?$data['text']:"";
$values['template_value'] = isset($data['template'])?$data['template']:"";
}
//Trick to add \r\n in the description text area
$values['description_value'] = str_replace(self::RN_TRANSFORMATION, "\r\n",
$values['description_value']);
return $values;
}
/**
* Display list of user interactions
*
* @global array $CFG_GLPI
* @param object $package PluginFusioninventoryDeployPackage instance
* @param array $data array converted of 'json' field in DB where stored checks
* @param string $rand unique element id used to identify/update an element
*/
function displayList(PluginFusioninventoryDeployPackage $package, $data, $rand) {
global $CFG_GLPI;
$interaction_types = $this->getTypes();
$package_id = $package->getID();
$canedit = $package->canUpdateContent();
$i = 0;
echo "<table class='tab_cadrehov package_item_list' id='table_userinteractions_$rand'>";
foreach ($data['jobs']['userinteractions'] as $interaction) {
echo Search::showNewLine(Search::HTML_OUTPUT, ($i%2));
if ($canedit) {
echo "<td class='control'>";
Html::showCheckbox(['name' => 'userinteractions_entries['.$i.']']);
echo "</td>";
}
//Get the audit full description (with type and return value)
//to be displayed in the UI
$text = $this->getInteractionDescription($interaction);
echo "<td>";
if ($canedit) {
echo "<a class='edit'
onclick=\"edit_subtype('userinteraction', $package_id, $rand ,this)\">";
}
echo $text;
if ($canedit) {
echo "</a>";
}
echo "</td>";
if ($canedit) {
echo "<td class='rowhandler control' title='".__('drag', 'fusioninventory').
"'><div class='drag row'></div></td>";
}
echo "</tr>";
$i++;
}
if ($canedit) {
echo "<tr><th>";
echo Html::getCheckAllAsCheckbox("userinteractionsList$rand", mt_rand());
echo "</th><th colspan='3' class='mark'></th></tr>";
}
echo "</table>";
if ($canedit) {
echo "&nbsp;&nbsp;<img src='".$CFG_GLPI["root_doc"]."/pics/arrow-left.png' alt='' />";
echo "<input type='submit' name='delete' value=\"".
__('Delete', 'fusioninventory')."\" class='submit' />";
}
}
/**
* Get of a short description of a user interaction
*
* @since 9.2
* @param interaction an array representing an interaction
* @return a short description
*/
function getInteractionDescription($interaction) {
$text = '';
if (isset($interaction['label']) && !empty($interaction['label'])) {
$text = $interaction['label'];
} else if (isset($interaction['name'])) {
$text.= $interaction['name'];
}
$text .= ' - '.$this->getLabelForAType($interaction['type']);
if ($interaction['template']) {
$text .= ' (';
$text .= Dropdown::getDropdownName('glpi_plugin_fusioninventory_deployuserinteractiontemplates',
$interaction['template']);
$text.= ')';
}
return $text;
}
/**
* Add a new item in checks of the package
*
* @param array $params list of fields with value of the check
*/
function add_item($params) {
if (!isset($params['text'])) {
$params['text'] = "";
}
if (!isset($params['template'])) {
$params['template'] = 0;
}
//prepare new check entry to insert in json
$entry = [
'name' => $params['name'],
'title' => $params['title'],
'text' => $params['text'],
'type' => $params['userinteractionstype'],
'template' => $params['template']
];
//Add to package defintion
$this->addToPackage($params['id'], $entry, 'userinteractions');
}
/**
* Save the item in checks
*
* @param array $params list of fields with value of the check
*/
function save_item($params) {
if (!isset($params['value'])) {
$params['value'] = "";
}
if (!isset($params['name'])) {
$params['name'] = "";
}
//prepare new check entry to insert in json
$entry = [
'name' => $params['name'],
'title' => $params['title'],
'text' => $params['text'],
'type' => $params['userinteractionstype'],
'template' => $params['template']
];
//update order
$this->updateOrderJson($params['id'],
$this->prepareDataToSave($params, $entry));
}
function getTypesAlreadyInUse(PluginFusioninventoryDeployPackage $package) {
$used_interactions = [];
$json = json_decode($package->fields['json'], true);
if (isset($json['jobs'][$this->json_name])
&& !empty($json['jobs'][$this->json_name])) {
foreach ($json['jobs'][$this->json_name] as $interaction) {
if (!isset($used_interactions[$interaction['type']])) {
$used_interactions[$interaction['type']] = $interaction['type'];
}
}
}
return $used_interactions;
}
/**
* Get a log message depending on an agent response
* @since 9.2
*
* @param behavior the behavior the agent must adopt for the job
* @param type the type of event that triggered the user interaction
* @param $event the button clicked by the user
* (or the what's happened in special cases, as defined in a template)
* @param user userid the user who performed the interaction
* @return string the message to be display in a taskjob log
*/
public function getLogMessage($behavior, $type, $event, $user) {
$message = self::getTypeName(1);
$message .= ': '.$this->getLabelForAType($type);
$message .= '/';
switch ($behavior) {
case self::RESPONSE_STOP:
$message .= sprintf(__('Job cancelled by the user %1$s',
'fusioninventory'), $user);
break;
case self::RESPONSE_CONTINUE:
$message .= sprintf(__('User %1$s agreed to continue the job',
'fusioninventory'), $user);
break;
case self::RESPONSE_POSTPONE:
$message .= sprintf(__('Job postponed by the user %1$s', 'fusioninventory'),
$user);
break;
case self::RESPONSE_BAD_EVENT:
$message .= __('Bad event sent to the agent', 'fusioninventory');
break;
}
$message.= ' ('.$this->getEventMessage($event).')';
return $message;
}
function getEventMessage($event = '') {
$message = __('%1$s button pressed');
switch ($event) {
case 'on_ok':
return sprintf($message, __('OK'));
case 'on_yes':
return sprintf($message, __('Yes'));
case 'on_async':
return __('Alert displayed, no input required', 'fusioninventory');
case 'on_no':
return sprintf($message, __('No'));
case 'on_retry':
return sprintf($message, __('Retry', 'fusioninventory'));
case 'on_cancel':
return sprintf($message, __('Cancel'));
case 'on_abort':
return sprintf($message, __('Abort', 'fusioninventory'));
case 'on_ignore':
return sprintf($message, __('Ignore', 'fusioninventory'));
case 'on_continue':
return sprintf($message, __('Continue'));
case 'on_timeout':
return __('Alert duration exceeded', 'fusioninventory');
case 'on_nouser':
return __('No user connected', 'fusioninventory');
case 'on_multiusers':
return __('Multiple users connected', 'fusioninventory');
}
}
}

View File

@@ -0,0 +1,724 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the actions in package for deploy system.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author Walid Nouh
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage user interactions templates.
* @since 9.2
*/
class PluginFusioninventoryDeployUserinteractionTemplate extends CommonDropdown {
/**
* The right name for this class
*
* @var string
*/
static $rightname = 'plugin_fusioninventory_userinteractiontemplate';
const ALERT_WTS = 'win32'; //Alerts for win32 platform (WTS API)
//Behaviors (to sent to the agent) :
//in two parts :
//- left part is the instruction for the agent
//- right part is the code that the agent returns to the server
//Continue a software deployment
const BEHAVIOR_CONTINUE_DEPLOY = 'continue:continue';
//Cancel a software deployment
const BEHAVIOR_STOP_DEPLOY = 'stop:stop';
//Postpone a software deployment
const BEHAVIOR_POSTPONE_DEPLOY = 'stop:postpone';
//Available buttons for Windows WTS API
const WTS_BUTTON_OK_SYNC = 'ok';
const WTS_BUTTON_OK_ASYNC = 'ok_async';
const WTS_BUTTON_OK_CANCEL = 'okcancel';
const WTS_BUTTON_YES_NO = 'yesno';
const WTS_BUTTON_ABORT_RETRY_IGNORE = 'abortretryignore';
const WTS_BUTTON_RETRY_CANCEL = 'retrycancel';
const WTS_BUTTON_YES_NO_CANCEL = 'yesnocancel';
const WTS_BUTTON_CANCEL_TRY_CONTINUE = 'canceltrycontinue';
//Icons to be displayed
const WTS_ICON_NONE = 'none';
const WTS_ICON_WARNING = 'warn';
const WTS_ICON_QUESTION = 'question';
const WTS_ICON_INFO = 'info';
const WTS_ICON_ERROR = 'error';
/**
* @see CommonGLPI::defineTabs()
**/
function defineTabs($options = []) {
$ong = [];
$this->addStandardTab(__CLASS__, $ong, $options)
->addStandardTab('Log', $ong, $options);
return $ong;
}
/**
* @see CommonGLPI::getTabNameForItem()
**/
function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) {
$tabs[1] = __('General');
$tabs[2] = _n('Behavior', 'Behaviors', 2, 'fusioninventory');
return $tabs;
}
/**
* @param $item CommonGLPI object
* @param $tabnum (default 1)
* @param $withtemplate (default 0)
**/
static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) {
global $CFG_GLPI;
if ($item->getType() == __CLASS__) {
switch ($tabnum) {
case 1 :
$item->showForm($item->fields['id']);
break;
case 2 :
$item->showBehaviors($item->fields['id']);
break;
}
}
return true;
}
/**
* Get name of this type by language of the user connected
*
* @param integer $nb number of elements
* @return string name of this type
*/
static function getTypeName($nb = 0) {
return _n('User interaction template',
'User interaction templates', $nb, 'fusioninventory');
}
/**
* Get list of supported interaction methods
*
* @since 9.2
* @return array
*/
static function getTypes() {
return [self::ALERT_WTS
=> __("Windows system alert (WTS)", 'fusioninventory')];
}
/**
* Display a dropdown with the list of alert types
*
* @since 9.2
* @param type the type of alert (if one already selected)
* @return rand
*/
function dropdownTypes($type = self::ALERT_WTS) {
return Dropdown::showFromArray('platform', self::getTypes(),
['value' => $type]);
}
/**
* Get available buttons for alerts, by interaction type
*
* @since 9.2
* @param interaction_type the type of interaction
* @return array
*/
static function getButtons($interaction_type = '') {
$interactions = [
self::ALERT_WTS => [
self::WTS_BUTTON_OK_SYNC => __('OK', 'fusioninventory'),
self::WTS_BUTTON_OK_ASYNC => __('OK (asynchronous)', 'fusioninventory'),
self::WTS_BUTTON_OK_CANCEL => __('OK - Cancel', 'fusioninventory'),
self::WTS_BUTTON_YES_NO => __('Yes - No', 'fusioninventory'),
self::WTS_BUTTON_ABORT_RETRY_IGNORE => __('OK - Abort - Retry', 'fusioninventory'),
self::WTS_BUTTON_RETRY_CANCEL => __('Retry - Cancel', 'fusioninventory'),
self::WTS_BUTTON_ABORT_RETRY_IGNORE => __('Abort - Retry - Ignore', 'fusioninventory'),
self::WTS_BUTTON_CANCEL_TRY_CONTINUE => __('Cancel - Try - Continue', 'fusioninventory'),
self::WTS_BUTTON_YES_NO_CANCEL => __('Yes - No - Cancel', 'fusioninventory')
]
];
if (isset($interactions[$interaction_type])) {
return $interactions[$interaction_type];
} else {
return false;
}
}
/**
* Display a dropdown with the list of buttons available
*
* @since 9.2
* @param type the type of button (if one already selected)
* @return rand
*/
public function dropdownButtons($button = self::WTS_BUTTON_OK_SYNC) {
return Dropdown::showFromArray('buttons',
self::getButtons(self::ALERT_WTS),
['value' => $button]);
}
/**
* Get available icons for alerts, by interaction type
*
* @since 9.2
* @param interaction_type the type of interaction
* @return array
*/
static function getIcons($interaction_type = self::ALERT_WTS) {
$icons = [
self::ALERT_WTS => [
self::WTS_ICON_NONE => __('None'),
self::WTS_ICON_WARNING => __('Warning'),
self::WTS_ICON_INFO => _n('Information', 'Informations', 1),
self::WTS_ICON_ERROR => __('Error'),
self::WTS_ICON_QUESTION => __('Question', 'fusioninventory')
]
];
if (isset($icons[$interaction_type])) {
return $icons[$interaction_type];
} else {
return false;
}
}
/**
* Display a dropdown with the list of buttons available
*
* @since 9.2
* @param type the type of button (if one already selected)
* @return rand
*/
function dropdownIcons($icon = self::WTS_ICON_NONE) {
return Dropdown::showFromArray('icon',
self::getIcons(),
['value' => $icon]);
}
/**
* Get available behaviors in case of user interactions
*
* @since 9.2
* @return array
*/
static function getBehaviors() {
return [self::BEHAVIOR_CONTINUE_DEPLOY => __('Continue job with no user interaction', 'fusioninventory'),
self::BEHAVIOR_POSTPONE_DEPLOY => __('Retry job later', 'fusioninventory'),
self::BEHAVIOR_STOP_DEPLOY => __('Cancel job', 'fusioninventory')
];
}
/**
* Display a dropdown with the list of available behaviors
*
* @since 9.2
* @param type the type of bahaviors (if one already selected)
* @return rand
*/
function dropdownBehaviors($name, $behavior = self::BEHAVIOR_CONTINUE_DEPLOY) {
return Dropdown::showFromArray($name,
self::getBehaviors(),
['value' => $behavior]);
}
/**
* Get the fields to be encoded in json
* @since 9.2
* @return an array of field names
*/
function getJsonFields() {
return array_merge($this->getMainFormFields(),
$this->getBehaviorsFields());
}
/**
* Get the fields to be encoded in json
* @since 9.2
* @return an array of field names
*/
function getMainFormFields() {
return ['platform', 'timeout', 'buttons', 'icon',
'retry_after', 'nb_max_retry'];
}
/**
* Get the fields to be encoded in json
* @since 9.2
* @return an array of field names
*/
function getBehaviorsFields() {
return ['on_timeout', 'on_nouser', 'on_multiusers', 'on_ok', 'on_no',
'on_yes', 'on_cancel', 'on_abort', 'on_retry', 'on_tryagain',
'on_ignore', 'on_continue', 'on_async'];
}
/**
* Initialize json fields
* @since 9.2
*
* @return an array of field names
*/
function initializeJsonFields($json_fields) {
foreach ($this->getJsonFields() as $field) {
if (!isset($json_fields[$field])) {
$json_fields[$field] = $this->getDefaultBehaviorForAButton($field);
}
}
return $json_fields;
}
/**
* Save form data as a json encoded array
* @since 9.2
* @param params form parameters
* @return json encoded array
*/
function saveToJson($params = []) {
$result = [];
foreach ($this->getJsonFields() as $field) {
if (isset($params[$field])) {
$result[$field] = $params[$field];
}
}
return json_encode($result);
}
/**
* Add the json template fields to package
*
* @since 9.2
* @param the input array
* @param array now containing input data + data from the template
*/
function addJsonFieldsToArray($params = []) {
$fields = json_decode($this->fields['json'], true);
foreach ($this->getJsonFields() as $field) {
if (isset($fields[$field])) {
$params[$field] = $fields[$field];
}
}
//If we deal with an asynchronous OK, then wait must be set to 0
if ($params['buttons'] == self::WTS_BUTTON_OK_ASYNC) {
$params['buttons'] = self::WTS_BUTTON_OK_SYNC;
$params['wait'] = 'no';
} else {
//Otherwise wait is 1
$params['wait'] = 'yes';
}
return $params;
}
/**
* Display an interaction template form
* @since 9.2
* @param $id id of a template to edit
* @param options POST form options
*/
function showForm($ID, $options = []) {
$this->initForm($ID);
$this->showFormHeader();
$json_data = json_decode($this->fields['json'], true);
$json_data = $this->initializeJsonFields($json_data);
echo "<tr class='tab_bg_1'>";
foreach ($this->getBehaviorsFields() as $field) {
echo Html::hidden($field, ['value' => $json_data[$field]]);
}
$rand = mt_rand();
$tplmark = $this->getAutofillMark('name', $options);
//TRANS: %1$s is a string, %2$s a second one without spaces between them : to change for RTL
echo "<td><label for='textfield_name$rand'>".sprintf(__('%1$s%2$s'), __('Name'), $tplmark) .
"</label></td>";
echo "<td>";
$objectName = autoName($this->fields["name"], "name",
(isset($options['withtemplate']) && ( $options['withtemplate']== 2)),
$this->getType(), $this->fields["entities_id"]);
Html::autocompletionTextField($this, 'name', [ 'value' => $objectName,
'rand' => $rand
]);
echo "</td>";
echo "<td>".__('Interaction format', 'fusioninventory')."</td>";
echo "<td>";
$this->dropdownTypes($json_data['platform']);
echo "</td>";
echo "</tr>";
echo "<tr class='tab_bg_1'>";
echo "<td>".__('Interaction type', 'fusioninventory')."</td>";
echo "<td>";
$this->dropdownButtons($json_data['buttons']);
echo "</td>";
echo "<td>".__('Alert icon', 'fusioninventory')."</td>";
echo "<td>";
$this->dropdownIcons($json_data['icon']);
echo "</td>";
echo "</tr>";
echo "<tr class='tab_bg_1'>";
echo "<td>".__('Retry job after', 'fusioninventory')."</td>";
echo "<td>";
$this->dropdownRetry($json_data['retry_after']);
echo "</td>";
echo "<td>".__('Maximum number of retry allowed', 'fusioninventory')."</td>";
echo "<td>";
Dropdown::showNumber('nb_max_retry',
['value' => $json_data['nb_max_retry'],
'min' => 1,
'max' => 20,
'step' => 1
]);
echo "</td>";
echo "</tr>";
echo "<tr class='tab_bg_1'>";
echo "<td>".__('Alert display timeout', 'fusioninventory')."</td>";
echo "<td>";
$this->dropdownTimeout($json_data['timeout']);
echo "</td>";
echo "<td colspan='2'></td>";
echo "</tr>";
$this->showFormButtons();
return true;
}
/**
* Dropdown for frequency (interval between 2 actions)
*
* @param $name select name
* @param $value default value (default 0)
**/
function dropdownRetry($value = 0) {
$tab[0] = __('Never');
$tab[MINUTE_TIMESTAMP] = sprintf(_n('%d minute', '%d minutes', 1), 1);
$tab[2*MINUTE_TIMESTAMP] = sprintf(_n('%d minute', '%d minutes', 2), 2);
$tab[3*MINUTE_TIMESTAMP] = sprintf(_n('%d minute', '%d minutes', 3), 3);
$tab[4*MINUTE_TIMESTAMP] = sprintf(_n('%d minute', '%d minutes', 4), 4);
// Minutes
for ($i=5; $i<60; $i+=5) {
$tab[$i*MINUTE_TIMESTAMP] = sprintf(_n('%d minute', '%d minutes', $i), $i);
}
// Heures
for ($i=1; $i<24; $i++) {
$tab[$i*HOUR_TIMESTAMP] = sprintf(_n('%d hour', '%d hours', $i), $i);
}
// Jours
$tab[DAY_TIMESTAMP] = __('Each day');
for ($i=2; $i<7; $i++) {
$tab[$i*DAY_TIMESTAMP] = sprintf(_n('%d day', '%d days', $i), $i);
}
$tab[WEEK_TIMESTAMP] = __('Each week');
$tab[MONTH_TIMESTAMP] = __('Each month');
Dropdown::showFromArray('retry_after', $tab, ['value' => $value]);
}
/**
* Dropdown for frequency (interval between 2 actions)
*
* @param $name select name
* @param $value default value (default 0)
**/
function dropdownTimeout($value = 0) {
$tab[0] = __('Never');
// Minutes
for ($i=30; $i<60; $i+=5) {
$tab[$i] = sprintf(_n('%d second', '%d seconds', $i), $i);
}
$tab[MINUTE_TIMESTAMP] = sprintf(_n('%d minute', '%d minutes', 1), 1);
$tab[2*MINUTE_TIMESTAMP] = sprintf(_n('%d minute', '%d minutes', 2), 2);
$tab[3*MINUTE_TIMESTAMP] = sprintf(_n('%d minute', '%d minutes', 3), 3);
$tab[4*MINUTE_TIMESTAMP] = sprintf(_n('%d minute', '%d minutes', 4), 4);
// Minutes
for ($i=5; $i<60; $i+=5) {
$tab[$i*MINUTE_TIMESTAMP] = sprintf(_n('%d minute', '%d minutes', $i), $i);
}
// Hours
for ($i=1; $i<13; $i++) {
$tab[$i*HOUR_TIMESTAMP] = sprintf(_n('%d hour', '%d hours', $i), $i);
}
Dropdown::showFromArray('timeout', $tab, ['value' => $value]);
}
/**
* Get all events leading to an action on a task
*
* @since 9.2
* @return array an array of event => event label
*/
public function getEvents() {
return ['on_ok' => __('Button ok', 'fusioninventory'),
'on_yes' => __('Button yes', 'fusioninventory'),
'on_continue' => __('Button continue', 'fusioninventory'),
'on_retry' => __('Button retry', 'fusioninventory'),
'on_tryagain' => __('Button try', 'fusioninventory'),
'on_no' => __('Button no', 'fusioninventory'),
'on_cancel' => __('Button cancel', 'fusioninventory'),
'on_abort' => __('Button abort', 'fusioninventory'),
'on_ignore' => __('Button ignore', 'fusioninventory'),
'on_nouser' => __('No active session', 'fusioninventory'),
'on_timeout' => __('Alert timeout exceeded', 'fusioninventory'),
'on_multiusers' => __('Several active sessions', 'fusioninventory')
];
}
/**
* Get the behaviors to define for an agent to correctly handle the interaction
*
* @since 9.2
* @param $param the button selected in the interaction template form
* @return array an array of needed interaction behaviors
*/
public function getBehaviorsToDisplay($button) {
$display = ['on_timeout', 'on_nouser', 'on_multiusers'];
switch ($button) {
case self::WTS_BUTTON_OK_SYNC:
case self::WTS_BUTTON_OK_ASYNC:
$display[] = 'on_ok';
break;
case self::WTS_BUTTON_YES_NO:
$display[] = 'on_yes';
$display[] = 'on_no';
break;
case self::WTS_BUTTON_YES_NO_CANCEL:
$display[] = 'on_yes';
$display[] = 'on_no';
$display[] = 'on_cancel';
break;
case self::WTS_BUTTON_OK_CANCEL:
$display[] = 'on_ok';
$display[] = 'on_cancel';
break;
case self::WTS_BUTTON_ABORT_RETRY_IGNORE:
$display[] = 'on_abort';
$display[] = 'on_retry';
$display[] = 'on_ignore';
break;
case self::WTS_BUTTON_RETRY_CANCEL:
$display[] = 'on_retry';
$display[] = 'on_cancel';
break;
case self::WTS_BUTTON_CANCEL_TRY_CONTINUE:
$display[] = 'on_tryagain';
$display[] = 'on_cancel';
$display[] = 'on_continue';
break;
}
return $display;
}
/**
* Get the default behavior for a button
* @since 9.2
* @param string $button the button for which the default behavior is request
* @return string the behavior
*/
public function getDefaultBehaviorForAButton($button) {
$behavior = '';
switch ($button) {
case 'on_yes':
case 'on_ok':
case 'on_multiusers':
case 'on_timeout':
case 'on_nouser':
$behavior = self::BEHAVIOR_CONTINUE_DEPLOY;
break;
case 'on_no':
case 'on_cancel':
case 'on_abort':
$behavior = self::BEHAVIOR_STOP_DEPLOY;
break;
case 'on_retry':
case 'on_ignore':
case 'on_tryagain':
$behavior = self::BEHAVIOR_POSTPONE_DEPLOY;
break;
}
return $behavior;
}
/**
* Show behaviors form
*
* @since 9.2
* @param ID the template's ID
*/
public function showBehaviors($ID) {
$json_data = json_decode($this->fields['json'], true);
$json_data = $this->initializeJsonFields($json_data);
$this->initForm($ID);
$this->showFormHeader();
echo "<tr class='tab_bg_1'>";
echo "<th colspan='4'>".__('Behaviors', 'fusioninventory')."</th>";
echo "</tr>";
foreach ($this->getMainFormFields() as $field) {
echo Html::hidden($field, ['value' => $json_data[$field]]);
}
foreach ($this->getEvents() as $event => $label) {
if (in_array($event,
$this->getBehaviorsToDisplay($json_data['buttons']))) {
echo "<tr class='tab_bg_1'>";
echo "<td>$label</td>";
echo "<td>";
if (empty($json_data[$event])) {
$value = $this->getDefaultBehaviorForAButton($event);
} else {
$value = $json_data[$event];
}
$this->dropdownBehaviors($event, $value);
echo "</td>";
echo "</tr>";
} else {
echo Html::hidden($event, $json_data[$event]);
}
}
$this->showFormButtons();
return true;
}
public function prepareInputForAdd($input) {
//Save params as a json array, ready to be saved in db
$input['json'] = $this->saveToJson($input);
return $input;
}
public function prepareInputForUpdate($input) {
return $this->prepareInputForAdd($input);
}
/**
* Get temlate values as an array
* @since 9.2
* @return array the template values as an array
*/
public function getValues() {
return json_decode($this->fields['json'], true);
}
}

View File

@@ -0,0 +1,204 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the general display in plugin.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author Vincent Mazzoni
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the general display in plugin.
*/
class PluginFusioninventoryDisplay extends CommonDBTM {
/**
* Display static progress bar (used for SNMP cartridge state)
*
* @param integer $percentage
* @param string $message
* @param string $order
* @param integer $width
* @param integer $height
*/
static function bar($percentage, $message = '', $order = '', $width = '400', $height = '20') {
if ((!empty($percentage)) AND ($percentage < 0)) {
$percentage = "";
} else if ((!empty($percentage)) AND ($percentage > 100)) {
$percentage = "";
}
echo "<div>
<table class='tab_cadre' width='".$width."'>
<tr>
<td align='center' width='".$width."'>";
if ((!empty($percentage))
|| ($percentage == "0")) {
echo $percentage."% ".$message;
}
echo "</td>
</tr>
<tr>
<td>
<table cellpadding='0' cellspacing='0'>
<tr>
<td width='".$width."' height='0' colspan='2'></td>
</tr>
<tr>";
if (empty($percentage)) {
echo "<td></td>";
} else {
echo " <td bgcolor='";
if ($order!= '') {
if ($percentage > 80) {
echo "red";
} else if ($percentage > 60) {
echo "orange";
} else {
echo "green";
}
} else {
if ($percentage < 20) {
echo "red";
} else if ($percentage < 40) {
echo "orange";
} else {
echo "green";
}
}
if ($percentage == 0) {
echo "' height='".$height."' width='1'>&nbsp;</td>";
} else {
echo "' height='".$height."' width='".(($width * $percentage) / 100)."'>&nbsp;</td>";
}
}
if ($percentage == 0) {
echo " <td height='".$height."' width='1'></td>";
} else {
echo " <td height='".$height."' width='".
($width - (($width * $percentage) / 100))."'></td>";
}
echo " </tr>
</table>
</td>
</tr>
</table>
</div>";
}
/**
* Disable debug mode to not see php errors
*/
static function disableDebug() {
error_reporting(0);
set_error_handler(['PluginFusioninventoryDisplay', 'error_handler']);
}
/**
* Enable debug mode if user is in debug mode
**/
static function reenableusemode() {
Toolbox::setDebugMode();
}
/**
* When debug is disabled, we transfer every errors in this emtpy function.
*
* @param integer $errno
* @param string $errstr
* @param string $errfile
* @param integer $errline
*/
static function error_handler($errno, $errstr, $errfile, $errline) {
}
/**
* Display progress bar
*
* @global array $CFG_GLPI
* @param integer $width
* @param integer $percent
* @param array $options
* @return string
*/
static function getProgressBar($width, $percent, $options = []) {
global $CFG_GLPI;
$param = [];
$param['title']=__('Progress', 'fusioninventory');
$param['simple']=false;
$param['forcepadding']=false;
if (is_array($options) && count($options)) {
foreach ($options as $key => $val) {
$param[$key]=$val;
}
}
$percentwidth=floor($percent*$width/100);
$output="<div class='center'><table class='tab_cadre' width='".($width+20)."px'>";
if (!$param['simple']) {
$output.="<tr><th class='center'>".$param['title']."&nbsp;".$percent."%</th></tr>";
}
$output.="<tr><td>
<table><tr><td class='center' style='background:url(".$CFG_GLPI["root_doc"].
"/pics/loader.png) repeat-x;' width='.$percentwidth' height='12'>";
if ($param['simple']) {
$output.=$percent."%";
} else {
$output.='&nbsp;';
}
$output.="</td></tr></table></td>";
$output.="</tr></table>";
$output.="</div>";
return $output;
}
}

View File

@@ -0,0 +1,281 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the entity configuration.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the entity configuration.
*/
class PluginFusioninventoryEntity extends CommonDBTM {
/**
* The right name for this class
*
* @var string
*/
static $rightname = 'entity';
/**
* Get name of this type by language of the user connected
*
* @param integer $nb number of elements
* @return string name of this type
*/
static function getTypeName($nb = 0) {
return Entity::getTypeName(1);
}
/**
* Get the tab name used for item
*
* @param object $item the item object
* @param integer $withtemplate 1 if is a template form
* @return string name of the tab
*/
function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) {
if ($item->fields['id'] > -1) {
if (Session::haveRight("config", READ)) {
return self::createTabEntry('Fusioninventory');
}
}
return '';
}
/**
* Display the content of the tab
*
* @param object $item
* @param integer $tabnum number of the tab to display
* @param integer $withtemplate 1 if is a template form
* @return boolean
*/
static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) {
if ($item->fields['id'] > -1) {
$pmEntity = new PluginFusioninventoryEntity();
$pmEntity->showForm($item->fields['id']);
return true;
}
return false;
}
/**
* Display form
*
* @global array $CFG_GLPI
* @param integer $entities_id
* @param array $options
* @return true
*/
function showForm($entities_id, $options = []) {
global $CFG_GLPI;
$a_configs = $this->find(['entities_id' => $entities_id], [], 1);
$id = 0;
if (count($a_configs) == '1') {
$a_config = current($a_configs);
$id = $a_config['id'];
}
$this->initForm($id, $options);
$this->showFormHeader($options);
echo "<tr>";
echo "<td colspan='2'>";
echo __('Model for automatic computers transfer in an other entity', 'fusioninventory').
"&nbsp:";
echo "</td>";
echo "<td colspan='2'>";
$params = [
'name' => 'transfers_id_auto',
'value' => $this->fields['transfers_id_auto'],
'emptylabel' => __('No automatic transfer')
];
if ($entities_id > 0) {
$params['toadd'] = ['-1' => __('Inheritance of the parent entity')];
}
Dropdown::show('Transfer', $params);
echo Html::hidden('entities_id', ['value' => $entities_id]);
echo "</td>";
echo "</tr>";
// Inheritance
if ($this->fields['transfers_id_auto'] == '-1') {
echo "<tr class='tab_bg_1'>";
// if ($this->fields['transfers_id_auto'] == '-1') {
echo "<td colspan='2'>";
echo "</td>";
echo "<td colspan='2' class='green'>";
echo __('Inheritance of the parent entity')."&nbsp;:&nbsp;";
$val = $this->getValueAncestor('transfers_id_auto', $entities_id);
if ($val == 0) {
echo __('No automatic transfer');
} else {
echo Dropdown::getDropdownName('glpi_transfers', $val);
}
echo "</td>";
// } else {
// echo "<td colspan='4'>";
// echo "</td>";
// }
echo "</tr>";
}
echo "<tr>";
echo "<td colspan='2'>";
$value = $this->fields["agent_base_url"];
$inheritedValue = $this->getValueAncestor('agent_base_url', $entities_id);
echo __('Service URL', 'fusioninventory').'&nbsp;';
Html::showToolTip('ex: http://192.168.20.1/glpi');
echo " : ";
echo "</td>";
echo "<td colspan='2'>";
if (empty($value) && $entities_id == 0) {
echo "<img src=\"".$CFG_GLPI["root_doc"]."/pics/warning.png\" width='20' height='20' alt=\"warning\"> ";
}
echo "<input type='text' name='agent_base_url' value='".$value."' size='30'/>";
echo "</td>";
echo "</tr>";
if (empty($value) && !empty($inheritedValue)) {
echo "<tr class='tab_bg_1'>";
echo "<td colspan='2'></td>";
echo "<td colspan='2' class='green'>";
echo __('Inheritance of the parent entity')."&nbsp;:&nbsp;".$inheritedValue;
echo "</td>";
echo "</tr>";
}
$this->showFormButtons($options);
return true;
}
/**
* Get value of config
*
* @global object $DB
* @param string $name field name
* @param integer $entities_id
* @return string value of field
*/
function getValueAncestor($name, $entities_id) {
global $DB;
$entities_ancestors = getAncestorsOf("glpi_entities", $entities_id);
$where = '';
if ($name == 'agent_base_url') {
$where = "AND `".$name."` != ''";
}
$nbentities = count($entities_ancestors);
for ($i=0; $i<$nbentities; $i++) {
$entity = array_pop($entities_ancestors);
$query = "SELECT * FROM `".$this->getTable()."`
WHERE `entities_id`='".$entity."'
AND `".$name."` IS NOT NULL
".$where."
LIMIT 1";
$result = $DB->query($query);
if ($DB->numrows($result) != 0) {
$data = $DB->fetchAssoc($result);
return $data[$name];
}
}
$this->getFromDB(1);
return $this->getField($name);
}
/**
* Get the value (of this entity or parent entity or in general config
*
* @global object $DB
* @param string $name field name
* @param integer $entities_id
* @return string value of this field
*/
function getValue($name, $entities_id) {
global $DB;
$where = '';
if ($name == 'agent_base_url') {
$where = "AND `".$name."` != ''";
}
$query = "SELECT `".$name."` FROM `".$this->getTable()."`
WHERE `entities_id`='".$entities_id."'
AND `".$name."` IS NOT NULL
".$where."
LIMIT 1";
$result = $DB->query($query);
if ($DB->numrows($result) > 0) {
$data = $DB->fetchAssoc($result);
return $data[$name];
}
return $this->getValueAncestor($name, $entities_id);
}
/**
* Initialize a field when get empty item (default values)
*/
function post_getEmpty() {
$this->fields['transfers_id_auto'] = -1;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,206 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the list of devices ignored on import.
* Mean when device go in import rules, rules say "ignore import this device
* because I don't want it"
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the list of devices ignored on import.
* Mean when device go in import rules, rules say "ignore import this device
* because I don't want it"
*/
class PluginFusioninventoryIgnoredimportdevice extends CommonDBTM {
/**
* The right name for this class
*
* @var string
*/
static $rightname = 'plugin_fusioninventory_ignoredimportdevice';
/**
* Get name of this type by language of the user connected
*
* @param integer $nb number of elements
* @return string name of this type
*/
static function getTypeName($nb = 0) {
return __('Equipment ignored on import', 'fusioninventory');
}
/**
* Get search function for the class
*
* @return array
*/
function rawSearchOptions() {
$tab = [];
$tab[] = [
'id' => 'common',
'name' => __('Agent', 'fusioninventory')
];
$tab[] = [
'id' => '1',
'table' => $this->getTable(),
'field' => 'name',
'name' => __('Name'),
'massiveaction' => false,
];
$tab[] = [
'id' => '2',
'table' => 'glpi_rules',
'field' => 'id',
'name' => __('Rule name', 'fusioninventory'),
'datatype' => 'itemlink',
'itemlink_type' => 'PluginFusioninventoryInventoryRuleImport',
'massiveaction' => false,
];
$tab[] = [
'id' => '3',
'table' => $this->getTable(),
'field' => 'date',
'name' => _n('Date', 'Dates', 1),
'datatype' => 'datetime',
'massiveaction' => false,
];
$tab[] = [
'id' => '4',
'table' => $this->getTable(),
'field' => 'itemtype',
'name' => __('Item type'),
'massiveaction' => false,
'datatype' => 'itemtypename',
];
$tab[] = [
'id' => '5',
'table' => 'glpi_entities',
'field' => 'completename',
'name' => Entity::getTypeName(1),
'massiveaction' => false,
'datatype' => 'dropdown',
];
$tab[] = [
'id' => '6',
'table' => $this->getTable(),
'field' => 'serial',
'name' => __('Serial number'),
'datatype' => 'string',
'massiveaction' => false,
];
$tab[] = [
'id' => '7',
'table' => $this->getTable(),
'field' => 'uuid',
'name' => __('UUID'),
'datatype' => 'string',
'massiveaction' => false,
];
$tab[] = [
'id' => '8',
'table' => $this->getTable(),
'field' => 'ip',
'name' => __('IP'),
'datatype' => 'string',
'massiveaction' => false,
];
$tab[] = [
'id' => '9',
'table' => $this->getTable(),
'field' => 'mac',
'name' => __('MAC'),
'datatype' => 'string',
'massiveaction' => false,
];
$tab[] = [
'id' => '10',
'table' => $this->getTable(),
'field' => 'method',
'name' => __('Module', 'fusioninventory'),
'datatype' => 'string',
'massiveaction' => false,
];
$tab[] = [
'id' => '11',
'table' => 'glpi_plugin_fusioninventory_agents',
'field' => 'name',
'name' => __('Agent', 'fusioninventory'),
'datatype' => 'itemlink',
'massiveaction' => false,
'itemlink_type' => 'PluginFusioninventoryAgent',
];
return $tab;
}
/**
* Get search parameters for default search / display list
*
* @return array
*/
static function getDefaultSearchRequest() {
return ['sort' => 3,
'order' => 'DESC'];
}
}

View File

@@ -0,0 +1,233 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the extended information of a computer.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Common inventory methods (local or snmp)
*/
class PluginFusioninventoryInventoryCommon extends CommonDBTM {
/**
* Import firmwares
* @since 9.2+2.0
*
* @param string $itemtype the itemtype to be inventoried
* @param array $a_inventory Inventory data
* @param integer Network equipment id
*
* @return void
*/
function importFirmwares($itemtype, $a_inventory, $items_id, $no_history = false) {
if (!isset($a_inventory['firmwares']) || !count($a_inventory['firmwares'])) {
return;
}
$ftype = new DeviceFirmwareType();
$ftype->getFromDBByCrit(['name' => 'Firmware']);
$default_type = $ftype->getId();
foreach ($a_inventory['firmwares'] as $a_firmware) {
$firmware = new DeviceFirmware();
$input = [
'designation' => $a_firmware['name'],
'version' => $a_firmware['version'],
'devicefirmwaretypes_id' => isset($a_firmware['devicefirmwaretypes_id']) ? $a_firmware['devicefirmwaretypes_id'] : $default_type,
'manufacturers_id' => $a_firmware['manufacturers_id']
];
//Check if firmware exists
$firmware->getFromDBByCrit($input);
if ($firmware->isNewItem()) {
$input['entities_id'] = $_SESSION['glpiactive_entity'];
//firmware does not exists yet, create it
$fid = $firmware->add($input);
} else {
$fid = $firmware->getID();
}
$relation = new Item_DeviceFirmware();
$input = [
'itemtype' => $itemtype,
'items_id' => $items_id,
'devicefirmwares_id' => $fid
];
//Check if firmware relation with equipment
$relation->getFromDBByCrit($input);
if ($relation->isNewItem()) {
$input = $input + [
'is_dynamic' => 1,
'entities_id' => $_SESSION['glpiactive_entity']
];
$relation->add($input, [], !$no_history);
}
}
}
/**
* Import ports
*
* @param array $a_inventory
* @param integer $items_id
*/
function importPorts($itemtype, $a_inventory, $items_id, $no_history = false) {
$networkPort = new NetworkPort();
$pfNetworkPort = new PluginFusioninventoryNetworkPort();
$networkports_id = 0;
foreach ($a_inventory['networkport'] as $a_port) {
$params = [
'itemtype' => $itemtype,
'items_id' => $items_id,
'instantiation_type' => 'NetworkPortEthernet',
'logical_number' => $a_port['logical_number']
];
$new = false;
if ($networkPort->getFromDBByCrit($params) == false) {
//The port has not been found.
//We then try to check if the port exists with another
//logical_number but the same mac
//The case has been found on SHARP printers
$params = ['itemtype' => $itemtype,
'items_id' => $items_id,
'instantiation_type' => 'NetworkPortEthernet',
'mac' => $a_port['mac']];
if ($networkPort->getFromDBByCrit($params) == false) {
$new = true;
}
}
if ($new) {
// Add port
$a_port['instantiation_type'] = 'NetworkPortEthernet';
$a_port['items_id'] = $items_id;
$a_port['itemtype'] = $itemtype;
$networkports_id = $networkPort->add($a_port, [], !$no_history);
unset($a_port['id']);
$a_pfnetworkport_DB = current($pfNetworkPort->find(
['networkports_id' => $networkports_id], [], 1));
$a_port['id'] = $a_pfnetworkport_DB['id'];
$pfNetworkPort->update($a_port);
} else {
// Update port
$networkports_id = $networkPort->fields['id'];
$a_port['id'] = $networkPort->fields['id'];
$networkPort->update($a_port);
unset($a_port['id']);
// Check if pfnetworkport exist.
$a_pfnetworkport_DB = current($pfNetworkPort->find(
['networkports_id' => $networkports_id], [], 1));
$a_port['networkports_id'] = $networkports_id;
if (isset($a_pfnetworkport_DB['id'])) {
$a_port['id'] = $a_pfnetworkport_DB['id'];
$pfNetworkPort->update($a_port);
} else {
$a_port['networkports_id'] = $networkports_id;
$pfNetworkPort->add($a_port);
}
}
}
}
/**
* Import firmwares
* @since 9.2+2.0
*
* @param string $itemtype the itemtype to be inventoried
* @param array $a_inventory Inventory data
* @param integer Network equipment id
*
* @return void
*/
function importSimcards($itemtype, $a_inventory, $items_id, $no_history = false) {
if (!isset($a_inventory['simcards']) || !count($a_inventory['simcards'])) {
return;
}
$simcard = new DeviceSimcard();
foreach ($a_inventory['simcards'] as $a_simcard) {
$relation = new Item_DeviceSimcard();
$input = [
'designation' => 'Simcard',
];
//Check if the simcard already exists
$simcard->getFromDBByCrit($input);
if ($simcard->isNewItem()) {
$input['entities_id'] = $_SESSION['glpiactive_entity'];
//firmware does not exists yet, create it
$simcards_id = $simcard->add($input);
} else {
$simcards_id = $simcard->getID();
}
//Import Item_DeviceSimcard
$input = [
'serial' => $a_simcard['serial'],
'msin' => $a_simcard['msin'],
'devicesimcards_id' => $simcards_id
];
//Check if there's already a connection between the simcard and an asset
$relation->getFromDBByCrit($input);
$input['itemtype'] = $itemtype;
$input['items_id'] = $items_id;
$input['is_dynamic'] = 1;
$input['entities_id'] = $_SESSION['glpiactive_entity'];
if ($relation->isNewItem()) {
$relations_id = $relation->add($input, [], !$no_history);
} else {
$input['id'] = $relation->getID();
$relations_id = $relation->update($input);
}
}
}
}

View File

@@ -0,0 +1,400 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the fields values to backend on computer
* inventory. If have serial xxxxx, so delete it.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the fields values to backend on computer inventory. If have serial
* xxxxx, so delete it.
*/
class PluginFusioninventoryInventoryComputerBlacklist extends CommonDBTM {
/**
* The right name for this class
*
* @var string
*/
static $rightname = 'plugin_fusioninventory_blacklist';
/**
* Get name of this type by language of the user connected
*
* @param integer $nb number of elements
* @return string name of this type
*/
static function getTypeName($nb = 0) {
return _n('Blacklist', 'Blacklists', $nb);
}
/**
* Get search function for the class
*
* @return array
*/
function rawSearchOptions() {
$tab = [];
$tab[] = [
'id' => 'common',
'name' => __('BlackList')
];
$tab[] = [
'id' => '1',
'table' => $this->getTable(),
'field' => 'value',
'name' => __('blacklisted value', 'fusioninventory'),
'autocomplete' => true,
];
$tab[] = [
'id' => '2',
'table' => 'glpi_plugin_fusioninventory_inventorycomputercriterias',
'field' => 'name',
'linkfield' => 'plugin_fusioninventory_criterium_id',
'name' => __('Type'),
'datatype' => 'dropdown',
'itemlink_type' => 'PluginFusioninventoryInventoryComputerCriteria',
];
return $tab;
}
/**
* Define tabs to display on form page
*
* @param array $options
* @return array containing the tabs name
*/
function defineTabs($options = []) {
$pfInventoryComputerCriteria = new PluginFusioninventoryInventoryComputerCriteria();
$ong = [];
$i = 1;
$fields = $pfInventoryComputerCriteria->find();
foreach ($fields as $data) {
$ong[$i] = $data['name'];
$i++;
}
return $ong;
}
/**
* Display form for blacklist
*
* @param integer $items_id
* @param array $options
* @return true
*/
function showForm($items_id, $options = []) {
if ($items_id!='') {
$this->getFromDB($items_id);
} else {
$this->getEmpty();
}
$this->showFormHeader();
echo "<tr class='tab_bg_1'>";
echo "<td>".__('blacklisted value', 'fusioninventory')."</td>";
echo "<td>";
Html::autocompletionTextField($this, 'value');
echo "</td>";
echo "<td>".__('Type')."</td>";
echo "<td>";
Dropdown::show('PluginFusioninventoryInventoryComputerCriteria',
['name' => 'plugin_fusioninventory_criterium_id',
'value' => $this->fields['plugin_fusioninventory_criterium_id']]);
echo "</td>";
echo "</tr>";
$this->showFormButtons();
return true;
}
/**
* Remove fields in inventory XML from agent which are blacklisted
*
* @param array $a_computerinventory
* @return array
*/
function cleanBlacklist($a_computerinventory) {
$pfInventoryComputerCriteria = new PluginFusioninventoryInventoryComputerCriteria();
$fields = $pfInventoryComputerCriteria->find();
foreach ($fields as $id=>$data) {
switch ($data['comment']) {
case 'ssn':
$a_blacklist = $this->find(['plugin_fusioninventory_criterium_id' => $id]);
foreach ($a_blacklist as $blacklist_id=>$blacklist_data) {
if ((isset($a_computerinventory['Computer']['serial']))
&& (strtolower($a_computerinventory['Computer']['serial'])
== strtolower($blacklist_data['value']))) {
$a_computerinventory['Computer']['serial'] = "";
}
if (((!isset($a_computerinventory['Computer']['serial']))
|| ($a_computerinventory['Computer']['serial'] == ""))
&& isset($a_computerinventory['Computer']['mserial'])) {
$a_computerinventory['Computer']['serial'] = $a_computerinventory['Computer']['mserial'];
foreach ($a_blacklist as $blacklist_data2) {
if ($a_computerinventory['Computer']['serial'] == $blacklist_data2['value']) {
$a_computerinventory['Computer']['serial'] = "";
}
}
}
if (isset($a_computerinventory['monitor'])) {
foreach ($a_computerinventory['monitor'] as $num_m=>$data_m) {
if ((isset($data_m['serial']))
&& (strtolower($data_m['serial'])
== strtolower($blacklist_data['value']))) {
$a_computerinventory['monitor'][$num_m]['serial'] = "";
}
}
}
}
break;
case 'uuid':
$a_blacklist = $this->find(['plugin_fusioninventory_criterium_id' => $id]);
foreach ($a_blacklist as $blacklist_id=>$blacklist_data) {
if ((isset($a_computerinventory['Computer']['uuid']))
&& (strtolower($a_computerinventory['Computer']['uuid'])
== strtolower($blacklist_data['value']))) {
$a_computerinventory['Computer']['uuid'] = "";
}
}
break;
case 'macAddress':
$a_blacklist = $this->find(['plugin_fusioninventory_criterium_id' => $id]);
foreach ($a_blacklist as $blacklist_id=>$blacklist_data) {
if (isset($a_computerinventory['networkport'])) {
foreach ($a_computerinventory['networkport'] as $key=>$network) {
if ((isset($network['mac']))
AND (strtolower($network['mac'])
== strtolower($blacklist_data['value']))) {
$a_computerinventory['networkport'][$key]['mac'] = "";
}
}
}
}
break;
case 'winProdKey':
$a_blacklist = $this->find(['plugin_fusioninventory_criterium_id' => $id]);
foreach ($a_blacklist as $blacklist_id=>$blacklist_data) {
if ((isset($a_computerinventory['fusioninventorycomputer']['items_operatingsystems_id']['license_number']))
&& (strtolower($a_computerinventory['fusioninventorycomputer']['items_operatingsystems_id']['license_number'])
== strtolower($blacklist_data['value']))) {
$a_computerinventory['fusioninventorycomputer']['items_operatingsystems_id']['license_number'] = "";
}
}
break;
case 'smodel':
$a_blacklist = $this->find(['plugin_fusioninventory_criterium_id' => $id]);
foreach ($a_blacklist as $blacklist_id=>$blacklist_data) {
if ((isset($a_computerinventory['Computer']['computermodels_id']))
&& (strtolower($a_computerinventory['Computer']['computermodels_id'])
== strtolower($blacklist_data['value']))) {
$a_computerinventory['Computer']['computermodels_id'] = "";
}
}
if (isset($a_computerinventory['Computer'])) {
if ($a_computerinventory['Computer']['computermodels_id'] == "") {
if (isset($a_computerinventory['Computer']['mmodel'])) {
$a_computerinventory['Computer']['computermodels_id'] =
$a_computerinventory['Computer']['mmodel'];
foreach ($a_blacklist as $blacklist_id=>$blacklist_data) {
if ((isset($a_computerinventory['Computer']['computermodels_id']))
&& (strtolower($a_computerinventory['Computer']['computermodels_id'])
== strtolower($blacklist_data['value']))) {
$a_computerinventory['Computer']['computermodels_id'] = "";
break;
}
}
}
}
}
break;
case 'storagesSerial':
$a_blacklist = $this->find(['plugin_fusioninventory_criterium_id' => $id]);
// foreach ($a_blacklist as $blacklist_id=>$blacklist_data) {
// if (isset($arrayinventory['CONTENT']['STORAGES'])) {
// foreach ($arrayinventory['CONTENT']['STORAGES'] as $key=>$storage) {
// if ((isset($storage['SERIALNUMBER']))
// AND ($storage['SERIALNUMBER'] == $blacklist_data['value'])) {
// $arrayinventory['CONTENT']['STORAGES'][$key]['SERIALNUMBER'] = "";
// }
// }
// }
// }
break;
case 'drivesSerial':
$a_blacklist = $this->find(['plugin_fusioninventory_criterium_id' => $id]);
// foreach ($a_blacklist as $blacklist_id=>$blacklist_data) {
// if (isset($arrayinventory['CONTENT']['DRIVES'])) {
// foreach ($arrayinventory['CONTENT']['DRIVES'] as $key=>$drive) {
// if ((isset($drive['SERIAL']))
// AND ($drive['SERIAL'] == $blacklist_data['value'])) {
// $arrayinventory['CONTENT']['DRIVES'][$key]['SERIAL'] = "";
// }
// }
// }
// }
break;
case 'assetTag':
$a_blacklist = $this->find(['plugin_fusioninventory_criterium_id' => $id]);
// foreach ($a_blacklist as $blacklist_id=>$blacklist_data) {
// if ((isset($arrayinventory['CONTENT']['BIOS']['ASSETTAG']))
// AND ($arrayinventory['CONTENT']['BIOS']['ASSETTAG'] ==
// $blacklist_data['value'])) {
// $arrayinventory['CONTENT']['BIOS']['ASSETTAG'] = "";
// }
// }
break;
case 'manufacturer':
$a_blacklist = $this->find(['plugin_fusioninventory_criterium_id' => $id]);
foreach ($a_blacklist as $blacklist_id=>$blacklist_data) {
if ((isset($a_computerinventory['Computer']['manufacturers_id']))
&& (strtolower($a_computerinventory['Computer']['manufacturers_id'])
== strtolower($blacklist_data['value']))) {
$a_computerinventory['Computer']['manufacturers_id'] = "";
break;
}
}
if (isset($a_computerinventory['Computer'])) {
if ($a_computerinventory['Computer']['manufacturers_id'] == "") {
if (isset($a_computerinventory['Computer']['mmanufacturer'])) {
$a_computerinventory['Computer']['manufacturers_id'] =
$a_computerinventory['Computer']['mmanufacturer'];
foreach ($a_blacklist as $blacklist_id=>$blacklist_data) {
if ((isset($a_computerinventory['Computer']['manufacturers_id']))
&& (strtolower($a_computerinventory['Computer']['manufacturers_id'])
== strtolower($blacklist_data['value']))) {
$a_computerinventory['Computer']['manufacturers_id'] = "";
break;
}
}
}
}
if ($a_computerinventory['Computer']['manufacturers_id'] == "") {
if (isset($a_computerinventory['Computer']['bmanufacturer'])) {
$a_computerinventory['Computer']['manufacturers_id'] =
$a_computerinventory['Computer']['bmanufacturer'];
foreach ($a_blacklist as $blacklist_id=>$blacklist_data) {
if ((isset($a_computerinventory['Computer']['manufacturers_id']))
&& (strtolower($a_computerinventory['Computer']['manufacturers_id'])
== strtolower($blacklist_data['value']))) {
$a_computerinventory['Computer']['manufacturers_id'] = "";
break;
}
}
}
}
}
break;
case 'IP':
$a_blacklist = $this->find(['plugin_fusioninventory_criterium_id' => $id]);
foreach ($a_blacklist as $blacklist_id=>$blacklist_data) {
if (isset($a_computerinventory['networkport'])) {
foreach ($a_computerinventory['networkport'] as $key=>$netport_data) {
foreach ($netport_data['ipaddress'] as $num_ip=>$ip) {
if ($ip == $blacklist_data['value']) {
unset($a_computerinventory['networkport'][$key]['ipaddress'][$num_ip]);
}
}
}
}
}
break;
}
}
// Blacklist mac of "miniport*" for windows because have same mac as principal network ports
if (isset($a_computerinventory['networkport'])) {
foreach ($a_computerinventory['networkport'] as $key=>$network) {
if ((isset($network['name']))
AND (strtolower($network['name']) =="miniport d'ordonnancement de paquets")) {
$a_computerinventory['networkport'][$key]['mac'] = "";
}
}
}
return $a_computerinventory;
}
}

View File

@@ -0,0 +1,334 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the extended information of a computer.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the extended information of a computer.
*/
class PluginFusioninventoryInventoryComputerComputer extends PluginFusioninventoryItem {
/**
* The right name for this class
*
* @var string
*/
static $rightname = 'computer';
public $itemtype = 'Computer';
/**
* Get name of this type by language of the user connected
*
* @param integer $nb number of elements
* @return string name of this type
*/
static function getTypeName($nb = 0) {
return "";
}
/**
* Display information about computer (bios, last contact...)
*
* @global array $CFG_GLPI
* @param object $item
* @return true
*/
static function showAgentInfo($item) {
global $CFG_GLPI;
$pfInventoryComputerComputer = new PluginFusioninventoryInventoryComputerComputer();
$a_computerextend = current($pfInventoryComputerComputer->find(['computers_id' => $item->getID()], [], 1));
if (empty($a_computerextend)) {
return;
}
echo '<table class="tab_glpi" width="100%">';
$pfAgent = new PluginFusioninventoryAgent();
$pfAgent->showInfoForComputer($item);
if ($a_computerextend['bios_date'] != '') {
echo '<tr class="tab_bg_1">';
echo '<td>'.__('BIOS date', 'fusioninventory').'</td>';
echo '<td>'.Html::convDate($a_computerextend['bios_date']).'</td>';
echo '</tr>';
}
if ($a_computerextend['bios_version'] != '') {
echo '<tr class="tab_bg_1">';
echo '<td>'.__('BIOS version', 'fusioninventory').'</td>';
echo '<td>'.$a_computerextend['bios_version'].'</td>';
echo '</tr>';
}
if ($a_computerextend['bios_manufacturers_id'] > 0) {
echo '<tr class="tab_bg_1">';
echo '<td>'.Manufacturer::getTypeName(1).'&nbsp;:</td>';
echo '<td>';
echo Dropdown::getDropdownName("glpi_manufacturers",
$a_computerextend['bios_manufacturers_id']);
echo '</td>';
echo '</tr>';
}
if ($a_computerextend['operatingsystem_installationdate'] != '') {
echo '<tr class="tab_bg_1">';
echo "<td>".OperatingSystem::getTypeName(1)." - ".__('Installation')." (".
strtolower(_n('Date', 'Dates', 1)).")</td>";
echo '<td>'.Html::convDate($a_computerextend['operatingsystem_installationdate']).'</td>';
echo '</tr>';
}
if ($a_computerextend['winowner'] != '') {
echo '<tr class="tab_bg_1">';
echo '<td>'.__('Owner', 'fusioninventory').'</td>';
echo '<td>'.$a_computerextend['winowner'].'</td>';
echo '</tr>';
}
if ($a_computerextend['wincompany'] != '') {
echo '<tr class="tab_bg_1">';
echo '<td>'.__('Company', 'fusioninventory').'</td>';
echo '<td>'.$a_computerextend['wincompany'].'</td>';
echo '</tr>';
}
return true;
}
/**
* Display information about computer that is linked to an agent but
* has no inventory
*
* @since 9.2
* @param object $item
* @return true
*/
static function showFormForAgentWithNoInventory($item) {
$id = $item->getID();
$pfComputer = new self();
if ($item->isNewItem()
|| !empty($pfComputer->hasAutomaticInventory($id))) {
return true;
} else {
$pfAgent = new PluginFusioninventoryAgent();
if ($pfAgent->getAgentWithComputerid($id)) {
echo '<tr>';
echo '<td colspan=\'4\'></td>';
echo '</tr>';
echo '<tr>';
echo '<th colspan="4">'.__('FusionInventory', 'fusioninventory').'</th>';
echo '</tr>';
$pfAgent->showInfoForComputer($item, 4);
}
return true;
}
}
/**
* Display information about a computer operating system
* has no inventory
*
* @since 9.2
* @param object $item
* @return true
*/
static function showFormOS($item) {
$pfComputer = new self();
$a_computerextend = current(
$pfComputer->find(['computers_id' => $item->fields['items_id']], [], 1)
);
if (empty($a_computerextend)) {
return;
}
echo '<tr class="tab_bg_1">';
echo "<th colspan='4'></th>";
echo "</tr>";
echo '<tr class="tab_bg_1">';
echo '<td>'.__('Company', 'fusioninventory').'</td>';
echo '<td>'.$a_computerextend['wincompany'].'</td>';
echo '<td>'.__('Owner', 'fusioninventory').'</td>';
echo '<td>'.$a_computerextend['winowner'].'</td>';
echo '</tr>';
echo '<tr class="tab_bg_1">';
echo "<td>".__('Comments')."</td>";
echo '<td>'.$a_computerextend['oscomment'].'</td>';
echo "<td>".__("Installation date")."</td>";
echo '<td>'.Html::convDate($a_computerextend['operatingsystem_installationdate']).'</td>';
echo "<tr class='tab_bg_1'>";
echo "<td>".__('HostID', 'fusioninventory')."</td>";
echo "<td>";
echo $a_computerextend['hostid'];
echo "</td><colspan='2'></td>";
echo "</tr>";
return true;
}
/**
* Display information about computer (bios, last contact...)
*
* @global array $CFG_GLPI
* @param object $item
* @return true
*/
static function showComputerInfo($item) {
$fi_path = Plugin::getWebDir('fusioninventory');
// Manage locks pictures
PluginFusioninventoryLock::showLockIcon('Computer');
$pfInventoryComputerComputer = new PluginFusioninventoryInventoryComputerComputer();
$a_computerextend = $pfInventoryComputerComputer->hasAutomaticInventory($item->getID());
if (empty($a_computerextend)) {
return true;
}
echo '<table class="tab_glpi" width="100%">';
echo '<tr>';
echo '<th colspan="4">'.__('FusionInventory', 'fusioninventory').'</th>';
echo '</tr>';
$pfAgent = new PluginFusioninventoryAgent();
$pfAgent->showInfoForComputer($item, 4);
echo '<tr class="tab_bg_1">';
if ($a_computerextend['remote_addr'] != '') {
echo '<td>'.__('Public contact address', 'fusioninventory').'</td>';
echo '<td>'.$a_computerextend['remote_addr'].'</td>';
} else {
echo "<td colspan='2'></td>";
}
echo '<td>';
echo __('Last inventory', 'fusioninventory');
echo '</td>';
echo '<td>';
echo Html::convDateTime($a_computerextend['last_fusioninventory_update']);
echo '</td>';
echo '</tr>';
echo '<tr class="tab_bg_1">';
// Display automatic entity transfer
if (Session::isMultiEntitiesMode()) {
echo '<td>'.__('Automatic entity transfer', 'fusioninventory').'</td>';
echo '<td>';
$pfEntity = new PluginFusioninventoryEntity();
if ($pfEntity->getValue('transfers_id_auto', $item->fields['entities_id']) == 0) {
echo __('No, locked (by entity configuration)', 'fusioninventory');
} else {
if ($a_computerextend['is_entitylocked'] == 1) {
echo __('No, locked manually', 'fusioninventory');
echo " [ <a href='".$fi_path."/front/computerentitylock.form.php?id=".
$a_computerextend['id']."&lock=0'>".__('Unlock it', 'fusioninventory')."</a> ]";
} else {
echo __('Yes');
echo " [ <a href='".$fi_path."/front/computerentitylock.form.php?id=".
$a_computerextend['id']."&lock=1'>".__('Lock it', 'fusioninventory')."</a> ]";
}
}
echo '</td>';
} else {
echo "<td colspan='2'></td>";
}
echo '<td>';
echo __('Last boot', 'fusioninventory');
echo '</td>';
echo '<td>';
echo Html::convDateTime($a_computerextend['last_boot']);
echo '</td>';
echo '</tr>';
$pfRemoteManagement = new PluginFusioninventoryComputerRemoteManagement();
$pfRemoteManagement->showInformation($item->getID());
echo '</table>';
return true;
}
/**
* Delete extended information of computer
*
* @param integer $computers_id
*/
static function cleanComputer($computers_id) {
$pfComputer = new self();
$pfComputer->deleteByCriteria(['computers_id' => $computers_id], true, false);
}
/**
* Get entity lock. If true, computer can't be transfered to another entity
* by agent inventory (so in automatic)
*
* @param integer $computers_id
* @return boolean
*/
function getLock($computers_id) {
$pfInventoryComputerComputer = new PluginFusioninventoryInventoryComputerComputer();
$a_computerextend = current($pfInventoryComputerComputer->find(
['computers_id' => $computers_id], [], 1));
if (empty($a_computerextend)) {
return false;
}
return $a_computerextend['is_entitylocked'];
}
}

View File

@@ -0,0 +1,56 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the the criteria of blacklist.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the the criteria of blacklist.
*/
class PluginFusioninventoryInventoryComputerCriteria extends CommonDBTM {
}

View File

@@ -0,0 +1,180 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the taskjob for VMWARE ESX / VCENTER remote
* inventory.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author Walid Nouh
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the taskjob for VMWARE ESX / VCENTER remote inventory.
*/
class PluginFusioninventoryInventoryComputerESX extends PluginFusioninventoryCommunication {
/**
* Get all devices and put in taskjobstate each task for
* each device for each agent
*
* @param integer $taskjobs_id id of taskjob esx
* @return string uniqid value
*/
function prepareRun($taskjobs_id) {
$task = new PluginFusioninventoryTask();
$job = new PluginFusioninventoryTaskjob();
$joblog = new PluginFusioninventoryTaskjoblog();
$jobstate = new PluginFusioninventoryTaskjobstate();
$uniqid= uniqid();
$job->getFromDB($taskjobs_id);
$task->getFromDB($job->fields['plugin_fusioninventory_tasks_id']);
$communication= $task->fields['communication'];
//list all agents
$agent_actions = importArrayFromDB($job->fields['action']);
$task_definitions = importArrayFromDB($job->fields['definition']);
$agent_actionslist = [];
foreach ($agent_actions as $targets) {
foreach ($targets as $itemtype => $items_id) {
$item = new $itemtype();
// Detect if agent exists
if ($item->getFromDB($items_id)) {
$agent_actionslist[$items_id] = 1;
}
}
}
// *** Add jobstate
if (empty($agent_actionslist)) {
$a_input= [];
$a_input['plugin_fusioninventory_taskjobs_id'] = $taskjobs_id;
$a_input['state'] = 0;
$a_input['plugin_fusioninventory_agents_id'] = 0;
$a_input['uniqid'] = $uniqid;
$a_input['execution_id'] = $task->fields['execution_id'];
foreach ($task_definitions as $task_definition) {
foreach ($task_definition as $task_itemtype => $task_items_id) {
$a_input['itemtype'] = $task_itemtype;
$a_input['items_id'] = $task_items_id;
$jobstates_id= $jobstate->add($a_input);
//Add log of taskjob
$a_input['plugin_fusioninventory_taskjobstates_id']= $jobstates_id;
$a_input['state'] = PluginFusioninventoryTaskjoblog::TASK_PREPARED;
$a_input['date'] = date("Y-m-d H:i:s");
$joblog->add($a_input);
$jobstate->changeStatusFinish($jobstates_id,
0,
'PluginFusioninventoryInventoryComputerESX',
1,
"Unable to find agent to run this job");
}
}
$job->update($job->fields);
} else {
foreach ($agent_actions as $targets) {
foreach ($targets as $items_id) {
if ($communication == "push") {
$_SESSION['glpi_plugin_fusioninventory']['agents'][$items_id] = 1;
}
foreach ($task_definitions as $task_definition) {
foreach ($task_definition as $task_itemtype => $task_items_id) {
$a_input = [];
$a_input['plugin_fusioninventory_taskjobs_id'] = $taskjobs_id;
$a_input['state'] = 0;
$a_input['plugin_fusioninventory_agents_id'] = $items_id;
$a_input['itemtype'] = $task_itemtype;
$a_input['items_id'] = $task_items_id;
$a_input['uniqid'] = $uniqid;
$a_input['date'] = date("Y-m-d H:i:s");
$a_input['execution_id'] = $task->fields['execution_id'];
$jobstates_id = $jobstate->add($a_input);
//Add log of taskjob
$a_input['plugin_fusioninventory_taskjobstates_id'] = $jobstates_id;
$a_input['state']= PluginFusioninventoryTaskjoblog::TASK_PREPARED;
$joblog->add($a_input);
unset($a_input['state']);
}
}
}
}
$job->fields['status']= 1;
$job->update($job->fields);
}
return $uniqid;
}
/**
* Get ESX jobs for this agent
*
* @param object $taskjobstate
* @return array
*/
function run($taskjobstate) {
$credential = new PluginFusioninventoryCredential();
$credentialip = new PluginFusioninventoryCredentialIp();
$credentialip->getFromDB($taskjobstate->fields['items_id']);
$credential->getFromDB($credentialip->fields['plugin_fusioninventory_credentials_id']);
$order['uuid'] = $taskjobstate->fields['uniqid'];
$order['host'] = $credentialip->fields['ip'];
$order['user'] = $credential->fields['username'];
$order['password'] = $credential->fields['password'];
return $order;
}
}

View File

@@ -0,0 +1,110 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the manual import of XML inventory.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the manual import of XML inventory.
*/
class PluginFusioninventoryInventoryComputerImportXML extends CommonDBTM {
/**
* Get rights
*
* @param string $interface
* @return array
*/
function getRights($interface = 'central') {
return [CREATE => __('Create')];
}
/**
* Display form for import the XML
*
* @global array $CFG_GLPI
* @return boolean
*/
function showForm() {
$target = Plugin::getWebDir('fusioninventory').'/front/inventorycomputerimportxml.php';
echo "<form action='".$target."' method='post' enctype='multipart/form-data'>";
echo "<br>";
echo "<table class='tab_cadre' cellpadding='1' width='600'>";
echo "<tr>";
echo "<th>";
echo __('Import XML file from an Agent', 'fusioninventory')." :";
echo "</th>";
echo "</tr>";
echo "<tr class='tab_bg_1'>";
echo "<td>";
echo __('You can use this menu to upload XML generated by an agent. '.
'The file must have .xml or .ocs extension. '.
'It\'s also possible to upload <b>ZIP</b> archive directly with a '.
'collection of XML files. '.
'Read you agent documentation to see how to generate such XML '.
'file', 'fusioninventory');
echo "</td>";
echo "</tr>";
echo "<tr class='tab_bg_1'>";
echo "<td align='center'>";
echo "<input type='file' name='importfile' value=''/>";
echo "&nbsp;<input type='submit' value='".__('Import')."' class='submit'/>";
echo "</td>";
echo "</tr>";
echo "</table>";
Html::closeForm();
return true;
}
}

View File

@@ -0,0 +1,665 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the import of computer inventory.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the import of computer inventory.
*/
class PluginFusioninventoryInventoryComputerInventory {
/**
* Initialize the array of inventory
*
* @var array
*/
private $arrayinventory = [];
/**
* initialize the device_id of the agent
*
* @var string
*/
private $device_id = '';
/**
* import data
*
* @global object $DB
* @global array $CFG_GLPI
* @param string $p_DEVICEID
* @param array $a_CONTENT
* @param array $arrayinventory
* @return string errors
*/
function import($p_DEVICEID, $a_CONTENT, $arrayinventory) {
global $DB, $CFG_GLPI;
$errors = '';
$_SESSION["plugin_fusioninventory_entity"] = -1;
// Prevent 2 computers with same name (Case of have the computer inventory 2 times in same time
// and so we don't want it create 2 computers instead one)
$name = '';
if (isset($arrayinventory['CONTENT']['HARDWARE']['NAME'])) {
$name = strtolower($arrayinventory['CONTENT']['HARDWARE']['NAME']);
}
$dbLock = new PluginFusioninventoryDBLock();
//Clean all locks lasting more than 10 minutes
$dbLock->releaseAllLocks();
if (!$dbLock->setLock('inventorynames', $name, true)) {
exit();
}
//$CFG_GLPI["use_log_in_files"] = TRUE;
$this->sendCriteria($p_DEVICEID, $arrayinventory);
$DB->delete(
'glpi_plugin_fusioninventory_dblockinventorynames', [
'value' => $name
]
);
return $errors;
}
/**
* Send Computer to inventoryruleimport
*
* @param string $p_DEVICEID
* @param array $arrayinventory
*/
function sendCriteria($p_DEVICEID, $arrayinventory) {
if (isset($_SESSION['plugin_fusioninventory_entityrestrict'])) {
unset($_SESSION['plugin_fusioninventory_entityrestrict']);
}
$this->device_id = $p_DEVICEID;
// * Hacks
// Hack to put OS in software
if (isset($arrayinventory['CONTENT']['HARDWARE']['OSNAME'])) {
$inputos = [];
if (isset($arrayinventory['CONTENT']['HARDWARE']['OSCOMMENTS'])) {
$inputos['COMMENTS'] = $arrayinventory['CONTENT']['HARDWARE']['OSCOMMENTS'];
}
$inputos['NAME'] = $arrayinventory['CONTENT']['HARDWARE']['OSNAME'];
if (isset($arrayinventory['CONTENT']['HARDWARE']['OSVERSION'])) {
$inputos['VERSION'] = $arrayinventory['CONTENT']['HARDWARE']['OSVERSION'];
}
if (isset($arrayinventory['CONTENT']['SOFTWARES']['VERSION'])) {
$temparray = $arrayinventory['CONTENT']['SOFTWARES'];
$arrayinventory['CONTENT']['SOFTWARES'] = [];
$arrayinventory['CONTENT']['SOFTWARES'][] = $temparray;
}
$arrayinventory['CONTENT']['SOFTWARES'][] = $inputos;
}
// Hack for USB Printer serial
if (isset($arrayinventory['CONTENT']['PRINTERS'])) {
foreach ($arrayinventory['CONTENT']['PRINTERS'] as $key=>$printer) {
if ((isset($printer['SERIAL']))
AND (preg_match('/\/$/', $printer['SERIAL']))) {
$arrayinventory['CONTENT']['PRINTERS'][$key]['SERIAL'] =
preg_replace('/\/$/', '', $printer['SERIAL']);
}
}
}
// Hack to remove Memories with Flash types see ticket
// http://forge.fusioninventory.org/issues/1337
if (isset($arrayinventory['CONTENT']['MEMORIES'])) {
foreach ($arrayinventory['CONTENT']['MEMORIES'] as $key=>$memory) {
if ((isset($memory['TYPE']))
AND (preg_match('/Flash/', $memory['TYPE']))) {
unset($arrayinventory['CONTENT']['MEMORIES'][$key]);
}
}
}
// End hack
$a_computerinventory = PluginFusioninventoryFormatconvert::computerInventoryTransformation(
$arrayinventory['CONTENT']);
// Get tag is defined and put it in fusioninventory_agent table
$tagAgent = "";
if (isset($a_computerinventory['ACCOUNTINFO'])) {
if (isset($a_computerinventory['ACCOUNTINFO']['KEYNAME'])
&& $a_computerinventory['ACCOUNTINFO']['KEYNAME'] == 'TAG') {
if (isset($a_computerinventory['ACCOUNTINFO']['KEYVALUE'])
&& $a_computerinventory['ACCOUNTINFO']['KEYVALUE'] != '') {
$tagAgent = $a_computerinventory['ACCOUNTINFO']['KEYVALUE'];
}
}
}
$pfAgent = new PluginFusioninventoryAgent();
$input = [];
$input['id'] = $_SESSION['plugin_fusioninventory_agents_id'];
$input['tag'] = $tagAgent;
$pfAgent->update($input);
$pfBlacklist = new PluginFusioninventoryInventoryComputerBlacklist();
$a_computerinventory = $pfBlacklist->cleanBlacklist($a_computerinventory);
if (isset($a_computerinventory['monitor'])) {
foreach ($a_computerinventory['monitor'] as $num=>$a_monit) {
$a_computerinventory['monitor'][$num] = $pfBlacklist->cleanBlacklist($a_monit);
}
}
$this->fillArrayInventory($a_computerinventory);
$input = [];
// Global criterias
if ((isset($a_computerinventory['Computer']['serial']))
AND (!empty($a_computerinventory['Computer']['serial']))) {
$input['serial'] = $a_computerinventory['Computer']['serial'];
}
if ((isset($a_computerinventory['Computer']['otherserial']))
AND (!empty($a_computerinventory['Computer']['otherserial']))) {
$input['otherserial'] = $a_computerinventory['Computer']['otherserial'];
}
if ((isset($a_computerinventory['Computer']['uuid']))
AND (!empty($a_computerinventory['Computer']['uuid']))) {
$input['uuid'] = $a_computerinventory['Computer']['uuid'];
}
if (isset($this->device_id) && !empty($this->device_id)) {
$input['device_id'] = $this->device_id;
}
foreach ($a_computerinventory['networkport'] as $network) {
if (((isset($network['virtualdev']))
&& ($network['virtualdev'] != 1))
OR (!isset($network['virtualdev']))) {
if ((isset($network['mac'])) AND (!empty($network['mac']))) {
$input['mac'][] = $network['mac'];
}
foreach ($network['ipaddress'] as $ip) {
if ($ip != '127.0.0.1' && $ip != '::1') {
$input['ip'][] = $ip;
}
}
if ((isset($network['subnet'])) AND (!empty($network['subnet']))) {
$input['subnet'][] = $network['subnet'];
}
}
}
// Case of virtualmachines
if (!isset($input['mac'])
&& !isset($input['ip'])) {
foreach ($a_computerinventory['networkport'] as $network) {
if ((isset($network['mac'])) AND (!empty($network['mac']))) {
$input['mac'][] = $network['mac'];
}
foreach ($network['ipaddress'] as $ip) {
if ($ip != '127.0.0.1' && $ip != '::1') {
$input['ip'][] = $ip;
}
}
if ((isset($network['subnet'])) AND (!empty($network['subnet']))) {
$input['subnet'][] = $network['subnet'];
}
}
}
if ((isset($a_computerinventory['fusioninventorycomputer']['items_operatingsystems_id']['license_number']))
AND (!empty($a_computerinventory['fusioninventorycomputer']['items_operatingsystems_id']['license_number']))) {
$input['mskey'] = $a_computerinventory['fusioninventorycomputer']['items_operatingsystems_id']['license_number'];
}
if ((isset($a_computerinventory['fusioninventorycomputer']['items_operatingsystems_id']['operatingsystems_id']))
AND (!empty($a_computerinventory['fusioninventorycomputer']['items_operatingsystems_id']['operatingsystems_id']))) {
$input['osname'] = $a_computerinventory['fusioninventorycomputer']['items_operatingsystems_id']['operatingsystems_id'];
}
if ((isset($a_computerinventory['fusioninventorycomputer']['oscomment']))
AND (!empty($a_computerinventory['fusioninventorycomputer']['oscomment']))) {
$input['oscomment'] = $a_computerinventory['fusioninventorycomputer']['oscomment'];
}
if ((isset($a_computerinventory['Computer']['computermodels_id']))
AND (!empty($a_computerinventory['Computer']['computermodels_id']))) {
$input['model'] = $a_computerinventory['Computer']['computermodels_id'];
}
if ((isset($a_computerinventory['Computer']['domains_id']))
AND (!empty($a_computerinventory['Computer']['domains_id']))) {
$input['domains_id'] = $a_computerinventory['Computer']['domains_id'];
}
$input['tag'] = $tagAgent;
if ((isset($a_computerinventory['Computer']['name']))
AND ($a_computerinventory['Computer']['name'] != '')) {
$input['name'] = $a_computerinventory['Computer']['name'];
} else {
$input['name'] = '';
}
$input['itemtype'] = "Computer";
// If transfer is disable, get entity and search only on this entity
// (see http://forge.fusioninventory.org/issues/1503)
// * entity rules
$inputent = $input;
if ((isset($a_computerinventory['Computer']['domains_id']))
AND (!empty($a_computerinventory['Computer']['domains_id']))) {
$inputent['domain'] = $a_computerinventory['Computer']['domains_id'];
}
if (isset($inputent['serial'])) {
$inputent['serialnumber'] = $inputent['serial'];
}
$ruleEntity = new PluginFusioninventoryInventoryRuleEntityCollection();
// * Reload rules (required for unit tests)
$ruleEntity->getCollectionPart();
$dataEntity = $ruleEntity->processAllRules($inputent, []);
if (isset($dataEntity['_ignore_import'])) {
return;
}
if (isset($dataEntity['entities_id'])
&& $dataEntity['entities_id'] >= 0) {
$_SESSION["plugin_fusioninventory_entity"] = $dataEntity['entities_id'];
$input['entities_id'] = $dataEntity['entities_id'];
} else if (isset($dataEntity['entities_id'])
&& $dataEntity['entities_id'] == -1) {
$input['entities_id'] = 0;
$_SESSION["plugin_fusioninventory_entity"] = -1;
} else {
$input['entities_id'] = 0;
$_SESSION["plugin_fusioninventory_entity"] = 0;
}
if (isset($dataEntity['locations_id'])) {
$_SESSION['plugin_fusioninventory_locations_id'] = $dataEntity['locations_id'];
}
// End entity rules
$_SESSION['plugin_fusioninventory_classrulepassed'] =
"PluginFusioninventoryInventoryComputerInventory";
//Add the location if needed (play rule locations engine)
$output = [];
$output = PluginFusioninventoryToolbox::addLocation($input, $output);
if (isset($output['locations_id'])) {
$_SESSION['plugin_fusioninventory_locations_id'] =
$output['locations_id'];
}
$rule = new PluginFusioninventoryInventoryRuleImportCollection();
// * Reload rules (required for unit tests)
$rule->getCollectionPart();
$data = $rule->processAllRules($input, [], ['class'=>$this]);
PluginFusioninventoryToolbox::logIfExtradebug("pluginFusioninventory-rules",
$data);
if (isset($data['_no_rule_matches']) AND ($data['_no_rule_matches'] == '1')) {
$this->rulepassed(0, "Computer");
} else if (!isset($data['found_equipment'])) {
$pfIgnoredimportdevice = new PluginFusioninventoryIgnoredimportdevice();
$inputdb = [];
$inputdb['name'] = $input['name'];
$inputdb['date'] = date("Y-m-d H:i:s");
$inputdb['itemtype'] = "Computer";
if ((isset($a_computerinventory['Computer']['domains_id']))
AND (!empty($a_computerinventory['Computer']['domains_id']))) {
$inputdb['domain'] = $a_computerinventory['Computer']['domains_id'];
}
if (isset($a_computerinventory['Computer']['serial'])) {
$inputdb['serial'] = $a_computerinventory['Computer']['serial'];
}
if (isset($a_computerinventory['Computer']['uuid'])) {
$inputdb['uuid'] = $a_computerinventory['Computer']['uuid'];
}
if (isset($input['ip'])) {
$inputdb['ip'] = $input['ip'];
}
if (isset($input['mac'])) {
$inputdb['mac'] = $input['mac'];
}
$inputdb['entities_id'] = $input['entities_id'];
if (isset($input['ip'])) {
$inputdb['ip'] = exportArrayToDB($input['ip']);
}
if (isset($input['mac'])) {
$inputdb['mac'] = exportArrayToDB($input['mac']);
}
$inputdb['rules_id'] = $data['_ruleid'];
$inputdb['method'] = 'inventory';
$inputdb['plugin_fusioninventory_agents_id'] = $_SESSION['plugin_fusioninventory_agents_id'];
// if existing ignored device, update it
if ($found = $pfIgnoredimportdevice->find(
['plugin_fusioninventory_agents_id' => $inputdb['plugin_fusioninventory_agents_id']],
['date DESC'], 1)) {
$agent = array_pop($found);
$inputdb['id'] = $agent['id'];
$pfIgnoredimportdevice->update($inputdb);
} else {
$pfIgnoredimportdevice->add($inputdb);
}
}
}
/**
* After rule engine passed, update task (log) and create item if required
*
* @global object $DB
* @global string $PLUGIN_FUSIONINVENTORY_XML
* @global boolean $PF_ESXINVENTORY
* @global array $CFG_GLPI
* @param integer $items_id id of the item (0 = not exist in database)
* @param string $itemtype
*/
function rulepassed($items_id, $itemtype, $ports_id = 0) {
global $DB, $PLUGIN_FUSIONINVENTORY_XML, $PF_ESXINVENTORY, $CFG_GLPI;
PluginFusioninventoryToolbox::logIfExtradebug(
"pluginFusioninventory-rules",
"Rule passed : ".$items_id.", ".$itemtype."\n"
);
$pfFormatconvert = new PluginFusioninventoryFormatconvert();
$a_computerinventory = $pfFormatconvert->replaceids($this->arrayinventory,
$itemtype, $items_id);
$entities_id = $_SESSION["plugin_fusioninventory_entity"];
if ($itemtype == 'Computer') {
$pfInventoryComputerLib = new PluginFusioninventoryInventoryComputerLib();
$pfAgent = new PluginFusioninventoryAgent();
$computer = new Computer();
if ($items_id == '0') {
if ($entities_id == -1) {
$entities_id = 0;
$_SESSION["plugin_fusioninventory_entity"] = 0;
}
$_SESSION['glpiactiveentities'] = [$entities_id];
$_SESSION['glpiactiveentities_string'] = $entities_id;
$_SESSION['glpiactive_entity'] = $entities_id;
} else {
$computer->getFromDB($items_id);
$a_computerinventory['Computer']['states_id'] = $computer->fields['states_id'];
$input = [];
$input = PluginFusioninventoryToolbox::addDefaultStateIfNeeded('computer', $input);
if (isset($input['states_id'])) {
$a_computerinventory['Computer']['states_id'] = $input['states_id'];
}
if ($entities_id == -1) {
$entities_id = $computer->fields['entities_id'];
$_SESSION["plugin_fusioninventory_entity"] = $computer->fields['entities_id'];
}
$_SESSION['glpiactiveentities'] = [$entities_id];
$_SESSION['glpiactiveentities_string'] = $entities_id;
$_SESSION['glpiactive_entity'] = $entities_id;
if ($computer->fields['entities_id'] != $entities_id) {
$pfEntity = new PluginFusioninventoryEntity();
$pfInventoryComputerComputer = new PluginFusioninventoryInventoryComputerComputer();
$moveentity = false;
if ($pfEntity->getValue('transfers_id_auto', $computer->fields['entities_id']) > 0) {
if (!$pfInventoryComputerComputer->getLock($items_id)) {
$moveentity = true;
}
}
if ($moveentity) {
$pfEntity = new PluginFusioninventoryEntity();
$transfer = new Transfer();
$transfer->getFromDB($pfEntity->getValue('transfers_id_auto', $entities_id));
$item_to_transfer = ["Computer" => [$items_id=>$items_id]];
$transfer->moveItems($item_to_transfer, $entities_id, $transfer->fields);
} else {
$_SESSION["plugin_fusioninventory_entity"] = $computer->fields['entities_id'];
$_SESSION['glpiactiveentities'] = [$computer->fields['entities_id']];
$_SESSION['glpiactiveentities_string'] = $computer->fields['entities_id'];
$_SESSION['glpiactive_entity'] = $computer->fields['entities_id'];
$entities_id = $computer->fields['entities_id'];
}
}
}
if ($items_id > 0) {
$a_computerinventory = $pfFormatconvert->extraCollectInfo(
$a_computerinventory,
$items_id);
}
$a_computerinventory = $pfFormatconvert->computerSoftwareTransformation(
$a_computerinventory,
$entities_id);
$no_history = false;
// * New
$setdynamic = 1;
if ($items_id == '0') {
$input = [];
$input['entities_id'] = $entities_id;
$input = PluginFusioninventoryToolbox::addDefaultStateIfNeeded('computer', $input);
if (isset($input['states_id'])) {
$a_computerinventory['Computer']['states_id'] = $input['states_id'];
} else {
$a_computerinventory['Computer']['states_id'] = 0;
}
$items_id = $computer->add($input);
$no_history = true;
$setdynamic = 0;
$_SESSION['glpi_fusionionventory_nolock'] = true;
if (isset($_SESSION['plugin_fusioninventory_rules_id'])) {
$pfRulematchedlog = new PluginFusioninventoryRulematchedlog();
$inputrulelog = [];
$inputrulelog['date'] = date('Y-m-d H:i:s');
$inputrulelog['rules_id'] = $_SESSION['plugin_fusioninventory_rules_id'];
if (isset($_SESSION['plugin_fusioninventory_agents_id'])) {
$inputrulelog['plugin_fusioninventory_agents_id'] =
$_SESSION['plugin_fusioninventory_agents_id'];
}
$inputrulelog['items_id'] = $items_id;
$inputrulelog['itemtype'] = $itemtype;
$inputrulelog['method'] = 'inventory';
$pfRulematchedlog->add($inputrulelog, [], false);
$pfRulematchedlog->cleanOlddata($items_id, $itemtype);
unset($_SESSION['plugin_fusioninventory_rules_id']);
}
}
if (isset($_SESSION['plugin_fusioninventory_locations_id'])) {
$a_computerinventory['Computer']['locations_id'] =
$_SESSION['plugin_fusioninventory_locations_id'];
unset($_SESSION['plugin_fusioninventory_locations_id']);
}
$serialized = gzcompress(serialize($a_computerinventory));
$a_computerinventory['fusioninventorycomputer']['serialized_inventory'] =
Toolbox::addslashes_deep($serialized);
if (!$PF_ESXINVENTORY) {
$pfAgent->setAgentWithComputerid($items_id, $this->device_id, $entities_id);
}
$query = $DB->buildInsert(
'glpi_plugin_fusioninventory_dblockinventories', [
'value' => $items_id
]
);
$CFG_GLPI["use_log_in_files"] = false;
if (!$DB->query($query)) {
$communication = new PluginFusioninventoryCommunication();
$communication->setMessage("<?xml version='1.0' encoding='UTF-8'?>
<REPLY>
<ERROR>ERROR: SAME COMPUTER IS CURRENTLY UPDATED</ERROR>
</REPLY>");
$communication->sendMessage($_SESSION['plugin_fusioninventory_compressmode']);
exit;
}
$CFG_GLPI["use_log_in_files"] = true;
// * For benchs
//$start = microtime(TRUE);
PluginFusioninventoryInventoryComputerStat::increment();
$pfInventoryComputerLib->updateComputer(
$a_computerinventory,
$items_id,
$no_history,
$setdynamic);
$DB->delete(
'glpi_plugin_fusioninventory_dblockinventories', [
'value' => $items_id
]
);
if (isset($_SESSION['glpi_fusionionventory_nolock'])) {
unset($_SESSION['glpi_fusionionventory_nolock']);
}
$plugin = new Plugin();
if ($plugin->isActivated('monitoring')) {
Plugin::doOneHook("monitoring", "ReplayRulesForItem", ['Computer', $items_id]);
}
// * For benchs
//Toolbox::logInFile("exetime", (microtime(TRUE) - $start)." (".$items_id.")\n".
// memory_get_usage()."\n".
// memory_get_usage(TRUE)."\n".
// memory_get_peak_usage()."\n".
// memory_get_peak_usage()."\n");
// Write XML file
if (!empty($PLUGIN_FUSIONINVENTORY_XML)) {
PluginFusioninventoryToolbox::writeXML(
$items_id,
$PLUGIN_FUSIONINVENTORY_XML->asXML(),
'computer');
}
} else if ($itemtype == 'PluginFusioninventoryUnmanaged') {
$a_computerinventory = $pfFormatconvert->computerSoftwareTransformation(
$a_computerinventory,
$entities_id);
$class = new $itemtype();
if ($items_id == "0") {
if ($entities_id == -1) {
$_SESSION["plugin_fusioninventory_entity"] = 0;
}
$input = [];
$input['date_mod'] = date("Y-m-d H:i:s");
$items_id = $class->add($input);
if (isset($_SESSION['plugin_fusioninventory_rules_id'])) {
$pfRulematchedlog = new PluginFusioninventoryRulematchedlog();
$inputrulelog = [];
$inputrulelog['date'] = date('Y-m-d H:i:s');
$inputrulelog['rules_id'] = $_SESSION['plugin_fusioninventory_rules_id'];
if (isset($_SESSION['plugin_fusioninventory_agents_id'])) {
$inputrulelog['plugin_fusioninventory_agents_id'] =
$_SESSION['plugin_fusioninventory_agents_id'];
}
$inputrulelog['items_id'] = $items_id;
$inputrulelog['itemtype'] = $itemtype;
$inputrulelog['method'] = 'inventory';
$pfRulematchedlog->add($inputrulelog);
$pfRulematchedlog->cleanOlddata($items_id, $itemtype);
unset($_SESSION['plugin_fusioninventory_rules_id']);
}
}
$class->getFromDB($items_id);
$_SESSION["plugin_fusioninventory_entity"] = $class->fields['entities_id'];
$input = [];
$input['id'] = $class->fields['id'];
// Write XML file
if (!empty($PLUGIN_FUSIONINVENTORY_XML)) {
PluginFusioninventoryToolbox::writeXML(
$items_id,
$PLUGIN_FUSIONINVENTORY_XML->asXML(),
'PluginFusioninventoryUnmanaged');
}
if (isset($a_computerinventory['Computer']['name'])) {
$input['name'] = $a_computerinventory['Computer']['name'];
}
$input['item_type'] = "Computer";
if (isset($a_computerinventory['Computer']['domains_id'])) {
$input['domain'] = $a_computerinventory['Computer']['domains_id'];
}
if (isset($a_computerinventory['Computer']['serial'])) {
$input['serial'] = $a_computerinventory['Computer']['serial'];
}
$class->update($input);
}
}
/**
* Return method name of this class/plugin
*
* @return string
*/
static function getMethod() {
return 'inventory';
}
/**
* Fill internal variable with the inventory array
*
* @param array $data
*/
function fillArrayInventory($data) {
$this->arrayinventory = $data;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,200 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the hooks for computer inventory. It's some
* other things we can do with inventory information.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the hooks for computer inventory. It's some other things we can do
* with inventory information.
*/
class PluginFusioninventoryInventoryComputerLibhook {
/**
* __contruct function where initilize sessions variables
*/
function __construct() {
if (!isset($_SESSION["plugin_fusioninventory_history_add"])) {
$_SESSION["plugin_fusioninventory_history_add"] = true;
}
if (!isset($_SESSION["plugin_fusioninventory_no_history_add"])) {
$_SESSION["plugin_fusioninventory_no_history_add"] = false;
}
$_SESSION["plugin_fusioninventory_userdefined"] = 0;
}
/**
* Define Mapping for unlock fields
*
* @return array of the mapping
*/
static function getMapping() {
$opt = [];
$i = 0;
// ** HARDWARE
$opt[$i]['xmlSection'] = 'HARDWARE';
$opt[$i]['xmlSectionChild'] = 'NAME';
$opt[$i]['glpiItemtype'] = 'Computer';
$opt[$i]['glpiField'] = 'name';
$i++;
$opt[$i]['xmlSection'] = 'HARDWARE';
$opt[$i]['xmlSectionChild'] = 'OSNAME';
$opt[$i]['glpiItemtype'] = 'Computer';
$opt[$i]['glpiField'] = 'operatingsystems_id';
$i++;
$opt[$i]['xmlSection'] = 'HARDWARE';
$opt[$i]['xmlSectionChild'] = 'OSVERSION';
$opt[$i]['glpiItemtype'] = 'Computer';
$opt[$i]['glpiField'] = 'operatingsystemversions_id';
$i++;
$opt[$i]['xmlSection'] = 'HARDWARE';
$opt[$i]['xmlSectionChild'] = 'WINPRODID';
$opt[$i]['glpiItemtype'] = 'Computer';
$opt[$i]['glpiField'] = 'os_licenseid';
$i++;
$opt[$i]['xmlSection'] = 'HARDWARE';
$opt[$i]['xmlSectionChild'] = 'WINPRODKEY';
$opt[$i]['glpiItemtype'] = 'Computer';
$opt[$i]['glpiField'] = 'os_license_number';
$i++;
$opt[$i]['xmlSection'] = 'HARDWARE';
$opt[$i]['xmlSectionChild'] = 'WORKGROUP';
$opt[$i]['glpiItemtype'] = 'Computer';
$opt[$i]['glpiField'] = 'domains_id';
$i++;
$opt[$i]['xmlSection'] = 'HARDWARE';
$opt[$i]['xmlSectionChild'] = 'OSCOMMENTS';
$opt[$i]['glpiItemtype'] = 'Computer';
$opt[$i]['glpiField'] = 'operatingsystemservicepacks_id';
$i++;
$opt[$i]['xmlSection'] = 'HARDWARE';
$opt[$i]['xmlSectionChild'] = 'UUID';
$opt[$i]['glpiItemtype'] = 'Computer';
$opt[$i]['glpiField'] = 'uuid';
$i++;
$opt[$i]['xmlSection'] = 'HARDWARE';
$opt[$i]['xmlSectionChild'] = 'DESCRIPTION';
$opt[$i]['glpiItemtype'] = 'Computer';
$opt[$i]['glpiField'] = 'comment';
// ** USERS
$i++;
$opt[$i]['xmlSection'] = 'USERS';
$opt[$i]['xmlSectionChild'] = 'LOGIN';
$opt[$i]['glpiItemtype'] = 'Computer';
$opt[$i]['glpiField'] = 'users_id';
$i++;
$opt[$i]['xmlSection'] = 'USERS';
$opt[$i]['xmlSectionChild'] = 'LOGIN';
$opt[$i]['glpiItemtype'] = 'Computer';
$opt[$i]['glpiField'] = 'contact';
// ** BIOS
$i++;
$opt[$i]['xmlSection'] = 'BIOS';
$opt[$i]['xmlSectionChild'] = 'SMANUFACTURER';
$opt[$i]['glpiItemtype'] = 'Computer';
$opt[$i]['glpiField'] = 'manufacturers_id';
$i++;
$opt[$i]['xmlSection'] = 'BIOS';
$opt[$i]['xmlSectionChild'] = 'SMODEL';
$opt[$i]['glpiItemtype'] = 'Computer';
$opt[$i]['glpiField'] = 'computermodels_id';
$i++;
$opt[$i]['xmlSection'] = 'BIOS';
$opt[$i]['xmlSectionChild'] = 'SSN';
$opt[$i]['glpiItemtype'] = 'Computer';
$opt[$i]['glpiField'] = 'serial';
$i++;
$opt[$i]['xmlSection'] = 'BIOS';
$opt[$i]['xmlSectionChild'] = 'TYPE';
$opt[$i]['glpiItemtype'] = 'Computer';
$opt[$i]['glpiField'] = 'computertypes_id';
return $opt;
}
/**
* Update model for HP for suppliertag plugin
*
* @param integer $items_id id of the computer
* @param string $partnumber HP partnumber
*/
function Suppliertag($items_id, $partnumber) {
if ($partnumber != 'Not Specified') {
$a_partnumber = explode("#", $partnumber);
$Plugin = new Plugin();
if ($Plugin->isActivated('manufacturersimports')) {
if (class_exists("PluginManufacturersimportsModel")) {
$PluginManufacturersimportsModel = new PluginManufacturersimportsModel();
$PluginManufacturersimportsModel->addModel(
['items_id' => $items_id,
'itemtype' => 'Computer',
'model_name' => $a_partnumber[0]]);
}
}
}
}
}

View File

@@ -0,0 +1,160 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the computer inventory stats (number of
* inventories arrived in the plugin Fusioninventory and regroued by hour).
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the computer inventory stats (number of inventories arrived in
* the plugin Fusioninventory and regroued by hour).
*/
class PluginFusioninventoryInventoryComputerStat extends CommonDBTM {
/**
* The right name for this class
*
* @var string
*/
static $rightname = 'plugin_fusioninventory_agent';
/**
* Get name of this type by language of the user connected
*
* @param integer $nb number of elements
* @return string name of this type
*/
static function getTypeName($nb = 0) {
return "Stat";
}
/**
* Init stats
*
* @global object $DB
*/
static function init() {
global $DB;
$insert = $DB->buildInsert(
'glpi_plugin_fusioninventory_inventorycomputerstats', [
'day' => new \QueryParam(),
'hour' => new \QueryParam()
]
);
$stmt = $DB->prepare($insert);
for ($d=1; $d<=365; $d++) {
for ($h=0; $h<24; $h++) {
$stmt->bind_param(
'ss',
$d,
$h
);
$stmt->execute();
}
}
mysqli_stmt_close($stmt);
}
/**
* Increment computer states
*
* @global object $DB
*/
static function increment() {
global $DB;
$DB->update(
'glpi_plugin_fusioninventory_inventorycomputerstats', [
'counter' => new \QueryExpression($DB->quoteName('counter') . ' + 1')
], [
'day' => date('z'),
'hour' => date('G')
]
);
}
/**
* Get stats for each hours for last xx hours
*
* @global object $DB
* @param integer $nb
* @return integer
*/
static function getLastHours($nb = 11) {
global $DB;
$a_counters = [];
$a_counters['key'] = 'test';
$timestamp = date('U');
for ($i=$nb; $i>=0; $i--) {
$timestampSearch = $timestamp - ($i * 3600);
$query = "SELECT * FROM `glpi_plugin_fusioninventory_inventorycomputerstats` "
."WHERE `day`='".date('z', $timestampSearch)."' "
." AND `hour`='".date('G', $timestampSearch)."' "
."LIMIT 1";
$result = $DB->query($query);
$data = $DB->fetchAssoc($result);
$cnt = 0;
if (!is_null($data)) {
$cnt = (int)$data['counter'];
}
$a_counters['values'][] = [
'label' => date('H', $timestampSearch).":00",
'value' => $cnt
];
}
return $a_counters;
}
}

View File

@@ -0,0 +1,111 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the webservice methods offered by the plugin
* FusionInventory. It require the GLPI plugin Webservice.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the webservice methods offered by the plugin FusionInventory.
* It require the GLPI plugin Webservice.
*/
class PluginFusioninventoryInventoryComputerWebservice {
/**
* Method for import XML by webservice
*
* @param array $params array ID of the agent
* @param string $protocol value the communication protocol used
* @return array
*
**/
static function loadInventory($params, $protocol) {
if (isset ($params['help'])) {
return ['base64' => 'string, mandatory',
'help' => 'bool, optional'];
}
if (!isset ($_SESSION['glpiID'])) {
return PluginWebservicesMethodCommon::Error($protocol, WEBSERVICES_ERROR_NOTAUTHENTICATED);
}
$content = base64_decode($params['base64']);
$pfCommunication = new PluginFusioninventoryCommunication();
$pfCommunication->handleOCSCommunication('', $content);
$msg = __('Computer injected into GLPI', 'fusioninventory');
return PluginWebservicesMethodCommon::Error($protocol, WEBSERVICES_ERROR_FAILED, '', $msg);
}
/**
* More information on the method
*
* @param array $params
* @param string $protocol
* @return array
*/
static function methodExtendedInfo($params, $protocol) {
$response = [];
if (!isset($params['computers_id'])
|| !is_numeric($params['computers_id'])) {
return $response;
}
$pfInventoryComputerComputer = new PluginFusioninventoryInventoryComputerComputer();
$a_computerextend = current($pfInventoryComputerComputer->find(
['computers_id' => $params['computers_id']],
[], 1));
if (empty($a_computerextend)) {
return $response;
}
return $a_computerextend;
}
}

View File

@@ -0,0 +1,163 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to get the name of PCIID, USBID and PCIID.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Used to get the name of PCIID, USBID and PCIID.
*/
class PluginFusioninventoryInventoryExternalDB extends CommonDBTM {
/**
* Get manufacturer from pciid
*
* @global object $DB
* @param string $pciid
* @return array
*/
static function getDataFromPCIID($pciid) {
global $DB;
$a_return = [];
if ($pciid == '') {
return $a_return;
}
$pciidArray = explode(":", $pciid);
if (!isset($pciidArray[1])) {
return $a_return;
}
$vendorId = $pciidArray[0];
$query_select = "SELECT `glpi_plugin_fusioninventory_pcivendors`.`name` as `manufacturer`,
`glpi_plugin_fusioninventory_pcidevices`.`name` as `name`
FROM `glpi_plugin_fusioninventory_pcivendors`
LEFT JOIN `glpi_plugin_fusioninventory_pcidevices`
ON `plugin_fusioninventory_pcivendor_id` = `glpi_plugin_fusioninventory_pcivendors`.`id`
WHERE `vendorid`='".$vendorId."'
AND `deviceid`='".$pciidArray[1]."'
LIMIT 1";
$resultSelect = $DB->query($query_select);
if ($DB->numrows($resultSelect) > 0) {
$data = $DB->fetchAssoc($resultSelect);
$a_return['name'] = html_entity_decode($data['name']);
$a_return['manufacturer'] = html_entity_decode($data['manufacturer']);
}
return $a_return;
}
/**
* Get data from vendorid and productid USB
*
* @global object $DB
* @param integer $vendorId
* @param integer $productId
* @return array
*/
static function getDataFromUSBID($vendorId, $productId) {
global $DB;
$vendorId = strtolower($vendorId);
$deviceId = strtolower($productId);
$vendors_name = "";
$devices_name = "";
$query_select = "SELECT id, name FROM `glpi_plugin_fusioninventory_usbvendors`
WHERE `vendorid`='".$vendorId."'
LIMIT 1";
$resultSelect = $DB->query($query_select);
if ($DB->numrows($resultSelect) > 0) {
$data = $DB->fetchAssoc($resultSelect);
$vendors_id = $data['id'];
$vendors_name = html_entity_decode($data['name']);
$query_selectd = "SELECT name FROM `glpi_plugin_fusioninventory_usbdevices`
WHERE `deviceid`='".$deviceId."'
AND `plugin_fusioninventory_usbvendor_id`='".$vendors_id."'
LIMIT 1";
$resultSelectd = $DB->query($query_selectd);
if ($DB->numrows($resultSelectd) > 0) {
$data = $DB->fetchAssoc($resultSelectd);
$devices_name = html_entity_decode($data['name']);
}
}
return [$vendors_name, $devices_name];
}
/**
* Get manufaturer linked to 6 first number of MAC address
*
* @global object $DB
* @param string $mac
* @return string
*/
static function getManufacturerWithMAC($mac) {
global $DB;
$a_mac = explode(":", $mac);
if (isset($a_mac[2])) {
$searchMac = $a_mac[0].":".$a_mac[1].":".$a_mac[2];
$query_select = "SELECT name FROM `glpi_plugin_fusioninventory_ouis`
WHERE `mac`='".$searchMac."'
LIMIT 1";
$resultSelect = $DB->query($query_select);
if ($DB->numrows($resultSelect) == 1) {
$data = $DB->fetchAssoc($resultSelect);
return $data['name'];
}
}
return "";
}
}

View File

@@ -0,0 +1,845 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the update of information into network
* equipment in GLPI.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the update of information into network equipment in GLPI.
*/
class PluginFusioninventoryInventoryNetworkEquipmentLib extends PluginFusioninventoryInventoryCommon {
public $data_device = [];
public $found_ports = [];
/**
* Function to update NetworkEquipment
*
* @global object $DB
* @param array $a_inventory data fron agent inventory
* @param integer $items_id id of the networkequipment
* @param boolean $no_history notice if changes must be logged or not
*/
function updateNetworkEquipment($a_inventory, $items_id, $no_history = false) {
global $DB;
$networkEquipment = new NetworkEquipment();
$pfNetworkEquipment = new PluginFusioninventoryNetworkEquipment();
$networkEquipment->getFromDB($items_id);
if (!isset($_SESSION['glpiactiveentities_string'])) {
$_SESSION['glpiactiveentities_string'] = "'" . $networkEquipment->fields['entities_id'] . "'";
}
if (!isset($_SESSION['glpiactiveentities'])) {
$_SESSION['glpiactiveentities'] = [$networkEquipment->fields['entities_id']];
}
if (!isset($_SESSION['glpiactive_entity'])) {
$_SESSION['glpiactive_entity'] = $networkEquipment->fields['entities_id'];
}
// * NetworkEquipment
$db_networkequipment = $networkEquipment->fields;
$a_lockable = PluginFusioninventoryLock::getLockFields('glpi_networkequipments', $items_id);
$a_ret = PluginFusioninventoryToolbox::checkLock($a_inventory['NetworkEquipment'],
$db_networkequipment, $a_lockable);
$a_inventory['NetworkEquipment'] = $a_ret[0];
$mac = $a_inventory['NetworkEquipment']['mac'];
unset($a_inventory['NetworkEquipment']['mac']);
$input = $a_inventory['NetworkEquipment'];
$input['id'] = $items_id;
$input['itemtype'] = 'NetworkEquipment';
//Add defaut status if there's one defined in the configuration
//If we're here it's because we've manually injected an snmpinventory xml file
$input = PluginFusioninventoryToolbox::addDefaultStateIfNeeded('snmp', $input);
//Add ips to the rule criteria array
$input['ip'] = $a_inventory['internalport'];
//Add the location if needed (play rule locations engine)
$input = PluginFusioninventoryToolbox::addLocation($input);
// Manage inventory number
if ($networkEquipment->fields['otherserial'] == ''
&& (!isset($input['otherserial'])
|| $input['otherserial'] == '')) {
$input['otherserial'] = PluginFusioninventoryToolbox::setInventoryNumber(
'NetworkEquipment', '', $networkEquipment->fields['entities_id']);
}
$networkEquipment->update($input, !$no_history);
$this->internalPorts($a_inventory['internalport'],
$items_id,
$mac,
'Internal');
// * NetworkEquipment fusion (ext)
$db_networkequipment = [];
$params = [
'FROM' => getTableForItemType("PluginFusioninventoryNetworkEquipment"),
'WHERE' => ['networkequipments_id' => $items_id]
];
$iterator = $DB->request($params);
while ($data = $iterator->next()) {
foreach ($data as $key=>$value) {
$db_networkequipment[$key] = Toolbox::addslashes_deep($value);
}
}
if (count($db_networkequipment) == '0') { // Add
$a_inventory['PluginFusioninventoryNetworkEquipment']['networkequipments_id'] =
$items_id;
$pfNetworkEquipment->add($a_inventory['PluginFusioninventoryNetworkEquipment']);
} else { // Update
$idtmp = $db_networkequipment['id'];
unset($db_networkequipment['id']);
unset($db_networkequipment['networkequipments_id']);
unset($db_networkequipment['plugin_fusioninventory_configsecurities_id']);
$a_ret = PluginFusioninventoryToolbox::checkLock(
$a_inventory['PluginFusioninventoryNetworkEquipment'],
$db_networkequipment);
$a_inventory['PluginFusioninventoryNetworkEquipment'] = $a_ret[0];
$input = $a_inventory['PluginFusioninventoryNetworkEquipment'];
$input['id'] = $idtmp;
$pfNetworkEquipment->update($input);
}
// * Ports
$this->importPorts('NetworkEquipment', $a_inventory, $items_id, $no_history);
//Import firmwares
$this->importFirmwares('NetworkEquipment', $a_inventory, $items_id, $no_history);
//Import simcards
$this->importSimcards('NetworkEquipment', $a_inventory, $items_id, $no_history);
Plugin::doHook("fusioninventory_inventory",
['inventory_data' => $a_inventory,
'networkequipments_id' => $items_id,
'no_history' => $no_history
]);
}
/**
* Import internal ports (so internal IP, management IP)
*
* @param array $a_ips
* @param integer $networkequipments_id
* @param string $mac
* @param string $networkname_name
*/
function internalPorts($a_ips, $networkequipments_id, $mac, $networkname_name) {
$networkPort = new NetworkPort();
$iPAddress = new IPAddress();
$pfUnmanaged = new PluginFusioninventoryUnmanaged();
$networkName = new NetworkName();
// Get agregated ports
$a_networkPortAggregates = current($networkPort->find(
['itemtype' => 'NetworkEquipment',
'items_id' => $networkequipments_id,
'instantiation_type' => 'NetworkPortAggregate',
'logical_number' => 0],
[], 1));
$a_ips_DB = [];
if (isset($a_networkPortAggregates['id'])) {
$a_networkPortAggregates['mac'] = $mac;
$networkPort->update($a_networkPortAggregates);
$networkports_id = $a_networkPortAggregates['id'];
} else {
$input = [];
$input['itemtype'] = 'NetworkEquipment';
$input['items_id'] = $networkequipments_id;
$input['instantiation_type'] = 'NetworkPortAggregate';
$input['name'] = 'general';
$input['mac'] = $mac;
$networkports_id = $networkPort->add($input);
}
// Get networkname
$a_networknames_find = current($networkName->find(
['items_id' => $networkports_id,
'itemtype' => 'NetworkPort'],
[], 1));
if (isset($a_networknames_find['id'])) {
$networknames_id = $a_networknames_find['id'];
$a_networknames_find['name'] = $networkname_name;
$networkName->update($a_networknames_find);
} else {
$input = [];
$input['items_id'] = $networkports_id;
$input['itemtype'] = 'NetworkPort';
$input['name'] = $networkname_name;
$networknames_id = $networkName->add($input);
}
$a_ips_fromDB = $iPAddress->find(
['itemtype' => 'NetworkName',
'items_id' => $networknames_id]);
foreach ($a_ips_fromDB as $data) {
$a_ips_DB[$data['id']] = $data['name'];
}
foreach ($a_ips as $key => $ip) {
foreach ($a_ips_DB as $keydb => $ipdb) {
if ($ip == $ipdb) {
unset($a_ips[$key]);
unset($a_ips_DB[$keydb]);
break;
}
}
}
if (count($a_ips) || count($a_ips_DB)) {
if (count($a_ips_DB) != 0 && count($a_ips) != 0) {
// Delete IPs in DB
foreach ($a_ips_DB as $idtmp => $ip) {
$iPAddress->delete(['id'=>$idtmp]);
}
}
if (count($a_ips) != 0) {
foreach ($a_ips as $ip) {
if ($ip != '127.0.0.1') {
$input = [];
$input['entities_id'] = 0;
$input['itemtype'] = 'NetworkName';
$input['items_id'] = $networknames_id;
$input['name'] = $ip;
$iPAddress->add($input);
// Search in unmanaged device if device with IP (LLDP) is yet added, in this case,
// we get id of this unmanaged device
$a_unmanageds = $pfUnmanaged->find(['ip' => $ip], [], 1);
if (count($a_unmanageds) > 0) {
$datas= current($a_unmanageds);
$this->unmanagedCDP = $datas['id'];
}
}
}
}
}
}
/**
* Import ports
*
* @param array $a_inventory
* @param integer $items_id
*/
function importPorts($itemtype, $a_inventory, $items_id, $no_history = false) {
//TODO : try to report this code in PluginFusioninventoryInventoryCommon::importPorts
$pfNetworkporttype = new PluginFusioninventoryNetworkporttype();
$networkPort = new NetworkPort();
$pfNetworkPort = new PluginFusioninventoryNetworkPort();
$networkports_id = 0;
$pfArrayPortInfos = [];
foreach ($a_inventory['networkport'] as $a_port) {
$ifType = $a_port['iftype'];
if ($pfNetworkporttype->isImportType($ifType)
|| isset($a_inventory['aggregate'][$a_port['logical_number']])
|| $ifType == '') {
$a_ports_DB = current($networkPort->find(
['itemtype' => 'NetworkEquipment',
'items_id' => $items_id,
'logical_number' => $a_port['logical_number']],
[], 1));
if (!isset($a_ports_DB['id'])) {
// Add port because not exists
if (isset($a_inventory['aggregate'])
&& isset($a_inventory['aggregate'][$a_port['logical_number']])) {
$a_port['instantiation_type'] = 'NetworkPortAggregate';
} else {
$a_port['instantiation_type'] = 'NetworkPortEthernet';
}
$a_port['items_id'] = $items_id;
$a_port['itemtype'] = 'NetworkEquipment';
$networkports_id = $networkPort->add($a_port, [], $no_history);
$a_pfnetworkport_DB = current($pfNetworkPort->find(
['networkports_id' => $networkports_id], [], 1));
$a_port['id'] = $a_pfnetworkport_DB['id'];
$a_port['lastup'] = date('Y-m-d H:i:s');
$pfNetworkPort->update($a_port);
} else {
// Update port
$networkports_id = $a_ports_DB['id'];
$a_port['id'] = $a_ports_DB['id'];
$networkPort->update($a_port);
unset($a_port['id']);
// Check if pfnetworkport exist.
$a_pfnetworkport_DB = current($pfNetworkPort->find(
['networkports_id' => $networkports_id], [], 1));
$a_port['networkports_id'] = $networkports_id;
if (isset($a_pfnetworkport_DB['id'])) {
$a_port['id'] = $a_pfnetworkport_DB['id'];
if ($a_port['ifstatus'] == 0
&& $a_pfnetworkport_DB['ifstatus'] == 1) {
$a_port['lastup'] = date('Y-m-d H:i:s');
}
$pfNetworkPort->update($a_port);
} else {
$a_port['networkports_id'] = $networkports_id;
$a_port['lastup'] = date('Y-m-d H:i:s');
$pfNetworkPort->add($a_port);
}
}
// Connections
if (isset($a_inventory['connection-lldp'][$a_port['logical_number']])) {
$this->importConnectionLLDP(
$a_inventory['connection-lldp'][$a_port['logical_number']],
$networkports_id);
} else if (isset($a_inventory['connection-mac'][$a_port['logical_number']])) {
$this->importConnectionMac(
$a_inventory['connection-mac'][$a_port['logical_number']],
$networkports_id);
}
// Vlan
if (isset($a_inventory['vlans'][$a_port['logical_number']])) {
$this->importPortVlan($a_inventory['vlans'][$a_port['logical_number']],
$networkports_id);
}
// Aggegation
if (isset($a_inventory['aggregate'])
&& isset($a_inventory['aggregate'][$a_port['logical_number']])) {
$this->importPortAggregate($a_inventory['aggregate'][$a_port['logical_number']],
$networkports_id, $items_id);
}
} else {
// Delete the port
$a_ports_DB = $networkPort->find(
['itemtype' => 'NetworkEquipment',
'items_id' => $items_id,
'logical_number' => $a_port['logical_number']],
[], 1);
if (count($a_ports_DB) > 0) {
$networkPort->delete(current($a_ports_DB));
}
}
}
}
/**
* Import LLDP connexions
*
* List of fields we have :
* - ifdescr
* - logical_number
* - sysdescr
* - model
* - ip
* - mac
* - name
*
* @param array $a_lldp
* @param integer $networkports_id
*/
function importConnectionLLDP($a_lldp, $networkports_id) {
$this->found_ports = [];
$pfNetworkPort = new PluginFusioninventoryNetworkPort();
$this->data_device = $a_lldp;
// Prepare data to import rule
$input_crit = [];
if (!empty($a_lldp['ifdescr'])) {
$input_crit['ifdescr'] = $a_lldp['ifdescr'];
}
if (!empty($a_lldp['logical_number'])) {
$input_crit['ifnumber'] = $a_lldp['logical_number'];
}
/* not coded in rules
if (!empty($a_lldp['sysdescr'])) {
$input_crit['sysdescr'] = $a_lldp['sysdescr'];
}*/
if (!empty($a_lldp['mac'])) {
$input_crit['mac'] = [$a_lldp['mac']];
}
if (!empty($a_lldp['name'])) {
$input_crit['name'] = $a_lldp['name'];
}
if (!empty($a_lldp['model'])) {
$input_crit['model'] = $a_lldp['model'];
}
if (!empty($a_lldp['ip'])) {
$input_crit['ip'] = [$a_lldp['ip']];
}
// Entity?
$rule = new PluginFusioninventoryInventoryRuleImportCollection();
$_SESSION['plugin_fusinvsnmp_datacriteria'] = serialize($input_crit);
// * Reload rules (required for unit tests)
$rule->getCollectionPart();
$data = $rule->processAllRules($input_crit, [], ['class'=>$this]);
PluginFusioninventoryToolbox::logIfExtradebug("pluginFusioninventory-rules",
$data);
$rule->getFromDB($data['_ruleid']);
if (count($this->found_ports)) {
$port_id = current(current($this->found_ports));
// We connect the 2 ports
$wire = new NetworkPort_NetworkPort();
$contact_id = $wire->getOppositeContact($networkports_id);
if (!($contact_id
AND $contact_id == $port_id)) {
$pfNetworkPort->disconnectDB($networkports_id);
$pfNetworkPort->disconnectDB($port_id);
$wire->add(['networkports_id_1'=> $networkports_id,
'networkports_id_2' => $port_id]);
}
}
}
/**
* Import connection with MAC address
*
* @param array $a_portconnection
* @param integer $networkports_id
*/
function importConnectionMac($a_portconnection, $networkports_id) {
$this->found_ports = [];
$wire = new NetworkPort_NetworkPort();
$networkPort = new NetworkPort();
$pfNetworkPort = new PluginFusioninventoryNetworkPort();
$pfUnmanaged = new PluginFusioninventoryUnmanaged();
$rule = new PluginFusioninventoryInventoryRuleImportCollection();
// Pass all MAC addresses in the import rules
foreach ($a_portconnection as $ifmac) {
$this->data_device = ['mac' => $ifmac];
$_SESSION['plugin_fusinvsnmp_datacriteria'] = serialize(['mac' => $ifmac]);
$data = $rule->processAllRules(['mac' => $ifmac], [], ['class'=>$this]);
}
$list_all_ports_found = [];
foreach ($this->found_ports as $itemtype => $ids) {
foreach ($ids as $items_id) {
$list_all_ports_found[] = $items_id;
}
}
if (count($list_all_ports_found) == 0) {
return;
}
$pfNetworkPort->loadNetworkport($networkports_id);
if ($pfNetworkPort->getValue('trunk') == '1'
&& count($list_all_ports_found) > 1) {
return;
}
// Try detect phone + computer on this port
if (count($list_all_ports_found) == 2) {
foreach ($this->found_ports as $itemtype => $ids) {
$phonecase = 0;
$macNotPhone_id = 0;
$phonePort_id = 0;
if ($itemtype == "phone") {
// Connect phone on switch port and other (computer..) in this phone
foreach ($ids as $items_id) {
$phonePort_id = current($items_id);
$phonecase++;
}
} else {
foreach ($ids as $items_id) {
$macNotPhone_id = $items_id;
}
}
}
if ($phonecase == 1) {
$wire->add(['networkports_id_1'=> $networkports_id,
'networkports_id_2' => $phonePort_id]);
$networkPort->getFromDB($phonePort_id);
$portLink_id = 0;
if ($networkPort->fields['name'] == 'Link') {
$portLink_id = $networkPort->fields['id'];
} else {
// Perhaps the phone as another port named 'Link'
$Phone = new Phone();
$Phone->getFromDB($networkPort->fields['items_id']);
$a_portsPhone = $networkPort->find(
['items_id' => $networkPort->fields['items_id'],
'itemtype' => 'Phone',
'name' => 'Link'],
[], 1);
$portLink_id = 0;
if (count($a_portsPhone) == '1') {
$a_portPhone = current($a_portsPhone);
$portLink_id = $a_portPhone['id'];
} else {
// Create Port Link
$input = [];
$input['name'] = 'Link';
$input['itemtype'] = 'Phone';
$input['items_id'] = $Phone->fields['id'];
$input['entities_id'] = $Phone->fields['entities_id'];
$portLink_id = $networkPort->add($input);
}
}
$opposite_id = false;
if ($opposite_id == $wire->getOppositeContact($portLink_id)) {
if ($opposite_id != $macNotPhone_id) {
$pfNetworkPort->disconnectDB($portLink_id); // disconnect this port
$pfNetworkPort->disconnectDB($macNotPhone_id); // disconnect destination port
}
}
$wire->add([
'networkports_id_1'=> $portLink_id,
'networkports_id_2' => $macNotPhone_id
]);
return;
}
}
if (count($list_all_ports_found) > 1) { // MultipleMac
// If we have minimum 1 device 'NetworkEquipment', we not manage these MAC addresses
if (isset($this->found_ports['NetworkEquipment'])) {
return;
}
// TODO update this function to pass the ports id found
$pfUnmanaged->hubNetwork($pfNetworkPort, $list_all_ports_found);
} else { // One mac on port
$networkPort->getFromDB(current($list_all_ports_found));
$id = $wire->getOppositeContact($networkPort->fields['id']);
if ($id && $id == $networkports_id) {
// yet connected
return;
}
$pfNetworkPort->disconnectDB($networkports_id); // disconnect this port
$pfNetworkPort->disconnectDB($networkPort->fields['id']); // disconnect destination port
$wire->add([
'networkports_id_1'=> $networkports_id,
'networkports_id_2' => $networkPort->fields['id']
]);
return;
}
}
/**
* Import VLANs
*
* @global object $DB
* @param array $a_vlans
* @param integer $networkports_id
*/
function importPortVlan($a_vlans, $networkports_id) {
global $DB;
$networkPort_Vlan = new NetworkPort_Vlan();
$db_vlans = [];
$query = "SELECT `glpi_networkports_vlans`.`id`, `glpi_vlans`.`name`, `glpi_vlans`.`tag`, `glpi_networkports_vlans`.`tagged`
FROM `glpi_networkports_vlans`
LEFT JOIN `glpi_vlans`
ON `vlans_id`=`glpi_vlans`.`id`
WHERE `networkports_id` = '$networkports_id'";
foreach ($DB->request($query) as $data) {
$db_vlans[$data['id']] = $data;
}
if (count($db_vlans) == 0) {
foreach ($a_vlans as $a_vlan) {
$this->addVlan($a_vlan, $networkports_id);
}
} else {
foreach ($a_vlans as $key => $arrays) {
foreach ($db_vlans as $keydb => $arraydb) {
if ($arrays['name'] == $arraydb['name'] && $arrays['tag'] == $arraydb['tag'] && $arrays['tagged'] == $arraydb['tagged']) {
unset($a_vlans[$key]);
unset($db_vlans[$keydb]);
break;
}
}
}
if (count($a_vlans) || count($db_vlans)) {
if (count($db_vlans) != 0) {
// Delete vlan in DB
foreach (array_keys($db_vlans) as $id) {
$networkPort_Vlan->delete(['id'=>$id]);
}
}
if (count($a_vlans) != 0) {
foreach ($a_vlans as $a_vlan) {
$this->addVlan($a_vlan, $networkports_id);
}
}
}
}
}
/**
* Add VLAN if not exist
*
* @param array $a_vlan
* @param integer $networkports_id
*/
function addVlan($a_vlan, $networkports_id) {
$networkPort_Vlan = new NetworkPort_Vlan();
$vlan = new Vlan();
$db_vlans = $vlan->find(['tag' => $a_vlan['tag'], 'name' => $a_vlan['name']], [], 1);
$vlans_id = 0;
if (count($db_vlans) > 0) {
$db_vlan = current($db_vlans);
$vlans_id = $db_vlan['id'];
} else {
$input = [];
$input['tag'] = $a_vlan['tag'];
$input['name'] = $a_vlan['name'];
$vlans_id = $vlan->add($input);
}
$input = [];
$input['networkports_id'] = $networkports_id;
$input['vlans_id'] = $vlans_id;
$input['tagged'] = $a_vlan['tagged'];
$networkPort_Vlan->add($input);
}
/**
* Import aggregate ports
*
* @param array $a_ports
* @param integer $networkports_id
* @param integer $networkequipments_id
*/
function importPortAggregate($a_ports, $networkports_id, $networkequipments_id) {
$networkPort = new NetworkPort();
$networkPortAggregate = new NetworkPortAggregate();
$a_aggregates = $networkPortAggregate->find(['networkports_id' => $networkports_id], [], 1);
$input = [];
if (count($a_aggregates) == 1) {
$input = current($a_aggregates);
} else {
$input['networkports_id'] = $networkports_id;
$input['networkports_id_list'] = exportArrayToDB([]);
$input['id'] = $networkPortAggregate->add($input);
}
$a_ports_db_tmp = [];
foreach ($a_ports as $logical_number) {
$a_networkports_DB = current($networkPort->find(
['itemtype' => 'NetworkEquipment',
'items_id' => $networkequipments_id,
'instantiation_type' => 'NetworkPortEthernet',
'logical_number' => $logical_number],
[], 1));
if (!isset($a_networkports_DB['id'])) {
// Add port
$a_port['instantiation_type'] = 'NetworkPortEthernet';
$a_port['items_id'] = $networkequipments_id;
$a_port['itemtype'] = 'NetworkEquipment';
$a_port['logical_number'] = $logical_number;
$networkports_id = $networkPort->add($a_port);
} else {
$networkports_id = $a_networkports_DB['id'];
}
$a_ports_db_tmp[] = $networkports_id;
}
$input['networkports_id_list'] = $a_ports_db_tmp;
$networkPortAggregate->update($input);
}
/**
* After rule engine passed, update task (log) and create item if required
*
* @param integer $items_id id of the item (0 = not exist in database)
* @param string $itemtype
*/
function rulepassed($items_id, $itemtype, $ports_id = 0) {
PluginFusioninventoryToolbox::logIfExtradebug(
"pluginFusioninventory-rules",
"Rule passed : ".$items_id.", ".$itemtype."\n"
);
$NetworkPort = new NetworkPort();
if ($itemtype == "") {
$itemtype = "PluginFusioninventoryUnmanaged";
}
$class = new $itemtype;
$dbu = new DbUtils();
if ($items_id == "0") {
// create the device
$input = $this->data_device;
if (!isset($input['name'])
&& isset($input['mac'])) {
$manufacturer = PluginFusioninventoryInventoryExternalDB::getManufacturerWithMAC($input['mac']);
$manufacturer = Toolbox::addslashes_deep($manufacturer);
$manufacturer = Toolbox::clean_cross_side_scripting_deep($manufacturer);
$input['name'] = $manufacturer;
}
$items_id = $class->add($input);
if (isset($_SESSION['plugin_fusioninventory_rules_id'])) {
$pfRulematchedlog = new PluginFusioninventoryRulematchedlog();
$inputrulelog = [];
$inputrulelog['date'] = date('Y-m-d H:i:s');
$inputrulelog['rules_id'] = $_SESSION['plugin_fusioninventory_rules_id'];
if (isset($_SESSION['plugin_fusioninventory_agents_id'])) {
$inputrulelog['plugin_fusioninventory_agents_id'] = $_SESSION['plugin_fusioninventory_agents_id'];
}
$inputrulelog['items_id'] = $items_id;
$inputrulelog['itemtype'] = $itemtype;
$inputrulelog['method'] = 'networkinventory';
$inputrulelog['criteria'] = $dbu->exportArrayToDB(unserialize($_SESSION['plugin_fusinvsnmp_datacriteria']));
$pfRulematchedlog->add($inputrulelog);
$pfRulematchedlog->cleanOlddata($items_id, $itemtype);
unset($_SESSION['plugin_fusioninventory_rules_id']);
}
// Create the network port
$input = [
'items_id' => $items_id,
'itemtype' => $itemtype
];
if (isset($this->data_device['ip'])) {
$input['_create_children'] = 1;
$input['NetworkName_name'] = '';
$input['NetworkName_fqdns_id'] = 0;
$input['NetworkName__ipaddresses'] = [
'-1' => $this->data_device['ip']
];
}
if (isset($this->data_device['ifdescr'])
&& !empty($this->data_device['ifdescr'])) {
$input['name'] = $this->data_device['ifdescr'];
}
if (!isset($input['name'])
&& isset($this->data_device['mac'])) {
$manufacturer = PluginFusioninventoryInventoryExternalDB::getManufacturerWithMAC($this->data_device['mac']);
$manufacturer = Toolbox::addslashes_deep($manufacturer);
$manufacturer = Toolbox::clean_cross_side_scripting_deep($manufacturer);
$input['name'] = $manufacturer;
}
if (isset($this->data_device['mac'])
&& !empty($this->data_device['mac'])) {
$input['mac'] = $this->data_device['mac'];
}
if (count($input) > 2) {
// so have network elements
$input['instantiation_type'] = 'NetworkPortEthernet';
$portID = $NetworkPort->add($input);
if (!isset($this->found_ports[$itemtype])) {
$this->found_ports[$itemtype] = [];
}
$this->found_ports[$itemtype][$portID] = $portID;
}
} else {
if ($ports_id > 0) {
if (!isset($this->found_ports[$itemtype])) {
$this->found_ports[$itemtype] = [];
}
$this->found_ports[$itemtype][$ports_id] = $ports_id;
} else {
// Add port
$input = [];
$input['items_id'] = $items_id;
$input['itemtype'] = $itemtype;
if (isset($this->data_device['ifdescr'])
&& !empty($this->data_device['ifdescr'])) {
$input['name'] = $this->data_device['ifdescr'];
}
if (isset($this->data_device['mac'])
&& !empty($this->data_device['mac'])) {
$input['mac'] = $this->data_device['mac'];
}
$input['instantiation_type'] = 'NetworkPortEthernet';
if (isset($this->data_device['ip'])
&& !empty($this->data_device['ip'])) {
$input['_create_children'] = 1;
$input['NetworkName_name'] = '';
$input['NetworkName_fqdns_id'] = 0;
$input['NetworkName__ipaddresses'] = [
'-1' => $this->data_device['ip']
];
}
$ports_id = $NetworkPort->add($input);
if (!isset($this->found_ports['PluginFusioninventoryUnmanaged'])) {
$this->found_ports['PluginFusioninventoryUnmanaged'] = [];
}
$this->found_ports['PluginFusioninventoryUnmanaged'][$ports_id] = $ports_id;
}
}
}
/**
* Get method name linked to this class
*
* @return string
*/
static function getMethod() {
return PluginFusioninventoryCommunicationNetworkInventory::getMethod();
}
}

View File

@@ -0,0 +1,249 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the update of information into printer in
* GLPI.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the update of information into printer in GLPI.
*/
class PluginFusioninventoryInventoryPrinterLib extends PluginFusioninventoryInventoryCommon {
/**
* Function to update Printer
*
* @global object $DB
* @param array $a_inventory data fron agent inventory
* @param integer $printers_id id of the printer
* @param boolean $no_history notice if changes must be logged or not
*/
function updatePrinter($a_inventory, $printers_id, $no_history = false) {
global $DB;
$printer = new Printer();
$pfPrinter = new PluginFusioninventoryPrinter();
$printer->getFromDB($printers_id);
if (!isset($_SESSION['glpiactiveentities_string'])) {
$_SESSION['glpiactiveentities_string'] = $printer->fields['entities_id'];
}
if (!isset($_SESSION['glpiactiveentities'])) {
$_SESSION['glpiactiveentities'] = [$printer->fields['entities_id']];
}
if (!isset($_SESSION['glpiactive_entity'])) {
$_SESSION['glpiactive_entity'] = $printer->fields['entities_id'];
}
// * Printer
$db_printer = $printer->fields;
$a_lockable = PluginFusioninventoryLock::getLockFields('glpi_printers', $printers_id);
$a_ret = PluginFusioninventoryToolbox::checkLock($a_inventory['Printer'],
$db_printer,
$a_lockable);
$a_inventory['Printer'] = $a_ret[0];
$input = $a_inventory['Printer'];
$input['id'] = $printers_id;
$input['itemtype'] = 'Printer';
if (isset($a_inventory['networkport'])) {
foreach ($a_inventory['networkport'] as $a_port) {
if (isset($a_port['ip'])) {
$input['ip'][] = $a_port['ip'];
}
}
}
//Add the location if needed (play rule locations engine)
$input = PluginFusioninventoryToolbox::addLocation($input);
// manage auto inventory number
if ($printer->fields['otherserial'] == ''
&& (!isset($input['otherserial'])
|| $input['otherserial'] == '')) {
$input['otherserial'] = PluginFusioninventoryToolbox::setInventoryNumber(
'Printer', '', $printer->fields['entities_id']);
}
$printer->update($input, !$no_history);
$db_printer = [];
// * Printer fusion (ext)
$params = [
'FROM' => getTableForItemType("PluginFusioninventoryPrinter"),
'WHERE' => ['printers_id' => $printers_id]
];
$iterator = $DB->request($params);
while ($data = $iterator->next()) {
foreach ($data as $key=>$value) {
$db_printer[$key] = Toolbox::addslashes_deep($value);
}
}
if (count($db_printer) == '0') { // Add
$a_inventory['PluginFusioninventoryPrinter']['printers_id'] =
$printers_id;
$pfPrinter->add($a_inventory['PluginFusioninventoryPrinter']);
} else { // Update
$idtmp = $db_printer['id'];
unset($db_printer['id']);
unset($db_printer['printers_id']);
unset($db_printer['plugin_fusioninventory_configsecurities_id']);
$a_ret = PluginFusioninventoryToolbox::checkLock(
$a_inventory['PluginFusioninventoryPrinter'],
$db_printer);
$a_inventory['PluginFusioninventoryPrinter'] = $a_ret[0];
$input = $a_inventory['PluginFusioninventoryPrinter'];
$input['id'] = $idtmp;
$pfPrinter->update($input);
}
// * Ports
$this->importPorts('Printer', $a_inventory, $printers_id, $no_history);
//Import firmwares
$this->importFirmwares('Printer', $a_inventory, $printers_id, $no_history);
//Import simcards
$this->importSimcards('Printer', $a_inventory, $printers_id, $no_history);
// Page counters
$this->importPageCounters($a_inventory['pagecounters'], $printers_id);
//Update printer page counter
$this->updateGlpiPageCounter($a_inventory['pagecounters'], $printers_id);
// Cartridges
$this->importCartridges($a_inventory['cartridge'], $printers_id);
Plugin::doHook("fusioninventory_inventory",
['inventory_data' => $a_inventory,
'printers_id' => $printers_id,
'no_history' => $no_history
]);
}
/**
* Import page counters
*
* @param array $a_pagecounters
* @param integer $printers_id
*/
function importPageCounters($a_pagecounters, $printers_id) {
$pfPrinterLog = new PluginFusioninventoryPrinterLog();
//See if have an entry today
$a_entires = $pfPrinterLog->find(
['printers_id' => $printers_id,
'date' => ['LIKE', date("Y-m-d").' %']],
[], 1);
if (count($a_entires) > 0) {
return;
}
$a_pagecounters['printers_id'] = $printers_id;
$a_pagecounters['date'] = date("Y-m-d H:i:s");
$pfPrinterLog->add($a_pagecounters);
}
/**
* Fill the current counter or page of the printer in GLPI
* using FI counter value
*
* @param array $a_pagecounters
* @param integer $printers_id
*/
function updateGlpiPageCounter($a_pagecounters, $printers_id) {
if (is_array($a_pagecounters) && isset($a_pagecounters['pages_total'])) {
$printer = new Printer();
if ($printer->getFromDB($printers_id)) {
$printer->update(['id' => $printers_id,
'last_pages_counter' => $a_pagecounters['pages_total']
], 0);
}
}
}
/**
* Import cartridges
*
* @param array $a_cartridges
* @param integer $printers_id
*/
function importCartridges($a_cartridges, $printers_id) {
$pfPrinterCartridge = new PluginFusioninventoryPrinterCartridge();
$a_db = $pfPrinterCartridge->find(['printers_id' => $printers_id]);
$a_dbcartridges = [];
foreach ($a_db as $data) {
$a_dbcartridges[$data['plugin_fusioninventory_mappings_id']] = $data;
}
foreach ($a_cartridges as $mappings_id=>$value) {
if (isset($a_dbcartridges[$mappings_id])) {
$a_dbcartridges[$mappings_id]['state'] = $value;
$pfPrinterCartridge->update($a_dbcartridges[$mappings_id]);
} else {
$input = [];
$input['printers_id'] = $printers_id;
$input['plugin_fusioninventory_mappings_id'] = $mappings_id;
$input['state'] = $value;
$pfPrinterCartridge->add($input);
}
}
}
}

View File

@@ -0,0 +1,412 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage entity rules for computer.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author Walid Nouh
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage entity rules for computer.
*/
class PluginFusioninventoryInventoryRuleEntity extends Rule {
/**
* Set these rules can be sorted
*
* @var boolean
*/
public $can_sort=true;
/**
* Set these rules don't have specific parameters
*
* @var boolean
*/
public $specific_parameters = false;
/**
* The right name for this class
*
* @var string
*/
static $rightname = 'plugin_fusioninventory_ruleentity';
const PATTERN_CIDR = 333;
const PATTERN_NOT_CIDR = 334;
/**
* Get name of this type by language of the user connected
*
* @return string name of this type
*/
function getTitle() {
return __('Entity rules', 'fusioninventory');
}
/**
* Make some changes before process review result
*
* @param array $output
* @return array
*/
function preProcessPreviewResults($output) {
return $output;
}
/**
* Define maximum number of actions possible in a rule
*
* @return integer
*/
function maxActionsCount() {
return 2;
}
/**
* Code execution of actions of the rule
*
* @param array $output
* @param array $params
* @return array
*/
function executeActions($output, $params, array $input = []) {
PluginFusioninventoryToolbox::logIfExtradebug(
"pluginFusioninventory-rules-entity",
"execute actions, data:\n". print_r($output, true). "\n" . print_r($params, true)
);
PluginFusioninventoryToolbox::logIfExtradebug(
"pluginFusioninventory-rules-entity",
"execute actions: ". count($this->actions) ."\n"
);
if (count($this->actions)) {
foreach ($this->actions as $action) {
PluginFusioninventoryToolbox::logIfExtradebug(
"pluginFusioninventory-rules-entity",
"- action: ". $action->fields["action_type"] ." for: ". $action->fields["field"] ."\n"
);
switch ($action->fields["action_type"]) {
case "assign" :
PluginFusioninventoryToolbox::logIfExtradebug(
"pluginFusioninventory-rules-entity",
"- value ".$action->fields["value"]."\n"
);
// todo: If always for an entity, use entities_id, no?
$output[$action->fields["field"]] = $action->fields["value"];
break;
case "regex_result" :
//Assign entity using the regex's result
if ($action->fields["field"] == "_affect_entity_by_tag") {
PluginFusioninventoryToolbox::logIfExtradebug(
"pluginFusioninventory-rules-entity",
"- value ".$action->fields["value"]."\n"
);
//Get the TAG from the regex's results
$res = RuleAction::getRegexResultById($action->fields["value"],
$this->regex_results[0]);
if (!is_null($res)) {
//Get the entity associated with the TAG
$target_entity = Entity::getEntityIDByTag($res);
if ($target_entity != '') {
$output["entities_id"]=$target_entity;
PluginFusioninventoryToolbox::logIfExtradebug(
"pluginFusioninventory-rules-entity",
"- set entity: ".$target_entity."\n"
);
} else {
$output['pass_rule'] = true;
}
}
}
break;
}
}
}
return $output;
}
/**
* Get the criteria available for the rule
*
* @return array
*/
function getCriterias() {
$criterias = [];
$criterias['tag']['field'] = 'name';
$criterias['tag']['name'] = __('FusionInventory tag', 'fusioninventory');
$criterias['domain']['field'] = 'name';
$criterias['domain']['name'] = __('Domain');
$criterias['subnet']['field'] = 'name';
$criterias['subnet']['name'] = __('Subnet');
$criterias['ip']['field'] = 'name';
$criterias['ip']['name'] = __('IP Address', 'fusioninventory');
$criterias['name']['field'] = 'name';
$criterias['name']['name'] = __("Computer's name", 'fusioninventory');
$criterias['serial']['field'] = 'name';
$criterias['serial']['name'] = __('Serial number');
$criterias['oscomment']['field'] = 'name';
$criterias['oscomment']['name'] = OperatingSystem::getTypeName(1).'/'.__('Comments');
return $criterias;
}
/**
* Get the actions available for the rule
*
* @return array
*/
function getActions() {
$actions = [];
$actions['entities_id']['name'] = Entity::getTypeName(1);
$actions['entities_id']['type'] = 'dropdown';
$actions['entities_id']['table'] = 'glpi_entities';
$actions['locations_id']['name'] = __('Location');
$actions['locations_id']['type'] = 'dropdown';
$actions['locations_id']['table'] = 'glpi_locations';
$actions['_affect_entity_by_tag']['name'] = __('Entity from TAG');
$actions['_affect_entity_by_tag']['type'] = 'text';
$actions['_affect_entity_by_tag']['force_actions'] = ['regex_result'];
$actions['_ignore_import']['name'] =
__('Ignore in FusionInventory import', 'fusioninventory');
$actions['_ignore_import']['type'] = 'yesonly';
return $actions;
}
/**
* Add additional rule conditions for criteria
*
* @param integer $condition
* @param string $criteria
* @param string $name
* @param string $value
* @param boolean $test
* @return boolean
*/
function displayAdditionalRuleCondition($condition, $criteria, $name, $value, $test = false) {
if ($test) {
return false;
}
switch ($condition) {
case Rule::PATTERN_FIND:
return false;
case PluginFusioninventoryInventoryRuleImport::PATTERN_IS_EMPTY :
Dropdown::showYesNo($name, 0, 0);
return true;
case Rule::PATTERN_EXISTS:
echo Dropdown::showYesNo($name, 1, 0);
return true;
case Rule::PATTERN_DOES_NOT_EXISTS:
echo Dropdown::showYesNo($name, 1, 0);
return true;
}
return false;
}
/**
* Add more criteria
*
* @param string $criterion
* @return array
*/
static function addMoreCriteria($criterion = '') {
if ($criterion == 'ip'
|| $criterion == 'subnet') {
return [self::PATTERN_CIDR => __('is CIDR', 'fusioninventory'),
self::PATTERN_NOT_CIDR => __('is not CIDR', 'fusioninventory')];
}
return [];
}
/**
* Check the criteria
*
* @param object $criteria
* @param array $input
* @return boolean
*/
function checkCriteria(&$criteria, &$input) {
$res = parent::checkCriteria($criteria, $input);
if (in_array($criteria->fields["condition"], [self::PATTERN_CIDR])) {
$pattern = $criteria->fields['pattern'];
$value = $this->getCriteriaValue($criteria->fields["criteria"],
$criteria->fields["condition"],
$input[$criteria->fields["criteria"]]);
list ($subnet, $bits) = explode('/', $pattern);
$subnet = ip2long($subnet);
$mask = -1 << (32 - $bits);
$subnet &= $mask; // nb: in case the supplied subnet wasn't correctly aligned
if (is_array($value)) {
foreach ($value as $ip) {
if (isset($ip) && $ip != '') {
$ip = ip2long($ip);
if (($ip & $mask) == $subnet) {
$res = true;
break 1;
}
}
}
} else {
if (isset($value) && $value != '') {
$ip = ip2long($value);
if (($ip & $mask) == $subnet) {
$res = true;
}
}
}
} else if (in_array($criteria->fields["condition"], [self::PATTERN_NOT_CIDR])) {
$pattern = $criteria->fields['pattern'];
$value = $this->getCriteriaValue($criteria->fields["criteria"],
$criteria->fields["condition"],
$input[$criteria->fields["criteria"]]);
list ($subnet, $bits) = explode('/', $pattern);
$subnet = ip2long($subnet);
$mask = -1 << (32 - $bits);
$subnet &= $mask; // nb: in case the supplied subnet wasn't correctly aligned
if (is_array($value)) {
$resarray = true;
foreach ($value as $ip) {
if (isset($ip) && $ip != '') {
$ip = ip2long($ip);
if (($ip & $mask) == $subnet) {
$resarray = false;
}
}
}
$res = $resarray;
} else {
if (isset($value) && $value != '') {
$ip = ip2long($value);
if (($ip & $mask) != $subnet) {
$res = true;
}
}
}
}
return $res;
}
/**
* Process the rule
*
* @param array &$input the input data used to check criterias
* @param array &$output the initial ouput array used to be manipulate by actions
* @param array &$params parameters for all internal functions
* @param array &options array options:
* - only_criteria : only react on specific criteria
*
* @return array the output updated by actions.
* If rule matched add field _rule_process to return value
*/
function process(&$input, &$output, &$params, &$options = []) {
if ($this->validateCriterias($options)) {
$this->regex_results = [];
$this->criterias_results = [];
$input = $this->prepareInputDataForProcess($input, $params);
if ($this->checkCriterias($input)) {
unset($output["_no_rule_matches"]);
$refoutput = $output;
$output = $this->executeActions($output, $params);
if (!isset($output['pass_rule'])) {
$this->updateOnlyCriteria($options, $refoutput, $output);
//Hook
$hook_params["sub_type"] = $this->getType();
$hook_params["ruleid"] = $this->fields["id"];
$hook_params["input"] = $input;
$hook_params["output"] = $output;
Plugin::doHook("rule_matched", $hook_params);
$output["_rule_process"] = true;
}
}
}
}
}

View File

@@ -0,0 +1,100 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the entity rules collection.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author Walid Nouh
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the entity rules collection.
*/
class PluginFusioninventoryInventoryRuleEntityCollection extends RuleCollection {
/**
* Set stop play rules when have the first rule of list match
*
* @var boolean
*/
public $stop_on_first_match=true;
/**
* Define the name of menu option
*
* @var string
*/
public $menu_option='test';
/**
* The right name for this class
*
* @var string
*/
static $rightname = 'plugin_fusioninventory_ruleentity';
/**
* Get name of this type by language of the user connected
*
* @return string name of this type
*/
function getTitle() {
return __('Entity rules', 'fusioninventory');
}
/**
* Prepare input data for process the rule
*
* @param array $input
* @param array $params
* @return array
*/
function prepareInputDataForProcess($input, $params) {
return $input;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,194 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage import rule collection for inventory.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage import rule collection for inventory.
*/
class PluginFusioninventoryInventoryRuleImportCollection extends RuleCollection {
/**
* Set stop play rules when have the first rule of list match
*
* @var boolean
*/
public $stop_on_first_match = true;
/**
* Define the name of menu option
*
* @var string
*/
public $menu_option = 'fusionlinkcomputer';
/**
* The right name for this class
*
* @var string
*/
static $rightname = "plugin_fusioninventory_ruleimport";
/**
* Get name of this type by language of the user connected
*
* @return string name of this type
*/
function getTitle() {
return __('Equipment import and link rules', 'fusioninventory');
}
/**
* Prepare input data for process the rule
*
* @param array $input
* @param array $params
* @return array
*/
function prepareInputDataForProcess($input, $params) {
return array_merge($input, $params);
}
/**
* Make some changes before process review result
*
* @param array $output
* @return array
*/
function preProcessPreviewResults($output) {
if (isset($output["action"])) {
echo "<tr class='tab_bg_2'>";
echo "<td>".__('Action type')."</td>";
echo "<td>";
switch ($output["action"]) {
case PluginFusioninventoryInventoryRuleImport::LINK_RESULT_LINK :
echo __('Link');
break;
case PluginFusioninventoryInventoryRuleImport::LINK_RESULT_CREATE:
echo __('Device created', 'fusioninventory');
break;
case PluginFusioninventoryInventoryRuleImport::LINK_RESULT_DENIED:
echo __('Import denied', 'fusioninventory');
break;
}
echo "</td>";
echo "</tr>";
if ($output["action"] != PluginFusioninventoryInventoryRuleImport::LINK_RESULT_DENIED
&& isset($output["found_equipment"])) {
echo "<tr class='tab_bg_2'>";
$className = $output["found_equipment"][1];
$class = new $className();
if ($class->getFromDB($output["found_equipment"][0])) {
echo "<td>".__('Link')."</td>";
echo "<td>".$class->getLink(true)."</td>";
}
echo "</tr>";
}
}
return $output;
}
/**
* Get collection datas: retrieve descriptions and rules
*
* @global object $DB
* @param integer $retrieve_criteria
* @param integer $retrieve_action
* @param integer $condition
*/
function getCollectionDatas($retrieve_criteria = 0, $retrieve_action = 0, $condition = 0) {
global $DB;
if ($this->RuleList === null) {
$this->RuleList = SingletonRuleList::getInstance($this->getRuleClassName(),
$this->entity);
}
$need = 1+($retrieve_criteria?2:0)+($retrieve_action?4:0);
//Select all the rules of a different type
$criteria = $this->getRuleListCriteria();
$iterator = $DB->request($criteria);
$this->RuleList->list = [];
while ($rule = $iterator->next()) {
//For each rule, get a Rule object with all the criterias and actions
$tempRule = $this->getRuleClass();
if ($tempRule->getRuleWithCriteriasAndActions($rule["id"], $retrieve_criteria,
$retrieve_action)) {
//Add the object to the list of rules
$this->RuleList->list[] = $tempRule;
}
}
$this->RuleList->load = $need;
}
function getRuleClassName() {
if (preg_match('/(.*)Collection/', get_class($this), $rule_class)) {
if (debug_backtrace()[1]['function'] == 'getRuleListCriteria') {
$rule_class[1] = str_replace('\\', '\\\\\\', $rule_class[1]);
}
return $rule_class[1];
}
return "";
}
}

View File

@@ -0,0 +1,410 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the location rules for computer.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author Walid Nouh
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the location rules for computer.
*/
class PluginFusioninventoryInventoryRuleLocation extends Rule {
/**
* The right name for this class
*
* @var string
*/
static $rightname = "plugin_fusioninventory_rulelocation";
/**
* Set these rules can be sorted
*
* @var boolean
*/
public $can_sort=true;
/**
* Set these rules don't have specific parameters
*
* @var boolean
*/
public $specific_parameters = false;
const PATTERN_CIDR = 333;
const PATTERN_NOT_CIDR = 334;
/**
* Get name of this type by language of the user connected
*
* @return string name of this type
*/
function getTitle() {
return __('Location rules', 'fusioninventory');
}
/**
* Make some changes before process review result
*
* @param array $output
* @return array
*/
function preProcessPreviewResults($output) {
return $output;
}
/**
* Define maximum number of actions possible in a rule
*
* @return integer
*/
function maxActionsCount() {
return 2;
}
/**
* Code execution of actions of the rule
*
* @param array $output
* @param array $params
* @return array
*/
function executeActions($output, $params, array $input = []) {
PluginFusioninventoryToolbox::logIfExtradebug(
"pluginFusioninventory-rules-location",
"execute actions, data:\n". print_r($output, true). "\n" . print_r($params, true)
);
PluginFusioninventoryToolbox::logIfExtradebug(
"pluginFusioninventory-rules-location",
"execute actions: ". count($this->actions) ."\n"
);
if (count($this->actions)) {
foreach ($this->actions as $action) {
PluginFusioninventoryToolbox::logIfExtradebug(
"pluginFusioninventory-rules-location",
"- action: ". $action->fields["action_type"] ." for: ". $action->fields["field"] ."\n"
);
switch ($action->fields["action_type"]) {
case "assign" :
PluginFusioninventoryToolbox::logIfExtradebug(
"pluginFusioninventory-rules-location",
"- value ".$action->fields["value"]."\n"
);
$output[$action->fields["field"]] = $action->fields["value"];
break;
case "regex_result" :
$res = '';
if (isset($this->regex_results[0])) {
PluginFusioninventoryToolbox::logIfExtradebug(
"pluginFusioninventory-rules-collect",
"- regex ".print_r($this->regex_results[0], true)."\n"
);
$res .= RuleAction::getRegexResultById($action->fields["value"],
$this->regex_results[0]);
PluginFusioninventoryToolbox::logIfExtradebug(
"pluginFusioninventory-rules-collect",
"- regex result: ".$res."\n"
);
} else {
$res .= $action->fields["value"];
}
if ($res != '') {
$entities_id = 0;
if (isset($_SESSION["plugin_fusioninventory_entity"])
&& $_SESSION["plugin_fusioninventory_entity"] > 0) {
$entities_id = $_SESSION["plugin_fusioninventory_entity"];
}
$res = Dropdown::importExternal(getItemtypeForForeignKeyField($action->fields['field']), $res, $entities_id);
}
PluginFusioninventoryToolbox::logIfExtradebug(
"pluginFusioninventory-rules-location",
"- value ".$res."\n"
);
$output[$action->fields["field"]] = $res;
break;
}
}
}
return $output;
}
/**
* Get the criteria available for the rule
*
* @return array
*/
function getCriterias() {
$criterias = [];
$criterias['itemtype']['name'] = __('Assets', 'fusioninventory').' : '.
__('Item type');
$criterias['itemtype']['type'] = 'dropdown_itemtype';
$criterias['itemtype']['is_global'] = false;
$criterias['itemtype']['allow_condition'] = [Rule::PATTERN_IS,
Rule::PATTERN_IS_NOT,
Rule::REGEX_MATCH,
Rule::REGEX_NOT_MATCH
];
$criterias['tag']['field'] = 'name';
$criterias['tag']['name'] = __('FusionInventory tag', 'fusioninventory');
$criterias['domain']['field'] = 'name';
$criterias['domain']['name'] = __('Domain');
$criterias['subnet']['field'] = 'name';
$criterias['subnet']['name'] = __('Subnet');
$criterias['ip']['field'] = 'name';
$criterias['ip']['name'] = __('Address')." ".__('IP');
$criterias['name']['field'] = 'name';
$criterias['name']['name'] = __('Name');
$criterias['serial']['field'] = 'name';
$criterias['serial']['name'] = __('Serial number');
$criterias['oscomment']['field'] = 'name';
$criterias['oscomment']['name'] = OperatingSystem::getTypeName(1).'/'.__('Comments');
return $criterias;
}
/**
* Get the actions available for the rule
*
* @return array
*/
function getActions() {
$actions = [];
$actions['locations_id']['name'] = __('Location');
$actions['locations_id']['type'] = 'dropdown';
$actions['locations_id']['table'] = 'glpi_locations';
$actions['locations_id']['force_actions'] = ['assign', 'regex_result'];
$actions['_ignore_import']['name'] =
__('Ignore in FusionInventory import', 'fusioninventory');
$actions['_ignore_import']['type'] = 'yesonly';
return $actions;
}
/**
* Display more conditions
*
* @param integer $condition
* @param object $criteria
* @param string $name
* @param string $value
* @param boolean $test
* @return boolean
*/
function displayAdditionalRuleCondition($condition, $criteria, $name, $value, $test = false) {
if ($test) {
return false;
}
switch ($condition) {
case Rule::PATTERN_FIND:
return false;
case PluginFusioninventoryInventoryRuleImport::PATTERN_IS_EMPTY :
Dropdown::showYesNo($name, 0, 0);
return true;
case Rule::PATTERN_EXISTS:
echo Dropdown::showYesNo($name, 1, 0);
return true;
case Rule::PATTERN_DOES_NOT_EXISTS:
echo Dropdown::showYesNo($name, 1, 0);
return true;
case Rule::PATTERN_IS:
case Rule::PATTERN_IS_NOT:
if (!empty($criteria)
&& isset($criteria['type'])
&& $criteria['type'] == 'dropdown_itemtype') {
$types = $this->getItemTypesForRules();
Dropdown::showItemTypes($name, array_keys($types),
['value' => $value]);
return true;
}
}
return false;
}
/**
* Add more criteria
*
* @param string $criterion
* @return array
*/
static function addMoreCriteria($criterion = '') {
if ($criterion == 'ip'
|| $criterion == 'subnet') {
return [self::PATTERN_CIDR => __('is CIDR', 'fusioninventory'),
self::PATTERN_NOT_CIDR => __('is not CIDR', 'fusioninventory')];
}
return [];
}
/**
* Check criteria
*
* @param object $criteria
* @param array $input
* @return boolean
*/
function checkCriteria(&$criteria, &$input) {
$res = parent::checkCriteria($criteria, $input);
if (in_array($criteria->fields["condition"], [self::PATTERN_CIDR])) {
$pattern = $criteria->fields['pattern'];
$value = $this->getCriteriaValue($criteria->fields["criteria"],
$criteria->fields["condition"],
$input[$criteria->fields["criteria"]]);
list ($subnet, $bits) = explode('/', $pattern);
$subnet = ip2long($subnet);
$mask = -1 << (32 - $bits);
$subnet &= $mask; // nb: in case the supplied subnet wasn't correctly aligned
if (is_array($value)) {
foreach ($value as $ip) {
if (isset($ip) && $ip != '') {
$ip = ip2long($ip);
if (($ip & $mask) == $subnet) {
$res = true;
break 1;
}
}
}
} else {
if (isset($value) && $value != '') {
$ip = ip2long($value);
if (($ip & $mask) == $subnet) {
$res = true;
}
}
}
} else if (in_array($criteria->fields["condition"], [self::PATTERN_NOT_CIDR])) {
$pattern = $criteria->fields['pattern'];
$value = $this->getCriteriaValue($criteria->fields["criteria"],
$criteria->fields["condition"],
$input[$criteria->fields["criteria"]]);
list ($subnet, $bits) = explode('/', $pattern);
$subnet = ip2long($subnet);
$mask = -1 << (32 - $bits);
$subnet &= $mask; // nb: in case the supplied subnet wasn't correctly aligned
if (is_array($value)) {
$resarray = true;
foreach ($value as $ip) {
if (isset($ip) && $ip != '') {
$ip = ip2long($ip);
if (($ip & $mask) == $subnet) {
$resarray = false;
}
}
}
$res = $resarray;
} else {
if (isset($value) && $value != '') {
$ip = ip2long($value);
if (($ip & $mask) != $subnet) {
$res = true;
}
}
}
}
return $res;
}
/**
* Get itemtypes have state_type and unmanaged devices
*
* @global array $CFG_GLPI
* @return array
*/
function getItemTypesForRules() {
global $CFG_GLPI;
$types = [];
foreach ($CFG_GLPI["networkport_types"] as $itemtype) {
if (class_exists($itemtype)) {
$item = new $itemtype();
$types[$itemtype] = $item->getTypeName();
}
}
$types[""] = __('No itemtype defined', 'fusioninventory');
ksort($types);
return $types;
}
}

View File

@@ -0,0 +1,87 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the location rule collection.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author Kevin Roy
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the location rule collection.
*/
class PluginFusioninventoryInventoryRuleLocationCollection extends RuleCollection {
/**
* The right name for this class
*
* @var string
*/
static $rightname = "plugin_fusioninventory_rulelocation";
/**
* Set stop play rules when have the first rule of list match
*
* @var boolean
*/
public $stop_on_first_match=true;
/**
* Define the name of menu option
*
* @var string
*/
public $menu_option='test';
/**
* Get name of this type by language of the user connected
*
* @return string name of this type
*/
function getTitle() {
return __('Location rules', 'fusioninventory');
}
}

View File

@@ -0,0 +1,398 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the IP ranges for network discovery and
* network inventory.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the IP ranges for network discovery and network inventory.
*/
class PluginFusioninventoryIPRange extends CommonDBTM {
/**
* We activate the history.
*
* @var boolean
*/
public $dohistory = true;
/**
* The right name for this class
*
* @var string
*/
static $rightname = 'plugin_fusioninventory_iprange';
/**
* Check if can create an IP range
*
* @return true
*/
static function canCreate() {
return true;
}
/**
* Get name of this type by language of the user connected
*
* @param integer $nb number of elements
* @return string name of this type
*/
static function getTypeName($nb = 0) {
if (isset($_SERVER['HTTP_REFERER']) AND strstr($_SERVER['HTTP_REFERER'], 'iprange')) {
if ((isset($_POST['glpi_tab'])) AND ($_POST['glpi_tab'] == 1)) {
// Permanent task discovery
return __('Communication mode', 'fusioninventory');
} else if ((isset($_POST['glpi_tab'])) AND ($_POST['glpi_tab'] == 2)) {
// Permanent task inventory
return __('See all informations of task', 'fusioninventory');
} else {
return __('IP Ranges', 'fusioninventory');
}
}
return __('IP Ranges', 'fusioninventory');
}
/**
* Get comments of the object
*
* @return string comments in HTML format
*/
function getComments() {
$comment = $this->fields['ip_start']." -> ".$this->fields['ip_end'];
return Html::showToolTip($comment, ['display' => false]);
}
/**
* Get search function for the class
*
* @return array
*/
function rawSearchOptions() {
$tab = [];
$tab[] = [
'id' => 'common',
'name' => __('IP range configuration', 'fusioninventory')
];
$tab[] = [
'id' => '1',
'table' => $this->getTable(),
'field' => 'name',
'name' => __('Name'),
'datatype' => 'itemlink',
'autocomplete' => true,
];
$tab[] = [
'id' => '2',
'table' => 'glpi_entities',
'field' => 'completename',
'linkfield' => 'entities_id',
'name' => Entity::getTypeName(1),
'datatype' => 'dropdown',
];
$tab[] = [
'id' => '3',
'table' => $this->getTable(),
'field' => 'ip_start',
'name' => __('Start of IP range', 'fusioninventory'),
];
$tab[] = [
'id' => '4',
'table' => $this->getTable(),
'field' => 'ip_end',
'name' => __('End of IP range', 'fusioninventory'),
];
$tab[] = [
'id' => '5',
'table' => 'glpi_plugin_fusioninventory_configsecurities',
'field' => 'name',
'datatype' => 'dropdown',
'right' => 'all',
'name' => __('SNMP credentials', 'fusioninventory'),
'forcegroupby' => true,
'massiveaction' => false,
'joinparams' => [
'beforejoin' => [
'table' => "glpi_plugin_fusioninventory_ipranges_configsecurities",
'joinparams' => [
'jointype' => 'child',
],
],
],
];
return $tab;
}
/**
* Define tabs to display on form page
*
* @param array $options
* @return array containing the tabs name
*/
function defineTabs($options = []) {
$ong = [];
$this->addDefaultFormTab($ong);
$ong[$this->getType().'$task'] = _n('Task', 'Tasks', 2);
$this->addStandardTab('Log', $ong, $options);
return $ong;
}
/**
* Display the content of the tab
*
* @param object $item
* @param integer $tabnum number of the tab to display
* @param integer $withtemplate 1 if is a template form
* @return boolean
*/
static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) {
if ($tabnum == 'task') {
$pfTask = new PluginFusioninventoryTask();
$pfTask->showJobLogs();
return true;
}
return false;
}
/**
* Display form
*
* @param integer $id
* @param array $options
* @return true
*/
function showForm($id, $options = []) {
$this->initForm($id, $options);
$this->showFormHeader($options);
echo "<tr class='tab_bg_1'>";
echo "<td align='center' colspan='2'>" . __('Name') . "</td>";
echo "<td align='center' colspan='2'>";
Html::autocompletionTextField($this, 'name');
echo "</td>";
echo "</tr>";
echo "<tr class='tab_bg_1'>";
echo "<td align='center' colspan='2'>" . __('Start of IP range', 'fusioninventory') . "</td>";
echo "<td align='center' colspan='2'>";
if (empty($this->fields["ip_start"])) {
$this->fields["ip_start"] = "...";
}
$ipexploded = explode(".", $this->fields["ip_start"]);
$i = 0;
foreach ($ipexploded as $ipnum) {
if ($ipnum > 255) {
$ipexploded[$i] = '';
}
$i++;
}
echo "<input type='text' value='".$ipexploded[0].
"' name='ip_start0' id='ip_start0' size='3' maxlength='3' >.";
echo "<input type='text' value='".$ipexploded[1].
"' name='ip_start1' id='ip_start1' size='3' maxlength='3' >.";
echo "<input type='text' value='".$ipexploded[2].
"' name='ip_start2' id='ip_start2' size='3' maxlength='3' >.";
echo "<input type='text' value='".$ipexploded[3].
"' name='ip_start3' id='ip_start3' size='3' maxlength='3' >";
echo "</td>";
echo "</tr>";
echo "<tr class='tab_bg_1'>";
echo "<td align='center' colspan='2'>" . __('End of IP range', 'fusioninventory') . "</td>";
echo "<td align='center' colspan='2'>";
unset($ipexploded);
if (empty($this->fields["ip_end"])) {
$this->fields["ip_end"] = "...";
}
$ipexploded = explode(".", $this->fields["ip_end"]);
$j = 0;
foreach ($ipexploded as $ipnum) {
if ($ipnum > 255) {
$ipexploded[$j] = '';
}
$j++;
}
echo "<script type='text/javascript'>
function test(id) {
if (document.getElementById('ip_end' + id).value == '') {
if (id == 3) {
document.getElementById('ip_end' + id).value = '254';
} else {
document.getElementById('ip_end' + id).value = ".
"document.getElementById('ip_start' + id).value;
}
}
}
</script>";
echo "<input type='text' value='".$ipexploded[0].
"' name='ip_end0' id='ip_end0' size='3' maxlength='3' onfocus='test(0)'>.";
echo "<input type='text' value='".$ipexploded[1].
"' name='ip_end1' id='ip_end1' size='3' maxlength='3' onfocus='test(1)'>.";
echo "<input type='text' value='".$ipexploded[2].
"' name='ip_end2' id='ip_end2' size='3' maxlength='3' onfocus='test(2)'>.";
echo "<input type='text' value='".$ipexploded[3].
"' name='ip_end3' id='ip_end3' size='3' maxlength='3' onfocus='test(3)'>";
echo "</td>";
echo "</tr>";
echo "<tr class='tab_bg_1'>";
if (Session::isMultiEntitiesMode()) {
echo "<td align='center' colspan='2'>".Entity::getTypeName(1)."</td>";
echo "<td align='center' colspan='2'>";
Dropdown::show('Entity',
['name'=>'entities_id',
'value'=>$this->fields["entities_id"]]);
echo "</td>";
} else {
echo "<td colspan='2'></td>";
}
echo "</tr>";
$this->showFormButtons($options);
return true;
}
/**
* Check if IP is valid
*
* @param array $a_input array of IPs
* @return boolean
*/
function checkip($a_input) {
$count = 0;
foreach ($a_input as $num=>$value) {
if (strstr($num, "ip_")) {
if (($value>255) OR (!is_numeric($value)) OR strstr($value, ".")) {
$count++;
$a_input[$num] = "<font color='#ff0000'>".$a_input[$num]."</font>";
}
}
}
if ($count == '0') {
return true;
} else {
Session::addMessageAfterRedirect("<font color='#ff0000'>".__('Bad IP', 'fusioninventory').
"</font><br/>".
__('Start of IP range', 'fusioninventory')." : ".
$a_input['ip_start0'].".".$a_input['ip_start1'].".".
$a_input['ip_start2'].".".$a_input['ip_start3']."<br/>".
__('End of IP range', 'fusioninventory')." : ".
$a_input['ip_end0'].".".$a_input['ip_end1'].".".
$a_input['ip_end2'].".".$a_input['ip_end3']);
return false;
}
}
/**
* Get ip in long format
*
* @param string $ip IP in format IPv4
* @return integer $int
*/
function getIp2long($ip) {
$int = ip2long($ip);
if ($int < 0) {
$int = sprintf("%u\n", ip2long($ip));
}
return $int;
}
/**
* After purge item, delete SNMP credentials linked to this ip range
*/
function post_purgeItem() {
$pfIPRange_ConfigSecurity = new PluginFusioninventoryIPRange_ConfigSecurity();
$a_data = getAllDataFromTable('glpi_plugin_fusioninventory_ipranges_configsecurities',
['plugin_fusioninventory_ipranges_id' => $this->fields['id']]);
foreach ($a_data as $data) {
$pfIPRange_ConfigSecurity->delete($data);
}
parent::post_deleteItem();
}
/**
* Get the massive actions for this object
*
* @param object|null $checkitem
* @return array list of actions
*/
function getSpecificMassiveActions($checkitem = null) {
$actions = [];
if (Session::haveRight("plugin_fusioninventory_task", UPDATE)) {
$actions['PluginFusioninventoryTask'.MassiveAction::CLASS_ACTION_SEPARATOR.'addtojob_target'] = __('Target a task', 'fusioninventory');
}
return $actions;
}
}

View File

@@ -0,0 +1,240 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage SNMP credentials associated with IP ranges.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage SNMP credentials associated with IP ranges.
*/
class PluginFusioninventoryIPRange_ConfigSecurity extends CommonDBRelation {
/**
* Itemtype for the first part of relation
*
* @var string
*/
static public $itemtype_1 = 'PluginFusioninventoryIPRange';
/**
* id field name for the first part of relation
*
* @var string
*/
static public $items_id_1 = 'plugin_fusioninventory_ipranges_id';
/**
* Restrict the first item to the current entity
*
* @var string
*/
static public $take_entity_1 = true;
/**
* Itemtype for the second part of relation
*
* @var string
*/
static public $itemtype_2 = 'PluginFusioninventoryConfigSecurity';
/**
* id field name for the second part of relation
*
* @var string
*/
static public $items_id_2 = 'plugin_fusioninventory_configsecurities_id';
/**
* Not restrict the second item to the current entity
*
* @var string
*/
static public $take_entity_2 = false;
/**
* Get the tab name used for item
*
* @param object $item the item object
* @param integer $withtemplate 1 if is a template form
* @return string name of the tab
*/
function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) {
if ($item->fields['id'] > 0) {
return __('Associated SNMP credentials', 'fusioninventory');
}
return '';
}
/**
* Display the content of the tab
*
* @param object $item
* @param integer $tabnum number of the tab to display
* @param integer $withtemplate 1 if is a template form
* @return true
*/
static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) {
$pfIPRange_ConfigSecurity = new self();
$pfIPRange_ConfigSecurity->showForm($item);
return true;
}
/**
* Get standard massive action forbidden (hide in massive action list)
*
* @return array
*/
function getForbiddenStandardMassiveAction() {
$forbidden = parent::getForbiddenStandardMassiveAction();
$forbidden[] = 'update';
return $forbidden;
}
/**
* Display form
*
* @param object $item
* @param array $options
* @return boolean
*/
function showForm(CommonDBTM $item, $options = []) {
$ID = $item->getField('id');
if ($item->isNewID($ID)) {
return false;
}
if (!$item->can($item->fields['id'], READ)) {
return false;
}
$rand = mt_rand();
$a_data = getAllDataFromTable('glpi_plugin_fusioninventory_ipranges_configsecurities',
['plugin_fusioninventory_ipranges_id' => $item->getID()],
false,
'`rank`');
$a_used = [];
foreach ($a_data as $data) {
$a_used[] = $data['plugin_fusioninventory_configsecurities_id'];
}
echo "<div class='firstbloc'>";
echo "<form name='iprange_configsecurity_form$rand' id='iprange_configsecurity_form$rand' method='post'
action='".Toolbox::getItemTypeFormURL('PluginFusioninventoryIPRange_ConfigSecurity')."' >";
echo "<table class='tab_cadre_fixe'>";
echo "<tr class='tab_bg_2'>";
echo "<th colspan='2'>".__('Add SNMP credentials')."</th>";
echo "</tr>";
echo "<tr class='tab_bg_2'>";
echo "<td>";
Dropdown::show('PluginFusioninventoryConfigSecurity', ['used' => $a_used]);
echo "</td>";
echo "<td>";
echo Html::hidden('plugin_fusioninventory_ipranges_id',
['value' => $item->getID()]);
echo "<input type='submit' name='add' value=\"".
_sx('button', 'Associate')."\" class='submit'>";
echo "</td>";
echo "</tr>";
echo "</table>";
Html::closeForm();
echo "</div>";
// Display list of auth associated with IP range
$rand = mt_rand();
echo "<div class='spaced'>";
Html::openMassiveActionsForm('mass'.__CLASS__.$rand);
$massiveactionparams = ['container' => 'mass'.__CLASS__.$rand];
Html::showMassiveActions($massiveactionparams);
echo "<table class='tab_cadre_fixe'>";
echo "<tr class='tab_bg_2'>";
echo "<th width='10'>".Html::getCheckAllAsCheckbox('mass'.__CLASS__.$rand)."</th>";
echo "<th>";
echo __('SNMP credentials', 'fusioninventory');
echo "</th>";
echo "<th>";
echo __('Version', 'fusioninventory');
echo "</th>";
echo "<th>";
echo __('By order of priority', 'fusioninventory');
echo "</th>";
echo "</tr>";
$pfConfigSecurity = new PluginFusioninventoryConfigSecurity();
foreach ($a_data as $data) {
echo "<tr class='tab_bg_2'>";
echo "<td>";
Html::showMassiveActionCheckBox(__CLASS__, $data["id"]);
echo "</td>";
echo "<td>";
$pfConfigSecurity->getFromDB($data['plugin_fusioninventory_configsecurities_id']);
echo $pfConfigSecurity->getLink();
echo "</td>";
echo "<td>";
echo $pfConfigSecurity->getSNMPVersion($pfConfigSecurity->fields['snmpversion']);
echo "</td>";
echo "<td>";
echo $data['rank'];
echo "</td>";
echo "</tr>";
}
echo "</table>";
$massiveactionparams['ontop'] =false;
Html::showMassiveActions($massiveactionparams);
echo "</div>";
return true;
}
}

View File

@@ -0,0 +1,302 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the extended information of a computer.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Common class to manage informations FI display on an asset
*/
class PluginFusioninventoryItem extends CommonDBTM {
/**
* The right name for this class
*
* @var string
*/
static $rightname = '';
/**
* The itemtype we are processing
*/
public $itemtype = '';
/**
* Get automatic inventory info for a computer
* @since 9.1+1.2
* @param integer $items_id the item ID to look for
* @return inventory computer infos or an empty array
*/
function hasAutomaticInventory($items_id) {
$fk = getForeignKeyFieldForItemType($this->itemtype);
$params = [$fk => $items_id];
if ($this->getFromDBByCrit($params)) {
return $this->fields;
} else {
return [];
}
}
/**
* Form to download the XML inventory file
*
* @param integer $items_id the item ID to look for
*/
function showDownloadInventoryFile($items_id) {
global $CFG_GLPI;
$folder = substr($items_id, 0, -1);
if (empty($folder)) {
$folder = '0';
}
$file_found = false;
//Check if the file exists with the .xml extension (new format)
$file = PLUGIN_FUSIONINVENTORY_XML_DIR;
$filename = $items_id.'.xml';
$file_shortname = strtolower($this->itemtype)."/".$folder."/".$filename;
$file .= $file_shortname;
if (!file_exists($file)) {
//The file doesn't exists, check without the extension (old format)
$file = PLUGIN_FUSIONINVENTORY_XML_DIR;
$filename = $items_id;
$file_shortname = strtolower($this->itemtype)."/".$folder."/".$filename;
$file .= $file_shortname;
if (file_exists($file)) {
$file_found = true;
}
} else {
$file_found = true;
}
if ($file_found) {
echo "<table class='tab_cadre_fixe'>";
echo "<tr class='tab_bg_1'>";
echo "<th>";
$url = Plugin::getWebDir('fusioninventory')."/front/send_inventory.php";
$url.= "?itemtype=".get_class($this)
."&function=sendXML&items_id=".$file_shortname."&filename=".$filename;
echo "<a href='$url' target='_blank'>";
$message = __('Download inventory file', 'fusioninventory');
echo "<img src=\"".$CFG_GLPI["root_doc"].
"/pics/icones/csv-dist.png\" alt='$message' title='$message'>";
echo "&nbsp;$message</a>";
echo "</th></tr></table>";
}
}
/**
* Display form
*
* @param CommonDBTM $item CommonDBTM instance
* @param array $options optional parameters to be used for display purpose
*/
function showForm(CommonDBTM $item, $options = []) {
Session::checkRight($this::$rightname, READ);
$fk = getForeignKeyFieldForItemType($this->itemtype);
$params = [$fk => $item->getID()];
if (!$this->getFromDBByCrit($params)) {
// Add in database if not exist
$_SESSION['glpi_plugins_fusinvsnmp_table']
= getTableForItemType($this->itemtype);
$ID_tn = $this->add($params);
$this->getFromDB($ID_tn);
}
// Form item informations
echo "<div align='center'>";
echo "<form method='post' name='snmp_form' id='snmp_form'
action=\"".$options['target']."\">";
echo "<table class='tab_cadre' cellpadding='5' width='950'>";
echo "<tr class='tab_bg_1'>";
echo "<th colspan='4'>";
echo __('SNMP information', 'fusioninventory');
echo "</th>";
echo "</tr>";
echo "<tr class='tab_bg_1'>";
echo "<td align='center'>";
echo __('Sysdescr', 'fusioninventory');
echo "</td>";
echo "<td>";
echo "<textarea name='sysdescr' cols='45' rows='5'>";
echo $this->fields['sysdescr'];
echo "</textarea>";
echo "</td><td>";
echo "<table><tr>";
echo "<td align='center'>";
echo __('Last inventory', 'fusioninventory');
echo "</td>";
echo "<td>";
echo Html::convDateTime(
$this->fields['last_fusioninventory_update']);
echo "</td>";
echo "</tr>";
echo "<tr class='tab_bg_1'>";
echo "</td>";
echo "<td align='center'>".__('SNMP authentication', 'fusioninventory')."</td>";
echo "<td align='center'>";
PluginFusioninventoryConfigSecurity::authDropdown(
$this->fields["plugin_fusioninventory_configsecurities_id"]);
echo "</td>";
echo "</tr>";
echo "</table></td></tr>";
$this->addMoreInfos($options);
echo "<tr class='tab_bg_2 center'>";
echo "<td colspan='4'>";
echo "<div align='center'>";
echo Html::hidden('id', ['value' => $this->fields[$fk]]);
echo Html::submit(__('Update'), ['name' => 'update']);
echo "</td>";
echo "</tr>";
echo "</table>";
Html::closeForm();
echo "</div>";
}
/**
* Add more info to the tab if needed
* This method is used for child classes to add more specific infos
* in the form
* @since 9.2+2.0
*
* @param array $options display options
*/
function addMoreInfos($options = []) {
}
/**
* Get a FI class instance representing an itemtype
* @since 9.2+2.0
*
* @param array $options display options
*/
static function getFIItemClassInstance($itemtype) {
switch ($itemtype) {
case 'Computer':
return new PluginFusioninventoryInventoryComputerComputer();
case 'NetworkEquipment':
return new PluginFusioninventoryNetworkEquipment();
case 'Printer':
return new PluginFusioninventoryPrinter();
default:
// Toolbox::logDebug("getFIItemClassInstance: there's no FI class for itemtype $itemtype");
return false;
}
}
/**
* Computer uptime
* @since 9.2+2.0
*
* @param string $uptime the uptime as read from the XML file
* @return array an which contains values for day, hour, minute and second
*/
public function computeUptime($uptime) {
$day = 0;
$hour = 0;
$minute = 0;
$sec = 0;
$ticks = 0;
if (strstr($uptime, "days")) {
list($day, $hour, $minute, $sec, $ticks) = sscanf($uptime, "%d days, %d:%d:%d.%d");
} else if (strstr($uptime, "hours")) {
$day = 0;
list($hour, $minute, $sec, $ticks) = sscanf($uptime, "%d hours, %d:%d.%d");
} else if (strstr($uptime, "minutes")) {
$day = 0;
$hour = 0;
list($minute, $sec, $ticks) = sscanf($uptime, "%d minutes, %d.%d");
} else if ($uptime == "0") {
$day = 0;
$hour = 0;
$minute = 0;
$sec = 0;
} else {
list($hour, $minute, $sec, $ticks) = sscanf($uptime, "%d:%d:%d.%d");
$day = 0;
}
return [
'day' => $day,
'hour' => $hour,
'minute' => $minute,
'second' => $sec
];
}
/**
* Display uptime formatted in HTML
* @since 9.2+2.0
*
* @param string $uptime the uptime as read from the XML file
* @return string the uptime in a human readable format, formatted in HTML
*/
public function displayUptimeAsString($uptime) {
$uptime_values = $this->computeUptime($uptime);
$output = "<b>".$uptime_values['day']."</b> "
._n('Day', 'Days', $uptime_values['day'])." ";
$output.= "<b>".$uptime_values['hour']."</b> "
._n('Hour', 'Hours', $uptime_values['hour'])." ";
$output.= "<b>".$uptime_values['minute']."</b> "
._n('Minute', 'Minutes', $uptime_values['minute'])." ";
$output.=__('and');
$output.= "<b>".$uptime_values['second']."</b> "
.__('sec(s)', 'fusioninventory')." ";
return $output;
}
}

View File

@@ -0,0 +1,972 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the lock fields in itemtype.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author Vincent Mazzoni
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the lock fields in itemtype.
*/
class PluginFusioninventoryLock extends CommonDBTM{
/**
* The right name for this class
*
* @var string
*/
static $rightname = 'plugin_fusioninventory_lock';
/**
* Get name of this type by language of the user connected
*
* @param integer $nb number of elements
* @return string name of this type
*/
static function getTypeName($nb = 0) {
return _n('Lock', 'Locks', $nb);
}
/**
* Count number lock elements for item
*
* @param object $item
* @return integer
*/
static function countForLock(CommonGLPI $item) {
$pfLock = new self();
$a_data = current($pfLock->find(
['tablename' => $item->getTable(),
'items_id' => $item->fields['id']],
[], 1));
if (!is_array($a_data) || count($a_data) == 0) {
return 0;
}
return count(importArrayFromDB($a_data['tablefields']));
}
/**
* Get the tab name used for item
*
* @param object $item the item object
* @param integer $withtemplate 1 if is a template form
* @return string name of the tab
*/
function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) {
$items_id = $item->fields['id'];
$itemtype = $item->getType();
switch ($itemtype) {
case 'PluginFusioninventoryConfig':
return PluginFusioninventoryLock::getTypeName(2);
case 'NetworkEquipment':
$itemtype = 'networking';
default:
if (Session::haveRight(strtolower($itemtype), UPDATE)) {
if ($_SESSION['glpishow_count_on_tabs']) {
return self::createTabEntry(PluginFusioninventoryLock::getTypeName(2),
self::countForLock($item));
}
return PluginFusioninventoryLock::getTypeName(2);
}
}
return '';
}
/**
* Display the content of the tab
*
* @param object $item
* @param integer $tabnum number of the tab to display
* @param integer $withtemplate 1 if is a template form
* @return true
*/
static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) {
$pflock = new self();
if ($item->getType()=='PluginFusioninventoryConfig') {
echo "<table class='tab_cadre_fixe'>";
echo "<tr>";
echo "<td>";
$pflock->showFormItemtype('Computer');
echo "</td>";
echo "</tr>";
echo "<table class='tab_cadre_fixe'>";
echo "<tr>";
echo "<td>";
$pflock->showFormItemtype('Printer');
echo "</td>";
echo "</tr>";
echo "<table class='tab_cadre_fixe'>";
echo "<tr>";
echo "<td>";
$pflock->showFormItemtype('NetworkEquipment');
echo "</td>";
echo "</tr>";
echo "</table>";
return true;
}
if ($item->fields['id'] < 1) {
$pflock->showForm(Toolbox::getItemTypeFormURL('PluginFusioninventoryLock'),
$item->getType());
} else {
$pflock->showForm(Toolbox::getItemTypeFormURL('PluginFusioninventoryLock').'?id='.
$item->fields['id'],
$item->getType(), $item->fields['id']);
}
return true;
}
/**
* Display locks form for an item
*
* @todo check rights and entity
*
* @param string $p_target Target file.
* @param string $p_itemtype Class name.
* @param integer $p_items_id Line id.
* @return true
*/
function showForm($p_target, $p_itemtype, $p_items_id = 0) {
$can = 0;
$typeright = strtolower($p_itemtype);
if ($typeright == "networkequipment") {
$typeright = "networking";
}
if (Session::haveRight($typeright, UPDATE)) {
$can = 1;
}
$tableName = getTableForItemType($p_itemtype);
echo "<div width='50%'>";
$locked = PluginFusioninventoryLock::getLockFields($tableName, $p_items_id);
if (!count($locked)) {
$locked = [];
}
$colspan = '2';
if ($p_items_id > 0) {
$colspan = '3';
}
$item = new $p_itemtype;
if ($p_items_id == 0) {
$item->getEmpty();
} else {
$item->getFromDB($p_items_id);
}
if (!strstr($p_target, "ajax/dropdownMassiveAction.php")) {
echo "<br>";
echo "<form method='post' action='".$p_target."'>";
}
echo "<input type='hidden' name='id' value='$p_items_id'>";
echo "<input type='hidden' name='type' value='$p_itemtype'>";
echo "<table class='tab_cadre_fixe'>";
echo "<tr><th colspan='4'>".__('FusionInventory', 'fusioninventory')."</th></tr>";
echo "<tr><th>"._n('Field', 'Fields', 2)."</th>";
if ($p_items_id != '0') {
echo "<th>".__('Values GLPI', 'fusioninventory')."</th>";
echo "<th>".__('Values of last inventory', 'fusioninventory')."</th>";
}
echo "<th>"._n('Lock', 'Locks', 2, 'fusioninventory')."</th>";
echo "</tr>";
$checked = false;
$a_exclude = $this->excludeFields();
$serialized = $this->getSerializedInventoryArray($p_itemtype, $p_items_id);
$options = Search::getOptions($p_itemtype);
foreach ($item->fields as $key=>$val) {
$name = "";
$key_source = $key;
if (!in_array($key, $a_exclude)) {
if (in_array($key, $locked)) {
$checked = true;
} else {
$checked = false;
}
// Get name of field
$num = Search::getOptionNumber($p_itemtype, $key);
if (isset($options[$num]['name'])) {
$name = $options[$num]['name'];
} else {
// Get name by search in linkfields
foreach ($options as $opt) {
if (isset($opt['linkfield']) && $opt['linkfield'] == $key) {
$name = $opt['name'];
break;
}
}
}
$css_glpi_value = '';
if (isset($serialized[$key]) && $val != $serialized[$key]) {
$css_glpi_value = "class='tab_bg_1_2'";
}
// Get value of field
$val = $this->getValueForKey($val, $key);
echo "<tr class='tab_bg_1'>";
$table = getTableNameForForeignKeyField($key);
if ($name == "" && $table != "") {
$linkItemtype = getItemTypeForTable($table);
$class = new $linkItemtype();
$name = $class->getTypeName();
}
echo "<td>".$name."</td>";
if ($p_items_id != '0') {
// Current value of GLPI
echo "<td ".$css_glpi_value.">".$val."</td>";
// Value of last inventory
echo "<td>";
if (isset($serialized[$key_source])) {
echo $this->getValueForKey($serialized[$key_source], $key);
}
echo "</td>";
}
echo "<td align='center'>";
Html::showCheckbox(['name' => "lockfield_fusioninventory[$key_source]",
'checked' => $checked]);
echo "</td>";
echo "</tr>";
}
}
if ($p_items_id == '0') {
// add option selection for add theses lock filed or remove them
echo "<tr>";
echo "<th colspan='2'>".__('Job', 'fusioninventory')."</th>";
echo "<tr>";
echo "<tr class='tab_bg_1'>";
echo "<td>".__('Add locks', 'fusioninventory')."</td>";
echo "<td align='center'><input type='radio' name='actionlock' value='addLock' ".
"checked/></td>";
echo "</tr>";
echo "<tr class='tab_bg_1'>";
echo "<td>".__('Delete locks', 'fusioninventory')."</td>";
echo "<td align='center'><input type='radio' name='actionlock' value='deleteLock' /></td>";
echo "</tr>";
}
if ($can == '1') {
echo "<tr class='tab_bg_2'>";
echo "<td align='center' colspan='".($colspan + 1)."'>";
echo "<input class='submit' type='submit' name='unlock_field_fusioninventory'
value='" . __('Update') . "'>";
echo "</td>";
echo "</tr>";
}
echo "</table>";
if (!strstr($p_target, "ajax/dropdownMassiveAction.php")) {
Html::closeForm();
}
echo "</div>";
return true;
}
/**
* Display lock form for an itemtype
*
* @param string $itemtype
*/
function showFormItemtype($itemtype, $start_form = true, $show_button = true) {
$can = 0;
$typeright = strtolower($itemtype);
if ($typeright == "networkequipment") {
$typeright = "networking";
}
if (Session::haveRight($typeright, UPDATE)) {
$can = 1;
}
$tableName = getTableForItemType($itemtype);
echo "<div width='50%'>";
$locked = PluginFusioninventoryLock::getLockFields($tableName, 0);
if (!count($locked)) {
$locked = [];
}
$colspan = '2';
$item = new $itemtype;
$item->getEmpty();
if ($start_form) {
echo "<form method='post' action='".PluginFusioninventoryLock::getFormURL()."'>";
echo "<input type='hidden' name='id' value='0'>";
echo "<input type='hidden' name='type' value='$itemtype'>";
}
echo "<table class='tab_cadre_fixe'>";
echo "<tr>";
echo "<th colspan='2'>".$item->getTypeName(1)."</th>";
echo "</tr>";
echo "<tr><th>"._n('Field', 'Fields', 2)."</th>";
echo "<th>"._n('Lock', 'Locks', 2, 'fusioninventory')."</th>";
echo "</tr>";
$checked = false;
$a_exclude = $this->excludeFields();
$options = Search::getOptions($itemtype);
foreach ($item->fields as $key=>$val) {
$name = "";
$key_source = $key;
if (!in_array($key, $a_exclude)) {
if (in_array($key, $locked)) {
$checked = true;
} else {
$checked = false;
}
// Get name of field
$num = Search::getOptionNumber($itemtype, $key);
if (isset($options[$num]['name'])) {
$name = $options[$num]['name'];
} else {
//Get name by search in linkfields
foreach ($options as $opt) {
if (isset($opt['linkfield']) && $opt['linkfield'] == $key) {
$name = $opt['name'];
break;
}
}
}
// Get value of field
$val = $this->getValueForKey($val, $key);
echo "<tr class='tab_bg_1'>";
$table = getTableNameForForeignKeyField($key);
if ($name == "" && $table != "") {
$linkItemtype = getItemTypeForTable($table);
$class = new $linkItemtype();
$name = $class->getTypeName();
}
echo "<td>".$name."</td>";
echo "<td align='center'>";
Html::showCheckbox(['name' => "lockfield_fusioninventory[$key_source]",
'checked' => $checked]);
echo "</td>";
echo "</tr>";
}
}
if ($can == '1' && $show_button) {
echo "<tr class='tab_bg_2'>";
echo "<td align='center' colspan='".($colspan + 1)."'>";
echo Html::submit(__('Update'), ['name' => 'unlock_field_fusioninventory']);
echo "</td>";
echo "</tr>";
}
echo "</table>";
Html::closeForm();
echo "</div>";
}
/**
* Clean locks for an asset
*
* @param string $itemtype asset type
* @param int $items_id asset ID
* @return Nothing
* @since 0.90
*/
static function cleanForAsset($itemtype, $items_id) {
global $DB;
$DB->delete(
'glpi_plugin_fusioninventory_locks', [
'tablename' => getTableForItemType($itemtype),
'items_id' => $items_id
]
);
}
/**
* Unlock a field for a record.
*
* @todo check rights and entity
*
* @param string $p_table Table name.
* @param integer $p_items_id Line id.
* @param string $p_fieldToDel field to unlock.
*/
static function deleteInLockArray($p_table, $p_items_id, $p_fieldToDel) {
$pfLock = new PluginFusioninventoryLock();
$fieldsToLock = PluginFusioninventoryLock::getLockFields($p_table, $p_items_id);
if (count($fieldsToLock)) {
$fieldToDel=array_search($p_fieldToDel, $fieldsToLock);
if (isset($fieldsToLock[$fieldToDel])) {
unset ($fieldsToLock[$fieldToDel]);
}
if (count($fieldsToLock)) { // there are still locks
$fieldsToLock=array_values($fieldsToLock);
$a_lines = $pfLock->find(['tablename' => $p_table, 'items_id' => $p_items_id]);
$a_line = current($a_lines);
$pfLock->getFromDB($a_line['id']);
$input = [];
$input['id'] = $pfLock->fields['id'];
$input['tablefields'] = exportArrayToDB($fieldsToLock);
$pfLock->update($input);
} else { // no locks any more
$a_lines = $pfLock->find(['tablename' => $p_table, 'items_id' => $p_items_id]);
$a_line = current($a_lines);
$pfLock->getFromDB($a_line['id']);
$pfLock->delete($pfLock->fields);
}
}
}
/**
* Unlock a field for all records.
*
* @todo check rights and entity
*
* @global object $DB
* @param string $p_table Table name.
* @param string $p_fieldToDel field to unlock.
*/
static function deleteInAllLockArray($p_table, $p_fieldToDel) {
global $DB;
$query = "SELECT `items_id`
FROM `glpi_plugin_fusioninventory_locks`
WHERE `tablename`='".$p_table."'
AND `tablefields` LIKE '%".$p_fieldToDel."%';";
$result = $DB->query($query);
while ($data=$DB->fetchArray($result)) {
// TODO improve the lock deletion by transmiting the old locked fields to the
// deletion function
PluginFusioninventoryLock::deleteInLockArray($p_table, $data['items_id'], $p_fieldToDel);
}
}
/**
* Set lock fields for a record.
*
* @todo check rights and entity
*
* @global object $DB
* @param string $p_itemtype Table id.
* @param integer $p_items_id Line id.
* @param array $p_fieldsToLock Array of fields to lock.
* @param string $massiveaction
*
* @return boolean
*/
static function setLockArray($p_itemtype, $p_items_id, $p_fieldsToLock, $massiveaction = '') {
global $DB;
$success = false;
$pfl = new PluginFusioninventoryLock();
$tableName = getTableForItemType($p_itemtype);
$result = PluginFusioninventoryLock::getLock($tableName, $p_items_id);
if ($DB->numrows($result)) {
$a_lines = $pfl->find(['tablename' => $tableName, 'items_id' => $p_items_id]);
$a_line = current($a_lines);
$pfl->getFromDB($a_line['id']);
if ($massiveaction == 'addLock') {
$a_lockfieldsDB = importArrayFromDB($pfl->fields['tablefields']);
foreach ($p_fieldsToLock as $fieldtoadd) {
if (!in_array($fieldtoadd, $a_lockfieldsDB)) {
$a_lockfieldsDB[] = $fieldtoadd;
}
}
$pfl->fields['tablefields'] = exportArrayToDB($a_lockfieldsDB);
$success = $pfl->update($pfl->fields);
} else if ($massiveaction == 'deleteLock') {
$a_lockfieldsDB = importArrayFromDB($pfl->fields['tablefields']);
foreach ($p_fieldsToLock as $fieldtoadd) {
if (in_array($fieldtoadd, $a_lockfieldsDB)) {
$key = array_search($fieldtoadd, $a_lockfieldsDB);
unset($a_lockfieldsDB[$key]);
}
}
$pfl->fields['tablefields'] = exportArrayToDB($a_lockfieldsDB);
$success = $pfl->update($pfl->fields);
} else {
if (count($p_fieldsToLock)) { // old locks --> new locks
$pfl->fields['tablefields'] = exportArrayToDB($p_fieldsToLock);
$success = $pfl->update($pfl->fields);
} else { // old locks --> no locks any more
$success = $pfl->delete($pfl->fields);
}
}
} else if (count($p_fieldsToLock)) { // no locks --> new locks
$input = [];
$input['tablename'] = $tableName;
$input['items_id'] = $p_items_id;
$input['tablefields'] = exportArrayToDB($p_fieldsToLock);
$success = (bool) $pfl->add($input);
}
return $success;
}
/**
* Add lock fields for a record.
*
* @todo check rights and entity
*
* @global object $DB
* @param string $p_itemtype Table id.
* @param integer $p_items_id Line id.
* @param array $p_fieldsToLock Array of fields to lock.
*/
static function addLocks($p_itemtype, $p_items_id, $p_fieldsToLock) {
global $DB;
$tableName = getTableForItemType($p_itemtype);
$pfl = new PluginFusioninventoryLock();
$a_exclude = $pfl->excludeFields();
$p_fieldsToLock = array_diff($p_fieldsToLock, $a_exclude);
$result = PluginFusioninventoryLock::getLock($tableName, $p_items_id);
if ($DB->numrows($result)) {
$row = $DB->fetchAssoc($result);
$lockedFields = importArrayFromDB($row['tablefields']);
if (count(array_diff($p_fieldsToLock, $lockedFields))) { // old locks --> new locks
$p_fieldsToLock = array_merge($p_fieldsToLock, $lockedFields);
$a_lines = $pfl->find(['tablename' => $tableName, 'items_id' => $p_items_id]);
$a_line = current($a_lines);
$pfl->getFromDB($a_line['id']);
$pfl->fields['tablefields'] = exportArrayToDB($p_fieldsToLock);
$pfl->update($pfl->fields);
}
} else if (count($p_fieldsToLock)) { // no locks --> new locks
$input = [];
$input['tablename'] = $tableName;
$input['items_id'] = $p_items_id;
$input['tablefields'] = exportArrayToDB($p_fieldsToLock);
$pfl->add($input);
}
}
/**
* Get lock fields for a record.
*
* @todo check rights and entity
*
* @global object $DB
* @param string $p_table Table name.
* @param integer $p_items_id Line id.
* @return object
*/
static function getLock($p_table, $p_items_id) {
global $DB;
$query = "SELECT `id`, `tablefields`
FROM `glpi_plugin_fusioninventory_locks`
WHERE `tablename`='".$p_table."'
AND `items_id`='".$p_items_id."';";
$result = $DB->query($query);
return $result;
}
/**
* Get lock fields for a record.
*
* @todo check rights
*
* @global object $DB
* @param string $p_table Table name.
* @param integer $p_items_id Line id.
* @return array list of locked fields
*/
static function getLockFields($p_table, $p_items_id) {
global $DB;
$db_lock = $DB->fetchAssoc(PluginFusioninventoryLock::getLock($p_table, $p_items_id));
if ($db_lock !== null) {
$lock_fields = $db_lock["tablefields"];
$lock = importArrayFromDB($lock_fields);
} else {
$lock = [];
}
if ($p_items_id != 0) {
$db_lock = $DB->fetchAssoc(PluginFusioninventoryLock::getLock($p_table, 0));
if ($db_lock !== null) {
$lock_fields = $db_lock["tablefields"];
$lockItemtype = importArrayFromDB($lock_fields);
$lock = array_merge($lock, $lockItemtype);
}
}
return $lock;
}
/**
* convert an array resulting from many form checks (0=>on 2=>on 5=>on ...)
* into a classical array(0=>0 1=>2 2=>5 ...)
*
* @param array $p_checksArray checkbox array from form
* @return array
*/
static function exportChecksToArray($p_checksArray) {
$array = [];
foreach ($p_checksArray as $key => $value) {
if ($value > 0 || $value == "on") {
array_push($array, $key);
}
}
return $array;
}
/**
* Manage list of fields to exclude for lock
*
* @return array list of fields to exclude
*/
function excludeFields() {
$exclude = [];
$exclude[] = "id";
$exclude[] = "entities_id";
$exclude[] = "is_recursive";
$exclude[] = "date_mod";
$exclude[] = "date_creation";
$exclude[] = "is_deleted";
$exclude[] = "is_dynamic";
$exclude[] = "is_template";
$exclude[] = "template_name";
$exclude[] = "comment";
$exclude[] = "ticket_tco";
return $exclude;
}
/**
* Delete locks fields and get from lib value from last inventory
*
* @param object $item
*/
static function deleteLock($item) {
global $DB;
if ($item->fields['items_id'] == 0) {
return;
}
$pfLock = new PluginFusioninventoryLock();
$itemtype = getItemTypeForTable($item->fields['tablename']);
$items_id = $item->fields['items_id'];
$a_fieldList = [];
if ($item->fields['tablefields'] == $item->input['tablefields']) {
$a_fieldList = importArrayFromDB($item->fields['tablefields']);
} else {
$a_fieldListTemp = importArrayFromDB($item->fields['tablefields']);
$a_inputList = importArrayFromDB($item->input['tablefields']);
$a_diff = array_diff($a_fieldListTemp, $a_inputList);
$a_fieldList = [];
foreach ($a_diff as $value) {
if (in_array($value, $a_fieldListTemp)) {
$a_fieldList[] = $value;
}
}
}
// load general lock configuration
$generalLocks = PluginFusioninventoryLock::getLockFields($item->fields['tablename'], 0);
$a_fieldList = array_unique(array_merge($a_fieldList, $generalLocks));
//delete all lock case (no more lock)
if (!isset($item->updates)) {
$a_fieldList = [];
}
$item_device = new $itemtype();
$item_device->getFromDB($items_id);
$a_serialized = $pfLock->getSerializedInventoryArray($itemtype, $items_id);
foreach ($a_serialized as $key=>$value) {
if (!in_array($key, $a_fieldList)) {
$item_device->fields[$key] = $value;
}
}
$exclude = $pfLock->excludeFields();
foreach ($exclude as $key) {
if (isset($item_device->fields[$key])
&& $key != 'id') {
unset($item_device->fields[$key]);
}
}
$_SESSION['glpi_fusionionventory_nolock'] = true;
$item_device->update($item_device->fields);
unset($_SESSION['glpi_fusionionventory_nolock']);
}
/**
* Import OCS locks
*
* @global object $DB
*/
function importFromOcs() {
global $DB;
if ($DB->tableExists('glpi_ocslinks')) {
$sql = "SELECT * FROM `glpi_ocslinks`";
$result=$DB->query($sql);
while ($data=$DB->fetchArray($result)) {
$a_ocslocks = importArrayFromDB($data['computer_update']);
$a_fields = [];
foreach ($a_ocslocks as $field) {
if (!strstr($field, "_version")
AND $field != "date_mod") {
$a_fields[] = $field;
}
}
if (count($a_fields) > 0) {
$this->addLocks("Computer", $data['computers_id'], $a_fields);
}
}
}
}
/**
* Get serialized inventory and convert to array
*
* @param string $itemtype
* @param integer $items_id
* @return array
*/
function getSerializedInventoryArray($itemtype, $items_id) {
$item_extend = new PluginFusioninventoryLock();
if ($itemtype == 'Computer') {
$item_extend = new PluginFusioninventoryInventoryComputerComputer();
} else if ($itemtype == 'NetworkEquipment') {
$item_extend = new PluginFusioninventoryNetworkEquipment;
} else if ($itemtype == 'Printer') {
$item_extend = new PluginFusioninventoryPrinter();
}
if ($item_extend->getType() != 'PluginFusioninventoryLock') {
// Get device info + field 'serialized_inventory'
$a_lists = $item_extend->find([getForeignKeyFieldForItemType($itemtype) => $items_id], [], 1);
if (count($a_lists) == 1) {
$a_list = current($a_lists);
if (!empty($a_list['serialized_inventory'])) {
$serialized = unserialize(gzuncompress($a_list['serialized_inventory']));
return $serialized[$itemtype];
}
}
}
return [];
}
/**
* Get value for key
*
* @param string $val
* @param string $key
* @return string
*/
function getValueForKey($val, $key) {
if ((strstr($key, "_id")
|| ($key == 'is_ocs_import'))
AND $val == '0') {
$val = "";
}
$table = getTableNameForForeignKeyField($key);
if ($table != "") {
$linkItemtype = getItemTypeForTable($table);
$class = new $linkItemtype();
if (($val == "0") OR ($val == "")) {
$val = "";
} else {
$class->getFromDB($val);
$val = $class->getName();
}
}
return $val;
}
/**
* Display lock icon in main item form
*
* @param string $itemtype
*/
static function showLockIcon($itemtype) {
if (isset($_GET['id'])
&& $_GET['id'] > 0) {
$pfLock = new self();
$a_locks = $pfLock->getLockFields(getTableForItemType($itemtype), $_GET['id']);
foreach ($a_locks as $field) {
$js = '$("[name='.$field.']").closest("td").prev().toggleClass("lockfield", true);';
echo Html::scriptBlock($js);
}
}
}
/**
* Display form related to the massive action selected
*
* @param object $ma MassiveAction instance
* @return boolean
*/
static function showMassiveActionsSubForm(MassiveAction $ma) {
if ($ma->getAction() == 'manage_locks') {
//detect itemtype
$itemtype = str_replace("massform", "", $_POST['container']);
$pfil = new self;
$pfil->showForm($_SERVER["PHP_SELF"], $itemtype);
return true;
}
return false;
}
/**
* Execution code for massive action
*
* @param object $ma MassiveAction instance
* @param object $item item on which execute the code
* @param array $ids list of ID on which execute the code
*/
static function processMassiveActionsForOneItemtype(MassiveAction $ma, CommonDBTM $item,
array $ids) {
$itemtype = $item->getType();
switch ($ma->getAction()) {
case "manage_locks":
if ($itemtype == "NetworkEquipment"
|| $itemtype == "Printer"
|| $itemtype == "Computer") {
foreach ($ids as $key) {
if (isset($_POST["lockfield_fusioninventory"])
&& count($_POST["lockfield_fusioninventory"])) {
$tab=PluginFusioninventoryLock::exportChecksToArray($_POST["lockfield_fusioninventory"]);
//lock current item
if (PluginFusioninventoryLock::setLockArray($_POST['type'],
$key,
$tab,
$_POST['actionlock'])) {
//set action massive ok for this item
$ma->itemDone($item->getType(), $key, MassiveAction::ACTION_OK);
} else {
// KO
$ma->itemDone($item->getType(), $key, MassiveAction::ACTION_KO);
}
}
}
}
break;
}
}
/**
* Say if the field is locked
*
* @param array $a_lockable list of fields locked
* @param string $field field to check
* @return boolean
*/
static function isFieldLocked($a_lockable, $field) {
return in_array($field, $a_lockable);
}
static function showLocksForAnItem(CommonDBTM $item) {
$pflock = new self();
$itemtype = $item->getType();
if ($itemtype::canUpdate()) {
if ($item->getID() < 1) {
$pflock->showForm(Toolbox::getItemTypeFormURL(__CLASS__),
$item->getType());
} else {
$pflock->showForm(Toolbox::getItemTypeFormURL(__CLASS__).'?id='.
$item->getID(), $item->getType(), $item->getID());
}
}
return true;
}
}

View File

@@ -0,0 +1,83 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage extra debug in files.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage extra debug in files.
*/
class PluginFusioninventoryLogger {
/**
* Log when extra-debug is activated
*
* @param string $file
* @param string $message
*/
static function logIfExtradebug($file, $message) {
if (!PluginFusioninventoryConfig::isExtradebugActive()) {
return;
}
Toolbox::logInFile($file, $message);
}
/**
* log when extra-debug and debug mode is activated
*
* @param string $file
* @param string $message
*/
static function logIfExtradebugAndDebugMode($file, $message) {
if ($_SESSION['glpi_use_mode'] != Session::DEBUG_MODE) {
return;
}
self::logIfExtradebug($file, $message);
}
}

View File

@@ -0,0 +1,856 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the mapping of network equipment and
* printer.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author Vincent Mazzoni
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the mapping of network equipment and printer.
*/
class PluginFusioninventoryMapping extends CommonDBTM {
/**
* Get mapping
*
* @param string $p_itemtype Mapping itemtype
* @param string $p_name Mapping name
* @return array|false mapping fields or FALSE
*/
function get($p_itemtype, $p_name) {
$data = $this->find(['itemtype' => $p_itemtype, 'name' => $p_name], [], 1);
$mapping = current($data);
if (isset($mapping['id'])) {
return $mapping;
}
return false;
}
/**
* Add new mapping
*
* @global object $DB
* @param array $parm
*/
function set($parm) {
global $DB;
$data = current(getAllDataFromTable("glpi_plugin_fusioninventory_mappings",
['itemtype' => $parm['itemtype'], 'name' => $parm['name']]));
if (empty($data)) {
// Insert
$values = [
'itemtype' => $parm['itemtype'],
'name' => $parm['name'],
'table' => $parm['table'],
'tablefield' => $parm['tablefield'],
'locale' => $parm['locale']
];
if (isset($parm['shortlocale'])) {
$values['shortlocale'] = $parm['shortlocale'];
}
$DB->insert('glpi_plugin_fusioninventory_mappings', $values);
} else if ($data['table'] != $parm['table']
OR $data['tablefield'] != $parm['tablefield']
OR $data['locale'] != $parm['locale']) {
$data['table'] = $parm['table'];
$data['tablefield'] = $parm['tablefield'];
$data['locale'] = $parm['locale'];
if (isset($parm['shortlocale'])) {
$data['shortlocale'] = $parm['shortlocale'];
}
$this->update($data);
}
}
/**
* Get translation name of mapping
*
* @param array $mapping
* @return string
*/
function getTranslation ($mapping) {
switch ($mapping['locale']) {
case 1:
return __('networking > location', 'fusioninventory');
case 2:
return __('networking > firmware', 'fusioninventory');
case 3:
return __('networking > uptime', 'fusioninventory');
case 4:
return __('networking > port > mtu', 'fusioninventory');
case 5:
return __('networking > port > speed', 'fusioninventory');
case 6:
return __('networking > port > internal status', 'fusioninventory');
case 7:
return __('networking > ports > last change', 'fusioninventory');
case 8:
return __('networking > port > number of bytes entered', 'fusioninventory');
case 9:
return __('networking > port > number of bytes out', 'fusioninventory');
case 10:
return __('networking > port > number of input errors', 'fusioninventory');
case 11:
return __('networking > port > number of errors output', 'fusioninventory');
case 12:
return __('networking > CPU usage', 'fusioninventory');
case 13:
return __('networking > serial number', 'fusioninventory');
case 14:
return __('networking > port > connection status', 'fusioninventory');
case 15:
return __('networking > port > MAC address', 'fusioninventory');
case 16:
return __('networking > port > name', 'fusioninventory');
case 17:
return __('networking > model', 'fusioninventory');
case 18:
return __('networking > port > type', 'fusioninventory');
case 19:
return __('networking > VLAN', 'fusioninventory');
case 20:
return __('networking > name', 'fusioninventory');
case 21:
return __('networking > total memory', 'fusioninventory');
case 22:
return __('networking > free memory', 'fusioninventory');
case 23:
return __('networking > port > port description', 'fusioninventory');
case 24:
return __('printer > name', 'fusioninventory');
case 25:
return __('printer > model', 'fusioninventory');
case 26:
return __('printer > total memory', 'fusioninventory');
case 27:
return __('printer > serial number', 'fusioninventory');
case 28:
return __('printer > meter > total number of printed pages', 'fusioninventory');
case 29:
return __('printer > meter > number of printed black and white pages', 'fusioninventory');
case 30:
return __('printer > meter > number of printed color pages', 'fusioninventory');
case 31:
return __('printer > meter > number of printed monochrome pages', 'fusioninventory');
case 33:
return __('networking > port > duplex type', 'fusioninventory');
case 34:
return __('printer > consumables > black cartridge (%)', 'fusioninventory');
case 35:
return __('printer > consumables > photo black cartridge (%)', 'fusioninventory');
case 36:
return __('printer > consumables > cyan cartridge (%)', 'fusioninventory');
case 37:
return __('printer > consumables > yellow cartridge (%)', 'fusioninventory');
case 38:
return __('printer > consumables > magenta cartridge (%)', 'fusioninventory');
case 39:
return __('printer > consumables > light cyan cartridge (%)', 'fusioninventory');
case 40:
return __('printer > consumables > light magenta cartridge (%)', 'fusioninventory');
case 41:
return __('printer > consumables > photoconductor (%)', 'fusioninventory');
case 42:
return __('printer > consumables > black photoconductor (%)', 'fusioninventory');
case 43:
return __('printer > consumables > color photoconductor (%)', 'fusioninventory');
case 44:
return __('printer > consumables > cyan photoconductor (%)', 'fusioninventory');
case 45:
return __('printer > consumables > yellow photoconductor (%)', 'fusioninventory');
case 46:
return __('printer > consumables > magenta photoconductor (%)', 'fusioninventory');
case 47:
return __('printer > consumables > black transfer unit (%)', 'fusioninventory');
case 48:
return __('printer > consumables > cyan transfer unit (%)', 'fusioninventory');
case 49:
return __('printer > consumables > yellow transfer unit (%)', 'fusioninventory');
case 50:
return __('printer > consumables > magenta transfer unit (%)', 'fusioninventory');
case 51:
return __('printer > consumables > waste bin (%)', 'fusioninventory');
case 52:
return __('printer > consumables > four (%)', 'fusioninventory');
case 53:
return __('printer > consumables > cleaning module (%)', 'fusioninventory');
case 54:
return __('printer > meter > number of printed duplex pages', 'fusioninventory');
case 55:
return __('printer > meter > nomber of scanned pages', 'fusioninventory');
case 56:
return __('printer > location', 'fusioninventory');
case 57:
return __('printer > port > name', 'fusioninventory');
case 58:
return __('printer > port > MAC address', 'fusioninventory');
case 59:
return __('printer > consumables > black cartridge (max ink)', 'fusioninventory');
case 60:
return __('printer > consumables > black cartridge (remaining ink )', 'fusioninventory');
case 61:
return __('printer > consumables > cyan cartridge (max ink)', 'fusioninventory');
case 62:
return __('printer > consumables > cyan cartridge (remaining ink)', 'fusioninventory');
case 63:
return __('printer > consumables > yellow cartridge (max ink)', 'fusioninventory');
case 64:
return __('printer > consumables > yellow cartridge (remaining ink)', 'fusioninventory');
case 65:
return __('printer > consumables > magenta cartridge (max ink)', 'fusioninventory');
case 66:
return __('printer > consumables > magenta cartridge (remaining ink)', 'fusioninventory');
case 67:
return __('printer > consumables > light cyan cartridge (max ink)', 'fusioninventory');
case 68:
return __('printer > consumables > light cyan cartridge (remaining ink)', 'fusioninventory');
case 69:
return __('printer > consumables > light magenta cartridge (max ink)', 'fusioninventory');
case 70:
return __('printer > consumables > light magenta cartridge (remaining ink)', 'fusioninventory');
case 71:
return __('printer > consumables > photoconductor (max ink)', 'fusioninventory');
case 72:
return __('printer > consumables > photoconductor (remaining ink)', 'fusioninventory');
case 73:
return __('printer > consumables > black photoconductor (max ink)', 'fusioninventory');
case 74:
return __('printer > consumables > black photoconductor (remaining ink)', 'fusioninventory');
case 75:
return __('printer > consumables > color photoconductor (max ink)', 'fusioninventory');
case 76:
return __('printer > consumables > color photoconductor (remaining ink)', 'fusioninventory');
case 77:
return __('printer > consumables > cyan photoconductor (max ink)', 'fusioninventory');
case 78:
return __('printer > consumables > cyan photoconductor (remaining ink)', 'fusioninventory');
case 79:
return __('printer > consumables > yellow photoconductor (max ink)', 'fusioninventory');
case 80:
return __('printer > consumables > yellow photoconductor (remaining ink)', 'fusioninventory');
case 81:
return __('printer > consumables > magenta photoconductor (max ink)', 'fusioninventory');
case 82:
return __('printer > consumables > magenta photoconductor (remaining ink)', 'fusioninventory');
case 83:
return __('printer > consumables > black transfer unit (max ink)', 'fusioninventory');
case 84:
return __('printer > consumables > black transfer unit (remaining ink)', 'fusioninventory');
case 85:
return __('printer > consumables > cyan transfer unit (max ink)', 'fusioninventory');
case 86:
return __('printer > consumables > cyan transfer unit (remaining ink)', 'fusioninventory');
case 87:
return __('printer > consumables > yellow transfer unit (max ink)', 'fusioninventory');
case 88:
return __('printer > consumables > yellow transfer unit (remaining ink)', 'fusioninventory');
case 89:
return __('printer > consumables > magenta transfer unit (max ink)', 'fusioninventory');
case 90:
return __('printer > consumables > magenta transfer unit (remaining ink)', 'fusioninventory');
case 91:
return __('printer > consumables > waste bin (max ink)', 'fusioninventory');
case 92:
return __('printer > consumables > waste bin (remaining ink)', 'fusioninventory');
case 93:
return __('printer > consumables > four (max ink)', 'fusioninventory');
case 94:
return __('printer > consumables > four (remaining ink)', 'fusioninventory');
case 95:
return __('printer > consumables > cleaning module (max ink)', 'fusioninventory');
case 96:
return __('printer > consumables > cleaning module (remaining ink)', 'fusioninventory');
case 97:
return __('printer > port > type', 'fusioninventory');
case 98:
return __('printer > consumables > maintenance kit (max)', 'fusioninventory');
case 99:
return __('printer > consumables > maintenance kit (remaining)', 'fusioninventory');
case 400:
return __('printer > consumables > maintenance kit (%)', 'fusioninventory');
case 401:
return __('networking > CPU user', 'fusioninventory');
case 402:
return __('networking > CPU system', 'fusioninventory');
case 403:
return __('networking > contact', 'fusioninventory');
case 404:
return __('networking > comments', 'fusioninventory');
case 405:
return __('printer > contact', 'fusioninventory');
case 406:
return __('printer > comments', 'fusioninventory');
case 407:
return __('printer > port > IP address', 'fusioninventory');
case 408:
return __('networking > port > index number', 'fusioninventory');
case 409:
return __('networking > Address CDP', 'fusioninventory');
case 410:
return __('networking > Port CDP', 'fusioninventory');
case 411:
return __('networking > port > trunk/tagged', 'fusioninventory');
case 412:
return __('networking > MAC address filters (dot1dTpFdbAddress)', 'fusioninventory');
case 413:
return __('networking > Physical addresses in memory (ipNetToMediaPhysAddress)', 'fusioninventory');
case 414:
return __('networking > instances de ports (dot1dTpFdbPort)', 'fusioninventory');
case 415:
return __('networking > numéro de ports associé id du port (dot1dBasePortIfIndex)');
case 416:
return __('printer > port > index number', 'fusioninventory');
case 417:
return __('networking > MAC address', 'fusioninventory');
case 418:
return __('printer > Inventory number', 'fusioninventory');
case 419:
return __('networking > Inventory number', 'fusioninventory');
case 420:
return __('printer > manufacturer', 'fusioninventory');
case 421:
return __('networking > IP addresses', 'fusioninventory');
case 422:
return __('networking > PVID (port VLAN ID)', 'fusioninventory');
case 423:
return __('printer > meter > total number of printed pages (print)', 'fusioninventory');
case 424:
return __('printer > meter > number of printed black and white pages (print)', 'fusioninventory');
case 425:
return __('printer > meter > number of printed color pages (print)', 'fusioninventory');
case 426:
return __('printer > meter > total number of printed pages (copy)', 'fusioninventory');
case 427:
return __('printer > meter > number of printed black and white pages (copy)', 'fusioninventory');
case 428:
return __('printer > meter > number of printed color pages (copy)', 'fusioninventory');
case 429:
return __('printer > meter > total number of printed pages (fax)', 'fusioninventory');
case 430:
return __('networking > port > vlan', 'fusioninventory');
case 435:
return __('networking > CDP remote sysdescr', 'fusioninventory');
case 436:
return __('networking > CDP remote id', 'fusioninventory');
case 437:
return __('networking > CDP remote model device', 'fusioninventory');
case 438:
return __('networking > LLDP remote sysdescr', 'fusioninventory');
case 439:
return __('networking > LLDP remote id', 'fusioninventory');
case 440:
return __('networking > LLDP remote port description', 'fusioninventory');
case 104:
return __('MTU', 'fusioninventory');
case 105:
return __('Speed');
case 106:
return __('Internal status', 'fusioninventory');
case 107:
return __('Last Change', 'fusioninventory');
case 108:
return __('Number of received bytes', 'fusioninventory');
case 109:
return __('Number of outgoing bytes', 'fusioninventory');
case 110:
return __('Number of input errors', 'fusioninventory');
case 111:
return __('Number of output errors', 'fusioninventory');
case 112:
return __('CPU usage', 'fusioninventory');
case 114:
return __('Connection');
case 115:
return __('Internal MAC address', 'fusioninventory');
case 116:
return __('Name');
case 117:
return __('Model');
case 118:
return __('Type');
case 119:
return __('VLAN');
case 120:
return __('Alias', 'fusioninventory');
case 128:
return __('Total number of printed pages', 'fusioninventory');
case 129:
return __('Number of printed black and white pages', 'fusioninventory');
case 130:
return __('Number of printed color pages', 'fusioninventory');
case 131:
return __('Number of printed monochrome pages', 'fusioninventory');
case 133:
return __('Matte black cartridge', 'fusioninventory');
case 134:
return __('Black cartridge', 'fusioninventory');
case 135:
return __('Photo black cartridge', 'fusioninventory');
case 136:
return __('Cyan cartridge', 'fusioninventory');
case 137:
return __('Yellow cartridge', 'fusioninventory');
case 138:
return __('Magenta cartridge', 'fusioninventory');
case 139:
return __('Light cyan cartridge', 'fusioninventory');
case 140:
return __('Light magenta cartridge', 'fusioninventory');
case 141:
return __('Photoconductor', 'fusioninventory');
case 142:
return __('Black photoconductor', 'fusioninventory');
case 143:
return __('Color photoconductor', 'fusioninventory');
case 144:
return __('Cyan photoconductor', 'fusioninventory');
case 145:
return __('Yellow photoconductor', 'fusioninventory');
case 146:
return __('Magenta photoconductor', 'fusioninventory');
case 147:
return __('Black transfer unit', 'fusioninventory');
case 148:
return __('Cyan transfer unit', 'fusioninventory');
case 149:
return __('Yellow transfer unit', 'fusioninventory');
case 150:
return __('Magenta transfer unit', 'fusioninventory');
case 151:
return __('Waste bin', 'fusioninventory');
case 152:
return __('Four', 'fusioninventory');
case 153:
return __('Cleaning module', 'fusioninventory');
case 154:
return __('Number of pages printed duplex', 'fusioninventory');
case 155:
return __('Number of scanned pages', 'fusioninventory');
case 156:
return __('Maintenance kit', 'fusioninventory');
case 157:
return __('Black toner', 'fusioninventory');
case 158:
return __('Cyan toner', 'fusioninventory');
case 159:
return __('Magenta toner', 'fusioninventory');
case 160:
return __('Yellow toner', 'fusioninventory');
case 161:
return __('Black drum', 'fusioninventory');
case 162:
return __('Cyan drum', 'fusioninventory');
case 163:
return __('Magenta drum', 'fusioninventory');
case 164:
return __('Yellow drum', 'fusioninventory');
case 165:
return __('Many informations grouped', 'fusioninventory');
case 166:
return __('Black toner 2', 'fusioninventory');
case 167:
return __('Black toner Utilisé', 'fusioninventory');
case 168:
return __('Black toner Restant', 'fusioninventory');
case 169:
return __('Cyan toner Max', 'fusioninventory');
case 170:
return __('Cyan toner Utilisé', 'fusioninventory');
case 171:
return __('Cyan toner Restant', 'fusioninventory');
case 172:
return __('Magenta toner Max', 'fusioninventory');
case 173:
return __('Magenta toner Utilisé', 'fusioninventory');
case 174:
return __('Magenta toner Restant', 'fusioninventory');
case 175:
return __('Yellow toner Max', 'fusioninventory');
case 176:
return __('Yellow toner Utilisé', 'fusioninventory');
case 177:
return __('Yellow toner Restant', 'fusioninventory');
case 178:
return __('Black drum Max', 'fusioninventory');
case 179:
return __('Black drum Utilisé', 'fusioninventory');
case 180:
return __('Black drum Restant', 'fusioninventory');
case 181:
return __('Cyan drum Max', 'fusioninventory');
case 182:
return __('Cyan drum Utilisé', 'fusioninventory');
case 183:
return __('Cyan drumRestant', 'fusioninventory');
case 184:
return __('Magenta drum Max', 'fusioninventory');
case 185:
return __('Magenta drum Utilisé', 'fusioninventory');
case 186:
return __('Magenta drum Restant', 'fusioninventory');
case 187:
return __('Yellow drum Max', 'fusioninventory');
case 188:
return __('Yellow drum Utilisé', 'fusioninventory');
case 189:
return __('Yellow drum Restant', 'fusioninventory');
case 190:
return __('Waste bin Max', 'fusioninventory');
case 191:
return __('Waste bin Utilisé', 'fusioninventory');
case 192:
return __('Waste bin Restant', 'fusioninventory');
case 193:
return __('Maintenance kit Max', 'fusioninventory');
case 194:
return __('Maintenance kit Utilisé', 'fusioninventory');
case 195:
return __('Maintenance kit Restant', 'fusioninventory');
case 196:
return __('Grey ink cartridge', 'fusioninventory');
case 197:
return __('Paper roll in inches', 'fusioninventory');
case 198:
return __('Paper roll in centimeters', 'fusioninventory');
case 199:
return __('Transfer kit Max', 'fusioninventory');
case 200:
return __('Transfer kit used', 'fusioninventory');
case 201:
return __('Transfer kit remaining', 'fusioninventory');
case 202:
return __('Fuser kit', 'fusioninventory');
case 203:
return __('Fuser kit max', 'fusioninventory');
case 204:
return __('Fuser kit used', 'fusioninventory');
case 205:
return __('Fuser kit remaining', 'fusioninventory');
case 206:
return __('Gloss Enhancer ink cartridge', 'fusioninventory');
case 207:
return __('Blue ink cartridge', 'fusioninventory');
case 208:
return __('Green ink cartridge', 'fusioninventory');
case 209:
return __('Red ink cartridge', 'fusioninventory');
case 210:
return __('Chromatic Red ink cartridge', 'fusioninventory');
case 211:
return __('Light grey ink cartridge', 'fusioninventory');
case 212:
return __('Transfer kit', 'fusioninventory');
case 1423:
return __('Total number of printed pages (print)', 'fusioninventory');
case 1424:
return __('Number of printed black and white pages (print)', 'fusioninventory');
case 1425:
return __('Number of printed color pages (print)', 'fusioninventory');
case 1426:
return __('Total number of printed pages (copy)', 'fusioninventory');
case 1427:
return __('Number of printed black and white pages (copy)', 'fusioninventory');
case 1428:
return __('Number of printed color pages (copy)', 'fusioninventory');
case 1429:
return __('Total number of printed pages (fax)', 'fusioninventory');
case 1434:
return __('Total number of large printed pages', 'fusioninventory');
}
return $mapping['name'];
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,119 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the agent modules.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author Vincent Mazzoni
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the agent modules.
*/
class PluginFusioninventoryModule extends CommonDBTM {
/**
* Get all installed modules
*
* @param boolean $p_inactive Show inactive modules
* @return array
*/
static function getAll($p_inactive = false) {
$plugin = new Plugin();
if ($p_inactive) {
return $plugin->find(['state' => [1, 4], 'directory' => ['LIKE', 'fusinv%']]);
} else {
return $plugin->find(['state' => 1, 'directory' => ['LIKE', 'fusinv%']]);
}
}
/**
* Get module id or fusioninventory plugin id
*
* @param string $p_name the module name
* @return integer|false plugin id or FALSE if module is not active or not a
* fusioninventory module
*/
static function getModuleId($p_name) {
$index = false;
if (!isset($_SESSION['glpi_plugins'])) {
return $index;
}
if ($p_name == 'fusioninventory') {
$index = array_search($p_name, $_SESSION['glpi_plugins']);
if (!$index) {
$plugin = new Plugin();
$data = $plugin->find(['directory' => $p_name]);
if (count($data)) {
$fields = current($data);
$index = $fields['id'];
}
}
}
return $index;
}
/**
* Get module name
*
* @param integer $p_id the module id
* @return string|false false if module is not active or not a fusioninventory module
*/
static function getModuleName($p_id) {
if (isset($_SESSION['glpi_plugins'][$p_id])) {
if ((substr($_SESSION['glpi_plugins'][$p_id], 0, 6) == 'fusinv')
OR ($_SESSION['glpi_plugins'][$p_id] == 'fusioninventory')) {
return $_SESSION['glpi_plugins'][$p_id];
} else {
return false;
}
} else {
return false;
}
}
}

View File

@@ -0,0 +1,409 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage network discovery prepare the task and give
* the configuration to the agent.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access this file directly");
}
/**
* Manage network discovery prepare the task and give the configuration to the
* agent.
*/
class PluginFusioninventoryNetworkdiscovery extends PluginFusioninventoryCommunication {
/**
* Prepare network discovery.
* Get all devices and put in taskjobstat each task for each device for each
* agent
*
* @param integer $taskjobs_id
* @return string
*/
function prepareRun($taskjobs_id) {
$pfTask = new PluginFusioninventoryTask();
$pfTaskjob = new PluginFusioninventoryTaskjob();
$pfTaskjoblog = new PluginFusioninventoryTaskjoblog();
$pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
$pfAgentmodule = new PluginFusioninventoryAgentmodule();
$pfIPRange = new PluginFusioninventoryIPRange();
$pfAgent = new PluginFusioninventoryAgent();
$uniqid = uniqid();
$pfTaskjob->getFromDB($taskjobs_id);
$pfTask->getFromDB($pfTaskjob->fields['plugin_fusioninventory_tasks_id']);
$communication = $pfTask->fields['communication'];
//list all iprange
$a_iprange = importArrayFromDB($pfTaskjob->fields['definition']);
$count_ip = 0;
$a_iprangelist = [];
$a_subnet_nbip = [];
foreach ($a_iprange as $iprange) {
$iprange_id = current($iprange);
$a_iprangelist[] = $iprange_id;
$pfIPRange->getFromDB($iprange_id);
$s = $pfIPRange->getIp2long($pfIPRange->fields['ip_start']);
$e = $pfIPRange->getIp2long($pfIPRange->fields['ip_end']);
$a_subnet_nbip[$iprange_id] = $e-$s;
$count_ip += $e-$s;
}
//list all agents
$a_agent = importArrayFromDB($pfTaskjob->fields['action']);
$dynagent = 0;
$a_agentlist = [];
foreach ($a_agent as $agent) {
$agent_id = current($agent);
if ($agent_id == '.1') {
$dynagent = 1;
} else if ($agent_id == '.2') {
$dynagent = 2;
} else {
// Detect if agent exists
if ($pfAgent->getFromDB($agent_id)) {
if ($pfTask->fields['communication'] == 'pull') {
$a_agentlist[$agent_id] = 1;
} else {
if ($pfTaskjob->isAgentAlive('1', $agent_id)) {
$a_agentlist[$agent_id] = 1;
}
}
}
}
}
if ($dynagent == '1') {
$a_agents = $pfAgentmodule->getAgentsCanDo('NETWORKDISCOVERY');
foreach ($a_agents as $data) {
if (($count_ip / 10) >= count($a_agentlist)) {
$pfAgent->getFromDB($data['id']);
$a_ip = $pfAgent->getIPs();
foreach ($a_ip as $ip) {
if ($pfTask->fields['communication'] == 'push') {
if ($pfTaskjob->isAgentAlive('1', $data['id'])) {
$a_agentlist[$data['id']] = 1;
}
} else if ($pfTask->fields['communication'] == 'pull') {
$a_agentlist[$data['id']] = 1;
}
}
}
}
}
if ($dynagent == '2') {
// Dynamic with subnet
$pfSnmpinventory = new PluginFusioninventoryNetworkinventory();
$taskvalid = 0;
foreach ($a_subnet_nbip as $iprange_id=>$nbips) {
//$maxagentpossible = $nbips/10;
$pfIPRange->getFromDB($iprange_id);
$a_agentListComplete = [];
$a_agentList = $pfSnmpinventory->getAgentsSubnet($nbips, "push", "",
$pfIPRange->fields['ip_start'],
$pfIPRange->fields['ip_end']);
if (isset($a_agentList)) {
$a_agentListComplete = array_merge($a_agentListComplete, $a_agentList);
}
if (!isset($a_agentListComplete) or empty($a_agentListComplete)) {
$a_input = [];
$a_input['plugin_fusioninventory_taskjobs_id'] = $taskjobs_id;
$a_input['plugin_fusioninventory_agents_id'] = 0;
$a_input['state'] = 1;
$a_input['itemtype'] = 'PluginFusioninventoryIPRange';
$a_input['items_id'] = $iprange_id;
$a_input['uniqid'] = $uniqid;
$a_input['execution_id'] = $task->fields['execution_id'];
$Taskjobstates_id = $pfTaskjobstate->add($a_input);
//Add log of taskjob
$a_input['plugin_fusioninventory_taskjobstates_id'] = $Taskjobstates_id;
$a_input['state'] = 7;
$a_input['date'] = date("Y-m-d H:i:s");
$pfTaskjoblog->add($a_input);
$pfTaskjobstate->changeStatusFinish($Taskjobstates_id,
0,
'PluginFusioninventoryIPRange',
1,
"Unable to find agent to run this job");
$input_taskjob = [];
$input_taskjob['id'] = $pfTaskjob->fields['id'];
//$input_taskjob['status'] = 1;
$pfTaskjob->update($input_taskjob);
} else {
$s = $pfIPRange->getIp2long($pfIPRange->fields['ip_start']);
$e = $pfIPRange->getIp2long($pfIPRange->fields['ip_end']);
$nbIpAgent = ceil(($e-$s) / count($a_agentListComplete));
$iptimes = 0;
foreach ($a_agentListComplete as $agent_id) {
$_SESSION['glpi_plugin_fusioninventory']['agents'][$agent_id] = 1;
//Add jobstate and put status (waiting on server = 0)
$a_input = [];
$a_input['plugin_fusioninventory_taskjobs_id'] = $taskjobs_id;
$a_input['state'] = 0;
$a_input['plugin_fusioninventory_agents_id'] = $agent_id;
$a_input['itemtype'] = 'PluginFusioninventoryIPRange';
$a_input['uniqid'] = $uniqid;
$a_input['execution_id'] = $task->fields['execution_id'];
$a_input['items_id'] = $iprange_id;
if (($iptimes + $nbIpAgent) > ($e-$s)) {
$a_input['specificity'] = $iptimes."-".($e-$s);
} else {
$a_input['specificity'] = $iptimes."-".($iptimes + $nbIpAgent);
}
$taskvalid++;
$Taskjobstates_id = $pfTaskjobstate->add($a_input);
//Add log of taskjob
$a_input['plugin_fusioninventory_taskjobstates_id'] = $Taskjobstates_id;
$a_input['state'] = 7;
$a_input['date'] = date("Y-m-d H:i:s");
$pfTaskjoblog->add($a_input);
unset($a_input['state']);
$iptimes += $nbIpAgent + 1;
if (($iptimes) >= ($e-$s+1)) {
break;
}
$input_taskjob = [];
$input_taskjob['id'] = $pfTaskjob->fields['id'];
$input_taskjob['status'] = 1;
$pfTaskjob->update($input_taskjob);
}
}
}
if ($taskvalid == "0") {
$pfTaskjob->reinitializeTaskjobs($pfTaskjob->fields['plugin_fusioninventory_tasks_id']);
}
// *** Add jobstate
} else if (count($a_agentlist) == 0) {
$a_input = [];
$a_input['plugin_fusioninventory_taskjobs_id'] = $taskjobs_id;
$a_input['state'] = 1;
$a_input['plugin_fusioninventory_agents_id'] = 0;
$a_input['itemtype'] = 'PluginFusioninventoryIPRange';
$a_input['items_id'] = 0;
$a_input['uniqid'] = $uniqid;
$a_input['execution_id'] = $task->fields['execution_id'];
$Taskjobstates_id = $pfTaskjobstate->add($a_input);
//Add log of taskjob
$a_input['plugin_fusioninventory_taskjobstates_id'] = $Taskjobstates_id;
$a_input['state'] = 7;
$a_input['date'] = date("Y-m-d H:i:s");
$pfTaskjoblog->add($a_input);
$pfTaskjobstate->changeStatusFinish($Taskjobstates_id,
0,
'PluginFusioninventoryIPRange',
1,
"Unable to find agent to run this job");
$input_taskjob = [];
$input_taskjob['id'] = $pfTaskjob->fields['id'];
//$input_taskjob['status'] = 1;
$pfTaskjob->update($input_taskjob);
} else {
$iptimes = 0;
$nbIpadded = 0;
$break = 0;
$numberIpByAgent = ceil($count_ip / (count($a_agentlist)));
$a_iprangelistTmp = $a_iprangelist;
$ip_id = array_shift($a_iprangelistTmp);
foreach ($a_agentlist as $agent_id => $ip) {
//Add jobstate and put status (waiting on server = 0)
$a_input = [];
$a_input['plugin_fusioninventory_taskjobs_id'] = $taskjobs_id;
$a_input['state'] = 0;
$a_input['plugin_fusioninventory_agents_id'] = $agent_id;
$a_input['itemtype'] = 'PluginFusioninventoryIPRange';
$a_input['uniqid'] = $uniqid;
$a_input['execution_id'] = $task->fields['execution_id'];
// $nbIpAgent = $numberIpByAgent;
$nbIpadded = 0;
foreach ($a_iprangelist as $iprange_id) {
if ($ip_id == $iprange_id) {
$pfIPRange->getFromDB($iprange_id);
$s = $pfIPRange->getIp2long($pfIPRange->fields['ip_start']);
$e = $pfIPRange->getIp2long($pfIPRange->fields['ip_end']);
if ($communication == "push") {
$_SESSION['glpi_plugin_fusioninventory']['agents'][$agent_id] = 1;
}
$a_input['items_id'] = $iprange_id;
$nbIpAgent = $numberIpByAgent - $nbIpadded;
if (($iptimes + $nbIpAgent) > ($e-$s)) {
$a_input['specificity'] = $iptimes."-".($e-$s);
$nbIpadded = ($e-$s) - $iptimes;
$ip_id = array_shift($a_iprangelistTmp);
$iptimes = 0;
} else {
$a_input['specificity'] = $iptimes."-".($iptimes + $nbIpAgent);
$iptimes += $nbIpAgent+1;
$nbIpadded = 0;
$break = 1;
}
$Taskjobstates_id = $pfTaskjobstate->add($a_input);
//Add log of taskjob
$a_input['plugin_fusioninventory_taskjobstates_id'] = $Taskjobstates_id;
$a_input['state'] = 7;
$a_input['date'] = date("Y-m-d H:i:s");
$pfTaskjoblog->add($a_input);
unset($a_input['state']);
}
}
$input_taskjob = [];
$input_taskjob['id'] = $pfTaskjob->fields['id'];
$input_taskjob['status'] = 1;
$pfTaskjob->update($input_taskjob);
}
}
return $uniqid;
}
/**
* When agent contact server, this function send job data to agent
*
* @param object $jobstate PluginFusioninventoryTaskjobstate instance
* @return string
*/
function run($jobstate) {
$pfAgent = new PluginFusioninventoryAgent();
$pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
$pfTaskjob = new PluginFusioninventoryTaskjob();
$pfTaskjoblog = new PluginFusioninventoryTaskjoblog();
$pfIPRange = new PluginFusioninventoryIPRange();
$pfToolbox = new PluginFusioninventoryToolbox();
$pfConfig = new PluginFusioninventoryConfig();
$pfAgent->getFromDB($jobstate->fields['plugin_fusioninventory_agents_id']);
$sxml_option = $this->message->addChild('OPTION');
$sxml_option->addChild('NAME', 'NETDISCOVERY');
$sxml_param = $sxml_option->addChild('PARAM');
// Use general config when threads number is set to 0 on the agent
if ($pfAgent->fields["threads_networkdiscovery"] == 0) {
$sxml_param->addAttribute('THREADS_DISCOVERY',
$pfConfig->getValue('threads_networkdiscovery'));
} else {
$sxml_param->addAttribute('THREADS_DISCOVERY',
$pfAgent->fields["threads_networkdiscovery"]);
}
// Use general config when timeout is set to 0 on the agent
if ($pfAgent->fields["timeout_networkdiscovery"] == 0) {
$sxml_param->addAttribute('TIMEOUT',
$pfConfig->getValue('timeout_networkdiscovery'));
} else {
$sxml_param->addAttribute('TIMEOUT',
$pfAgent->fields["timeout_networkdiscovery"]);
}
$sxml_param->addAttribute('PID', $jobstate->fields['id']);
$changestate = 0;
$taskjobstatedatas = $jobstate->fields;
$sxml_rangeip = $sxml_option->addChild('RANGEIP');
$pfTaskjob->getFromDB($taskjobstatedatas['plugin_fusioninventory_taskjobs_id']);
$pfTaskjobstate->getFromDB($taskjobstatedatas['id']);
$pfIPRange->getFromDB($taskjobstatedatas['items_id']);
$sxml_rangeip->addAttribute('ID', $pfIPRange->fields['id']);
if (!is_null($pfTaskjobstate->fields['specificity'])) {
$a_split = explode("-", $pfTaskjobstate->fields['specificity']);
$first_ip = $pfIPRange->getIp2long($pfIPRange->fields["ip_start"]);
$last_ip = long2ip($first_ip + $a_split[1]);
$first_ip = long2ip($first_ip + $a_split[0]);
if ($first_ip != '0.0.0.0'
&& $last_ip != '0.0.0.0') {
$sxml_rangeip->addAttribute('IPSTART', $first_ip);
$sxml_rangeip->addAttribute('IPEND', $last_ip);
}
} else {
$sxml_rangeip->addAttribute('IPSTART', $pfIPRange->fields["ip_start"]);
$sxml_rangeip->addAttribute('IPEND', $pfIPRange->fields["ip_end"]);
}
$sxml_rangeip->addAttribute('ENTITY', $pfIPRange->fields["entities_id"]);
if ($changestate == '0') {
$pfTaskjobstate->changeStatus($pfTaskjobstate->fields['id'], 1);
$pfTaskjoblog->addTaskjoblog($pfTaskjobstate->fields['id'],
'0',
'PluginFusioninventoryAgent',
'1',
$pfAgent->fields["threads_networkdiscovery"].' threads '.
$pfAgent->fields["timeout_networkdiscovery"].' timeout'
);
$changestate = $pfTaskjobstate->fields['id'];
} else {
$pfTaskjobstate->changeStatusFinish($pfTaskjobstate->fields['id'],
$taskjobstatedatas['items_id'],
$taskjobstatedatas['itemtype'],
0,
"Merged with ".$changestate);
}
$pfIPRange_ConfigSecurity = new PluginFusioninventoryIPRange_ConfigSecurity();
$a_auths = $pfIPRange_ConfigSecurity->find(
['plugin_fusioninventory_ipranges_id' => $pfIPRange->fields['id']],
['rank']);
foreach ($a_auths as $dataAuth) {
$pfToolbox->addAuth($sxml_option, $dataAuth['plugin_fusioninventory_configsecurities_id']);
}
return $this->message;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,846 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage network inventory task jobs.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access this file directly");
}
/**
* Manage network inventory task jobs.
*/
class PluginFusioninventoryNetworkinventory extends PluginFusioninventoryCommunication {
/**
* Get all devices and put in taskjobstate each task for each device for
* each agent
*
* @global object $DB
* @param integer $taskjobs_id
* @return string
*/
function prepareRun($taskjobs_id) {
global $DB;
$pfTask = new PluginFusioninventoryTask();
$pfTaskjob = new PluginFusioninventoryTaskjob();
$pfTaskjoblog = new PluginFusioninventoryTaskjoblog();
$pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
$pfIPRange = new PluginFusioninventoryIPRange();
$pfAgent = new PluginFusioninventoryAgent();
$a_specificity = [];
$a_specificity['DEVICE'] = [];
$uniqid = uniqid();
$pfTaskjob->getFromDB($taskjobs_id);
$pfTask->getFromDB($pfTaskjob->fields['plugin_fusioninventory_tasks_id']);
$NetworkEquipment = new NetworkEquipment();
$NetworkPort = new NetworkPort();
/*
* * Different possibilities :
* IP RANGE
* NetworkEquipment
* Printer
*
* We will count total number of devices to query
*/
// get all snmpauth
$a_snmpauth = getAllDataFromTable("glpi_plugin_fusioninventory_configsecurities");
// get items_id by type
$a_iprange = [];
$a_NetworkEquipment = [];
$a_Printer = [];
$communication = $pfTask->fields['communication'];
$a_definition = importArrayFromDB($pfTaskjob->fields['definition']);
foreach ($a_definition as $datas) {
$itemtype = key($datas);
$items_id = current($datas);
switch ($itemtype) {
case 'PluginFusioninventoryIPRange':
$a_iprange[] = $items_id;
break;
case 'NetworkEquipment':
$query = "SELECT `glpi_networkequipments`.`id` AS `gID`,
`glpi_ipaddresses`.`name` AS `gnifaddr`,
`plugin_fusioninventory_configsecurities_id`,
FROM `glpi_networkequipments`
LEFT JOIN `glpi_plugin_fusioninventory_networkequipments`
ON `networkequipments_id`=`glpi_networkequipments`.`id`
LEFT JOIN `glpi_networkports`
ON `glpi_networkports`.`items_id`=`glpi_networkequipments`.`id`
AND `glpi_networkports`.`itemtype`='NetworkEquipment'
LEFT JOIN `glpi_networknames`
ON `glpi_networknames`.`items_id`=`glpi_networkports`.`id`
AND `glpi_networknames`.`itemtype`='NetworkPort'
LEFT JOIN `glpi_ipaddresses`
ON `glpi_ipaddresses`.`items_id`=`glpi_networknames`.`id`
AND `glpi_ipaddresses`.`itemtype`='NetworkName'
WHERE `glpi_networkequipments`.`is_deleted`='0'
AND `plugin_fusioninventory_configsecurities_id`!='0'
AND `glpi_networkequipments`.`id` = '".$items_id."'
AND `glpi_ipaddresses`.`name`!=''
LIMIT 1";
$result=$DB->query($query);
while ($data=$DB->fetchArray($result)) {
if (isset($a_snmpauth[$data['plugin_fusioninventory_configsecurities_id']])) {
$input = [];
$input['TYPE'] = 'NETWORKING';
$input['ID'] = $data['gID'];
$input['IP'] = $data['gnifaddr'];
$input['AUTHSNMP_ID'] = $data['plugin_fusioninventory_configsecurities_id'];
$a_specificity['DEVICE']['NetworkEquipment'.$data['gID']] = $input;
$a_NetworkEquipment[] = $items_id;
}
}
break;
case 'Printer':
$query = "SELECT `glpi_printers`.`id` AS `gID`,
`glpi_ipaddresses`.`name` AS `gnifaddr`,
`plugin_fusioninventory_configsecurities_id`,
FROM `glpi_printers`
LEFT JOIN `glpi_plugin_fusioninventory_printers`
ON `printers_id`=`glpi_printers`.`id`
LEFT JOIN `glpi_networkports`
ON `glpi_networkports`.`items_id`=`glpi_printers`.`id`
AND `glpi_networkports`.`itemtype`='Printer'
LEFT JOIN `glpi_networknames`
ON `glpi_networknames`.`items_id`=`glpi_networkports`.`id`
AND `glpi_networknames`.`itemtype`='NetworkPort'
LEFT JOIN `glpi_ipaddresses`
ON `glpi_ipaddresses`.`items_id`=`glpi_networknames`.`id`
AND `glpi_ipaddresses`.`itemtype`='NetworkName'
WHERE `glpi_printers`.`is_deleted`=0
AND `plugin_fusioninventory_configsecurities_id`!='0'
AND `glpi_printers`.`id` = '".$items_id."'
AND `glpi_ipaddresses`.`name`!=''
LIMIT 1";
$result=$DB->query($query);
while ($data=$DB->fetchArray($result)) {
if (isset($a_snmpauth[$data['plugin_fusioninventory_configsecurities_id']])) {
$input = [];
$input['TYPE'] = 'PRINTER';
$input['ID'] = $data['gID'];
$input['IP'] = $data['gnifaddr'];
$input['AUTHSNMP_ID'] = $data['plugin_fusioninventory_configsecurities_id'];
$a_specificity['DEVICE']['Printer'.$data['gID']] = $input;
$a_Printer[] = $items_id;
}
}
break;
}
}
// Get all devices on each iprange
foreach ($a_iprange as $items_id) {
$pfIPRange->getFromDB($items_id);
// Search NetworkEquipment
$query = "SELECT `glpi_networkequipments`.`id` AS `gID`,
`glpi_ipaddresses`.`name` AS `gnifaddr`,
`plugin_fusioninventory_configsecurities_id`,
FROM `glpi_networkequipments`
LEFT JOIN `glpi_plugin_fusioninventory_networkequipments`
ON `networkequipments_id`=`glpi_networkequipments`.`id`
LEFT JOIN `glpi_networkports`
ON `glpi_networkports`.`items_id`=`glpi_networkequipments`.`id`
AND `glpi_networkports`.`itemtype`='NetworkEquipment'
LEFT JOIN `glpi_networknames`
ON `glpi_networknames`.`items_id`=`glpi_networkports`.`id`
AND `glpi_networknames`.`itemtype`='NetworkPort'
LEFT JOIN `glpi_ipaddresses`
ON `glpi_ipaddresses`.`items_id`=`glpi_networknames`.`id`
AND `glpi_ipaddresses`.`itemtype`='NetworkName'
WHERE `glpi_networkequipments`.`is_deleted`='0'
AND `plugin_fusioninventory_configsecurities_id`!='0'";
if ($pfIPRange->fields['entities_id'] != '-1') {
$entities = "(".$this->fields['entities_id'];
foreach (getAncestorsOf("glpi_entities", $pfIPRange->fields['entities_id']) as $parent) {
$entities .= ",$parent";
}
$entities .= ")";
$query .= " AND `glpi_networkequipments`.`entities_id` IN ".
$entities." ";
}
$query .= " AND inet_aton(`glpi_ipaddresses`.`name`)
BETWEEN inet_aton('".$pfIPRange->fields['ip_start']."')
AND inet_aton('".$pfIPRange->fields['ip_end']."') ";
$query .= " GROUP BY `glpi_networkequipments`.`id`";
$result=$DB->query($query);
while ($data=$DB->fetchArray($result)) {
if (isset($a_snmpauth[$data['plugin_fusioninventory_configsecurities_id']])) {
$input = [];
$input['TYPE'] = 'NETWORKING';
$input['ID'] = $data['gID'];
$input['IP'] = $data['gnifaddr'];
$input['AUTHSNMP_ID'] = $data['plugin_fusioninventory_configsecurities_id'];
$a_specificity['DEVICE']['NetworkEquipment'.$data['gID']] = $input;
$a_NetworkEquipment[] = $data['gID'];
}
}
// Search Printer
$query = "SELECT `glpi_printers`.`id` AS `gID`,
`glpi_ipaddresses`.`name` AS `gnifaddr`,
`plugin_fusioninventory_configsecurities_id`,
FROM `glpi_printers`
LEFT JOIN `glpi_plugin_fusioninventory_printers`
ON `printers_id`=`glpi_printers`.`id`
LEFT JOIN `glpi_networkports`
ON `glpi_networkports`.`items_id`=`glpi_printers`.`id`
AND `glpi_networkports`.`itemtype`='Printer'
LEFT JOIN `glpi_networknames`
ON `glpi_networknames`.`items_id`=`glpi_networkports`.`id`
AND `glpi_networknames`.`itemtype`='NetworkPort'
LEFT JOIN `glpi_ipaddresses`
ON `glpi_ipaddresses`.`items_id`=`glpi_networknames`.`id`
AND `glpi_ipaddresses`.`itemtype`='NetworkName'
WHERE `glpi_printers`.`is_deleted`=0
AND `plugin_fusioninventory_configsecurities_id`!='0'";
if ($pfIPRange->fields['entities_id'] != '-1') {
$entities = "(".$this->fields['entities_id'];
foreach (getAncestorsOf("glpi_entities", $pfIPRange->fields['entities_id']) as $parent) {
$entities .= ",$parent";
}
$entities .= ")";
$query .= "AND `glpi_printers`.`entities_id` IN ".$entities." ";
}
$query .= " AND inet_aton(`glpi_ipaddresses`.`name`)
BETWEEN inet_aton('".$pfIPRange->fields['ip_start']."')
AND inet_aton('".$pfIPRange->fields['ip_end']."') ";
$query .= " GROUP BY `glpi_printers`.`id`";
$result=$DB->query($query);
while ($data=$DB->fetchArray($result)) {
if (isset($a_snmpauth[$data['plugin_fusioninventory_configsecurities_id']])) {
$input = [];
$input['TYPE'] = 'PRINTER';
$input['ID'] = $data['gID'];
$input['IP'] = $data['gnifaddr'];
$input['AUTHSNMP_ID'] = $data['plugin_fusioninventory_configsecurities_id'];
$a_specificity['DEVICE']['Printer'.$data['gID']] = $input;
$a_Printer[] = $data['gID'];
}
}
}
$count_device = count($a_NetworkEquipment) + count($a_Printer);
$a_actions = importArrayFromDB($pfTaskjob->fields['action']);
// *** For dynamic agent same subnet, it's an another management ***
if (strstr($pfTaskjob->fields['action'], '".2"')) {
$a_subnet = [];
$a_agentList = [];
$a_devicesubnet = [];
foreach ($a_NetworkEquipment as $items_id) {
$NetworkEquipment->getFromDB($items_id);
$a_ip = explode(".", $NetworkEquipment->fields['ip']);
$ip_subnet = $a_ip[0].".".$a_ip[1].".".$a_ip[2].".";
if (!isset($a_subnet[$ip_subnet])) {
$a_subnet[$ip_subnet] = 0;
}
$a_subnet[$ip_subnet]++;
$a_devicesubnet[$ip_subnet]['NetworkEquipment'][$items_id] = 1;
}
foreach ($a_Printer as $items_id) {
$a_ports = $NetworkPort->find(
['itemtype' => 'Printer',
'items_id' => $items_id,
['ip'] => ['!=', '127.0.0.1']]);
foreach ($a_ports as $a_port) {
$a_ip = explode(".", $a_port['ip']);
$ip_subnet = $a_ip[0].".".$a_ip[1].".".$a_ip[2].".";
if (!isset($a_subnet[$ip_subnet])) {
$a_subnet[$ip_subnet] = 0;
}
$a_subnet[$ip_subnet]++;
$a_devicesubnet[$ip_subnet]['Printer'][$items_id] = 1;
}
}
$a_agentsubnet = [];
foreach ($a_subnet as $subnet=>$num) {
$a_agentList = $this->getAgentsSubnet($num, $communication, $subnet);
if (!isset($a_agentList)) {
$a_agentsubnet[$subnet] = '';
} else {
$a_agentsubnet[$subnet] = $a_agentList;
}
}
$a_input = [];
$a_input['plugin_fusioninventory_taskjobs_id'] = $taskjobs_id;
$a_input['state'] = 1;
$a_input['plugin_fusioninventory_agents_id'] = 0;
$a_input['itemtype'] = '';
$a_input['items_id'] = 0;
$a_input['uniqid'] = $uniqid;
$a_input['execution_id'] = $task->fields['execution_id'];
$taskvalid = 0;
foreach ($a_agentsubnet as $subnet=>$a_agentList) {
if (!isset($a_agentList)
OR (isset($a_agentList)
&& is_array($a_agentList)
&& count($a_agentList) == '0')
OR (isset($a_agentList)
&& !is_array($a_agentList)
&& $a_agentList == '')) {
// No agent available for this subnet
for ($i=0; $i < 2; $i++) {
$itemtype = 'Printer';
if ($i == '0') {
$itemtype = 'NetworkEquipment';
}
if (isset($a_devicesubnet[$subnet][$itemtype])) {
foreach ($a_devicesubnet[$subnet][$itemtype] as $items_id=>$num) {
$a_input['itemtype'] = $itemtype;
$a_input['items_id'] = $items_id;
$a_input['specificity'] = exportArrayToDB(
$a_specificity['DEVICE'][$itemtype.$items_id]);
$Taskjobstates_id = $pfTaskjobstate->add($a_input);
//Add log of taskjob
$a_input['plugin_fusioninventory_taskjobstates_id'] = $Taskjobstates_id;
$a_input['state'] = 7;
$a_input['date'] = date("Y-m-d H:i:s");
$pfTaskjoblog->add($a_input);
$pfTaskjobstate->changeStatusFinish($Taskjobstates_id,
0,
'',
1,
"Unable to find agent to inventory ".
"this ".$itemtype);
$a_input['state'] = 1;
}
}
}
} else {
// add taskjobstate
$count_device_subnet = 0;
if (isset($a_devicesubnet[$subnet]['NetworkEquipment'])) {
$count_device_subnet += count($a_devicesubnet[$subnet]['NetworkEquipment']);
}
if (isset($a_devicesubnet[$subnet]['Printer'])) {
$count_device_subnet += count($a_devicesubnet[$subnet]['Printer']);
}
$nb_devicebyagent = ceil($count_device_subnet / count($a_agentList));
$nbagent = 0;
$agent_id = array_pop($a_agentList);
$a_input['state'] = 0;
for ($i=0; $i < 2; $i++) {
$itemtype = 'Printer';
if ($i == '0') {
$itemtype = 'NetworkEquipment';
}
if (isset($a_devicesubnet[$subnet][$itemtype])) {
foreach ($a_devicesubnet[$subnet][$itemtype] as $items_id=>$num) {
$a_input['itemtype'] = $itemtype;
$a_input['items_id'] = $items_id;
$a_input['specificity'] = exportArrayToDB(
$a_specificity['DEVICE'][$itemtype.$items_id]);
if ($nbagent == $nb_devicebyagent) {
$agent_id = array_pop($a_agentList);
$nbagent = 0;
}
$a_input['plugin_fusioninventory_agents_id'] = $agent_id;
$nbagent++;
$taskvalid++;
$Taskjobstates_id = $pfTaskjobstate->add($a_input);
//Add log of taskjob
$a_input['plugin_fusioninventory_taskjobstates_id'] = $Taskjobstates_id;
$a_input['state'] = 7;
$a_input['date'] = date("Y-m-d H:i:s");
$pfTaskjoblog->add($a_input);
unset($a_input['state']);
$a_input['plugin_fusioninventory_agents_id'] = 0;
$a_input['state'] = 0;
if ($communication == "push") {
$_SESSION['glpi_plugin_fusioninventory']['agents'][$agent_id] = 1;
}
}
}
}
}
}
if ($taskvalid == "0") {
$pfTaskjob->reinitializeTaskjobs($pfTaskjob->fields['plugin_fusioninventory_tasks_id']);
}
} else {
$a_agentList = [];
// *** Only agents not dynamic ***
if ((!strstr($pfTaskjob->fields['action'], '".1"'))
AND (!strstr($pfTaskjob->fields['action'], '".2"'))) {
$agent_require_model = 0;
foreach ($a_actions as $a_action) {
if ((!in_array('.1', $a_action))
AND (!in_array('.2', $a_action))) {
$agent_id = current($a_action);
if ($pfAgent->getFromDB($agent_id)) {
$agent_version = $pfAgent->getAgentVersion($agent_id);
if (strnatcmp($agent_version, '2.3.4') < 0) {
$agent_require_model = 1;
}
if ($communication == 'pull') {
$a_agentList[] = $agent_id;
} else {
if ($pfTaskjob->isAgentAlive('1', $agent_id)) {
$a_agentList[] = $agent_id;
}
}
}
}
}
} else if (strstr($pfTaskjob->fields['action'], '".1"')) {
/*
* Case : dynamic agent
*/
$a_agentList = $this->getAgentsSubnet($count_device, $communication);
}
/*
* Manage agents
*/
if (count($a_agentList) == 0) {
$a_input = [];
$a_input['plugin_fusioninventory_taskjobs_id'] = $taskjobs_id;
$a_input['state'] = 1;
$a_input['plugin_fusioninventory_agents_id'] = 0;
$a_input['itemtype'] = '';
$a_input['items_id'] = 0;
$a_input['uniqid'] = $uniqid;
$a_input['execution_id'] = $task->fields['execution_id'];
$Taskjobstates_id = $pfTaskjobstate->add($a_input);
//Add log of taskjob
$a_input['plugin_fusioninventory_taskjobstates_id'] = $Taskjobstates_id;
$a_input['state'] = 7;
$a_input['date'] = date("Y-m-d H:i:s");
$pfTaskjoblog->add($a_input);
$pfTaskjobstate->changeStatusFinish($Taskjobstates_id,
0,
'',
1,
"Unable to find agent to run this job");
$input_taskjob = [];
$input_taskjob['id'] = $pfTaskjob->fields['id'];
//$input_taskjob['status'] = 0;
$pfTaskjob->update($input_taskjob);
} else if ($count_device == 0) {
$a_input = [];
$a_input['plugin_fusioninventory_taskjobs_id'] = $taskjobs_id;
$a_input['state'] = 1;
$a_input['plugin_fusioninventory_agents_id'] = 0;
$a_input['itemtype'] = '';
$a_input['items_id'] = 0;
$a_input['uniqid'] = $uniqid;
$Taskjobstates_id = $pfTaskjobstate->add($a_input);
//Add log of taskjob
$a_input['plugin_fusioninventory_taskjobstates_id'] = $Taskjobstates_id;
$a_input['state'] = 7;
$a_input['date'] = date("Y-m-d H:i:s");
$pfTaskjoblog->add($a_input);
$pfTaskjobstate->changeStatusFinish($Taskjobstates_id,
0,
'',
0,
"No suitable devices to inventory");
$input_taskjob = [];
$input_taskjob['id'] = $pfTaskjob->fields['id'];
//$input_taskjob['status'] = 1;
$pfTaskjob->update($input_taskjob);
} else {
foreach ($a_agentList as $agent_id) {
//Add jobstate and put status (waiting on server = 0)
$a_input = [];
$a_input['plugin_fusioninventory_taskjobs_id'] = $taskjobs_id;
$a_input['state'] = 0;
$a_input['plugin_fusioninventory_agents_id'] = $agent_id;
$a_input['uniqid'] = $uniqid;
$a_input['execution_id'] = $task->fields['execution_id'];
$alternate = 0;
for ($d=0; $d < ceil($count_device / count($a_agentList)); $d++) {
if ((count($a_NetworkEquipment) + count($a_Printer)) > 0) {
$getdevice = "NetworkEquipment";
if ($alternate == "1") {
$getdevice = "Printer";
$alternate = 0;
} else {
$getdevice = "NetworkEquipment";
$alternate++;
}
if (count($a_NetworkEquipment) == '0') {
$getdevice = "Printer";
} else if (count($a_Printer) == '0') {
$getdevice = "NetworkEquipment";
}
$a_input['itemtype'] = $getdevice;
switch ($getdevice) {
case 'NetworkEquipment':
$a_input['items_id'] = array_pop($a_NetworkEquipment);
$a_input['specificity'] = exportArrayToDB(
$a_specificity['DEVICE']['NetworkEquipment'.$a_input['items_id']]);
break;
case 'Printer':
$a_input['items_id'] = array_pop($a_Printer);
$a_input['specificity'] = exportArrayToDB(
$a_specificity['DEVICE']['Printer'.$a_input['items_id']]);
break;
}
$Taskjobstates_id = $pfTaskjobstate->add($a_input);
//Add log of taskjob
$a_input['plugin_fusioninventory_taskjobstates_id'] = $Taskjobstates_id;
$a_input['state'] = 7;
$a_input['date'] = date("Y-m-d H:i:s");
$pfTaskjoblog->add($a_input);
unset($a_input['state']);
if ($communication == "push") {
$_SESSION['glpi_plugin_fusioninventory']['agents'][$agent_id] = 1;
}
}
}
}
$input_taskjob = [];
$input_taskjob['id'] = $pfTaskjob->fields['id'];
$input_taskjob['status'] = 1;
$pfTaskjob->update($input_taskjob);
}
}
return $uniqid;
}
/**
* When agent contact server, this function send datas to agent
*
* @param object $jobstate PluginFusioninventoryTaskjobstate instance
* @return SimpleXMLElement
*/
function run($jobstate) {
$pfAgent = new PluginFusioninventoryAgent();
$pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
$pfTaskjoblog = new PluginFusioninventoryTaskjoblog();
$pfConfigSecurity = new PluginFusioninventoryConfigSecurity();
$pfToolbox = new PluginFusioninventoryToolbox();
$pfConfig = new PluginFusioninventoryConfig();
$current = $jobstate;
$pfAgent->getFromDB($current->fields['plugin_fusioninventory_agents_id']);
$ip = current(PluginFusioninventoryToolbox::getIPforDevice(
$jobstate->fields['itemtype'],
$jobstate->fields['items_id']));
if ($ip == '') {
$pfTaskjobstate->changeStatusFinish($jobstate->fields['id'],
$jobstate->fields['items_id'],
$jobstate->fields['itemtype'],
1,
"Device have no ip");
} else {
$sxml_option = $this->message->addChild('OPTION');
$sxml_option->addChild('NAME', 'SNMPQUERY');
$sxml_param = $sxml_option->addChild('PARAM');
// Use general config when threads number is set to 0 on the agent
if ($pfAgent->fields["threads_networkinventory"] == 0) {
$sxml_param->addAttribute('THREADS_QUERY',
$pfConfig->getValue('threads_networkinventory'));
} else {
$sxml_param->addAttribute('THREADS_QUERY',
$pfAgent->fields["threads_networkinventory"]);
}
// Use general config when timeout is set to 0 on the agent
if ($pfAgent->fields["timeout_networkinventory"] == 0) {
$sxml_param->addAttribute('TIMEOUT',
$pfConfig->getValue('timeout_networkinventory'));
} else {
$sxml_param->addAttribute('TIMEOUT',
$pfAgent->fields["timeout_networkinventory"]);
}
$sxml_param->addAttribute('PID', $current->fields['id']);
$changestate = 0;
$taskjobstatedatas = $jobstate->fields;
$sxml_device = $sxml_option->addChild('DEVICE');
$a_extended = ['plugin_fusioninventory_configsecurities_id' => 0];
if ($jobstate->fields['itemtype'] == 'Printer') {
$sxml_device->addAttribute('TYPE', 'PRINTER');
$pfPrinter = new PluginFusioninventoryPrinter();
$a_extended = current($pfPrinter->find(['printers_id' => $jobstate->fields['items_id']], [], 1));
} else if ($jobstate->fields['itemtype'] == 'NetworkEquipment') {
$sxml_device->addAttribute('TYPE', 'NETWORKING');
$pfNetworkEquipment = new PluginFusioninventoryNetworkEquipment();
$a_extended = current($pfNetworkEquipment->find(['networkequipments_id' => $jobstate->fields['items_id']], [], 1));
}
$sxml_device->addAttribute('ID', $jobstate->fields['items_id']);
$sxml_device->addAttribute('IP', $ip);
$sxml_device->addAttribute('AUTHSNMP_ID', $a_extended['plugin_fusioninventory_configsecurities_id']);
if ($changestate == '0') {
$pfTaskjobstate->changeStatus($taskjobstatedatas['id'], 1);
$pfTaskjoblog->addTaskjoblog($taskjobstatedatas['id'],
'0',
'PluginFusioninventoryAgent',
'1',
$pfAgent->fields["threads_networkinventory"].' threads '.
$pfAgent->fields["timeout_networkinventory"].' timeout'
);
$changestate = $pfTaskjobstate->fields['id'];
} else {
$pfTaskjobstate->changeStatusFinish($taskjobstatedatas['id'],
$taskjobstatedatas['items_id'],
$taskjobstatedatas['itemtype'],
0,
"Merged with ".$changestate);
}
$snmpauthlist=$pfConfigSecurity->find();
if (count($snmpauthlist)) {
foreach ($snmpauthlist as $snmpauth) {
$pfToolbox->addAuth($sxml_option, $snmpauth['id']);
}
}
}
return $this->message;
}
/**
* Get agents by the subnet given
*
* @global object $DB
* @param integer $nb_computers
* @param string $communication
* @param string $subnet
* @param string $ipstart
* @param string $ipend
* @return array
*/
function getAgentsSubnet($nb_computers, $communication, $subnet = '', $ipstart = '', $ipend = '') {
global $DB;
$pfTaskjob = new PluginFusioninventoryTaskjob();
$pfAgentmodule = new PluginFusioninventoryAgentmodule();
// Number of computers min by agent
$nb_computerByAgentMin = 20;
$nb_agentsMax = ceil($nb_computers / $nb_computerByAgentMin);
$a_agentList = [];
if ($subnet != '') {
$subnet = " AND `glpi_ipaddresses`.`name` LIKE '".$subnet."%' ";
} else if ($ipstart != '' AND $ipend != '') {
$subnet = " AND ( INET_ATON(`glpi_ipaddresses`.`name`) > INET_ATON('".$ipstart."')
AND INET_ATON(`glpi_ipaddresses`.`name`) < INET_ATON('".$ipend."') ) ";
}
$a_agents = $pfAgentmodule->getAgentsCanDo('NETWORKINVENTORY');
$a_agentsid = [];
foreach ($a_agents as $a_agent) {
$a_agentsid[] = $a_agent['id'];
}
if (count($a_agentsid) == '0') {
return $a_agentList;
}
$where = " AND `glpi_plugin_fusioninventory_agents`.`ID` IN (";
$where .= implode(', ', $a_agentsid);
$where .= ")
AND `glpi_ipaddresses`.`name` != '127.0.0.1' ";
$query = "SELECT `glpi_plugin_fusioninventory_agents`.`id` as `a_id`,
`glpi_ipaddresses`.`name` as ip, token
FROM `glpi_plugin_fusioninventory_agents`
LEFT JOIN `glpi_networkports`
ON `glpi_networkports`.`items_id` = `glpi_plugin_fusioninventory_agents`.`computers_id`
LEFT JOIN `glpi_networknames`
ON `glpi_networknames`.`items_id`=`glpi_networkports`.`id`
AND `glpi_networknames`.`itemtype`='NetworkPort'
LEFT JOIN `glpi_ipaddresses`
ON `glpi_ipaddresses`.`items_id`=`glpi_networknames`.`id`
AND `glpi_ipaddresses`.`itemtype`='NetworkName'
LEFT JOIN `glpi_computers`
ON `glpi_computers`.`id` = `glpi_plugin_fusioninventory_agents`.`computers_id`
WHERE `glpi_networkports`.`itemtype`='Computer'
".$subnet."
".$where." ";
Toolbox::logInFile('NET', $query);
$result = $DB->query($query);
if ($result) {
while ($data=$DB->fetchArray($result)) {
if ($communication == 'push') {
if ($pfTaskjob->isAgentAlive("1", $data['a_id'])) {
if (!in_array($a_agentList, $data['a_id'])) {
$a_agentList[] = $data['a_id'];
if (count($a_agentList) >= $nb_agentsMax) {
return $a_agentList;
}
}
}
} else if ($communication == 'pull') {
if (!in_array($data['a_id'], $a_agentList)) {
$a_agentList[] = $data['a_id'];
if (count($a_agentList) > $nb_agentsMax) {
return $a_agentList;
}
}
}
}
}
return $a_agentList;
}
/**
* Get the devices have an IP in the IP range
*
* @global object $DB
* @param integer $ipranges_id
* @return array
*/
function getDevicesOfIPRange($ipranges_id) {
global $DB;
$devicesList = [];
$pfIPRange = new PluginFusioninventoryIPRange();
// get all snmpauth
$a_snmpauth = getAllDataFromTable("glpi_plugin_fusioninventory_configsecurities");
$pfIPRange->getFromDB($ipranges_id);
// Search NetworkEquipment
$query = "SELECT `glpi_networkequipments`.`id` AS `gID`,
`glpi_networkequipments`.`name` AS `gNAME`,
`glpi_ipaddresses`.`name` AS `gnifaddr`,
`plugin_fusioninventory_configsecurities_id`
FROM `glpi_networkequipments`
LEFT JOIN `glpi_plugin_fusioninventory_networkequipments`
ON `networkequipments_id`=`glpi_networkequipments`.`id`
LEFT JOIN `glpi_networkports`
ON `glpi_networkports`.`items_id`=`glpi_networkequipments`.`id`
AND `glpi_networkports`.`itemtype`='NetworkEquipment'
LEFT JOIN `glpi_networknames`
ON `glpi_networknames`.`items_id`=`glpi_networkports`.`id`
AND `glpi_networknames`.`itemtype`='NetworkPort'
LEFT JOIN `glpi_ipaddresses`
ON `glpi_ipaddresses`.`items_id`=`glpi_networknames`.`id`
AND `glpi_ipaddresses`.`itemtype`='NetworkName'
WHERE `glpi_networkequipments`.`is_deleted`='0'
AND `plugin_fusioninventory_configsecurities_id`!='0'";
if ($pfIPRange->fields['entities_id'] != '-1') {
$entities = "(".$pfIPRange->fields['entities_id'];
foreach (getAncestorsOf("glpi_entities", $pfIPRange->fields['entities_id']) as $parent) {
$entities .= ",$parent";
}
$entities .= ")";
$query .= " AND `glpi_networkequipments`.`entities_id` IN ".
$entities." ";
}
$query .= " AND inet_aton(`glpi_ipaddresses`.`name`)
BETWEEN inet_aton('".$pfIPRange->fields['ip_start']."')
AND inet_aton('".$pfIPRange->fields['ip_end']."') ";
$query .= " GROUP BY `glpi_networkequipments`.`id`";
$result=$DB->query($query);
while ($data=$DB->fetchArray($result)) {
if (isset($a_snmpauth[$data['plugin_fusioninventory_configsecurities_id']])) {
$devicesList[] = [
'NetworkEquipment' => $data['gID']
];
}
}
// Search Printer
$query = "SELECT `glpi_printers`.`id` AS `gID`,
`glpi_printers`.`name` AS `gNAME`,
`glpi_ipaddresses`.`name` AS `gnifaddr`,
`plugin_fusioninventory_configsecurities_id`
FROM `glpi_printers`
LEFT JOIN `glpi_plugin_fusioninventory_printers`
ON `printers_id`=`glpi_printers`.`id`
LEFT JOIN `glpi_networkports`
ON `glpi_networkports`.`items_id`=`glpi_printers`.`id`
AND `glpi_networkports`.`itemtype`='Printer'
LEFT JOIN `glpi_networknames`
ON `glpi_networknames`.`items_id`=`glpi_networkports`.`id`
AND `glpi_networknames`.`itemtype`='NetworkPort'
LEFT JOIN `glpi_ipaddresses`
ON `glpi_ipaddresses`.`items_id`=`glpi_networknames`.`id`
AND `glpi_ipaddresses`.`itemtype`='NetworkName'
WHERE `glpi_printers`.`is_deleted`=0
AND `plugin_fusioninventory_configsecurities_id`!='0'";
if ($pfIPRange->fields['entities_id'] != '-1') {
$entities = "(".$pfIPRange->fields['entities_id'];
foreach (getAncestorsOf("glpi_entities", $pfIPRange->fields['entities_id']) as $parent) {
$entities .= ",$parent";
}
$entities .= ")";
$query .= "AND `glpi_printers`.`entities_id` IN ".$entities." ";
}
$query .= " AND inet_aton(`glpi_ipaddresses`.`name`)
BETWEEN inet_aton('".$pfIPRange->fields['ip_start']."')
AND inet_aton('".$pfIPRange->fields['ip_end']."') ";
$query .= " GROUP BY `glpi_printers`.`id`";
$result=$DB->query($query);
while ($data=$DB->fetchArray($result)) {
if (isset($a_snmpauth[$data['plugin_fusioninventory_configsecurities_id']])) {
$devicesList[] = [
'Printer' => $data['gID']
];
}
}
return $devicesList;
}
}

View File

@@ -0,0 +1,361 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the network ports display and parse the
* inventory to add / update in database.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author Vincent Mazzoni
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access this file directly");
}
/**
* Manage the network ports display and parse the inventory to add / update
* in database.
*/
class PluginFusioninventoryNetworkPort extends CommonDBTM {
/**
* Initialize the port of database
*
* @var array
*/
private $portDB = [];
/**
* Initialize the port information from inventory
*
* @var array
*/
private $portModif = [];
/**
* Initialize network port id
*
* @var integer
*/
private $plugin_fusinvsnmp_networkports_id = 0;
/**
* Initialize VLANs (number and name) of port
*
* @var array
*/
private $portVlans=[];
/**
* Get search function for the class
*
* @return array
*/
function rawSearchOptions() {
$tab = [];
$tab[] = [
'id' => 'common',
'name' => __('Characteristics')
];
$tab[] = [
'id' => '1',
'table' => 'glpi_networkports',
'field' => 'name',
'name' => __('Name'),
'type' => 'text',
'massiveaction' => false,
];
$tab[] = [
'id' => '3',
'table' => $this->getTable(),
'field' => 'ifmtu',
'name' => __('MTU', 'fusioninventory'),
];
$tab[] = [
'id' => '5',
'table' => $this->getTable(),
'field' => 'ifspeed',
'name' => __('Speed'),
];
$tab[] = [
'id' => '6',
'table' => $this->getTable(),
'field' => 'ifinternalstatus',
'name' => __('Internal status', 'fusioninventory'),
];
$tab[] = [
'id' => '7',
'table' => $this->getTable(),
'field' => 'iflastchange',
'name' => __('Last change', 'fusioninventory'),
];
$tab[] = [
'id' => '8',
'table' => $this->getTable(),
'field' => 'ifinoctets',
'name' => __('Number of bytes received / Number of bytes sent', 'fusioninventory'),
];
$tab[] = [
'id' => '9',
'table' => $this->getTable(),
'field' => 'ifinerrors',
'name' => __('Number of input errors / Number of errors in reception', 'fusioninventory'),
];
$tab[] = [
'id' => '10',
'table' => $this->getTable(),
'field' => 'portduplex',
'name' => __('Duplex', 'fusioninventory'),
];
$tab[] = [
'id' => '11',
'table' => $this->getTable(),
'field' => 'mac',
'name' => __('Internal MAC address', 'fusioninventory'),
];
$tab[] = [
'id' => '12',
'table' => $this->getTable(),
'field' => 'vlan',
'name' => __('VLAN'),
];
$tab[] = [
'id' => '13',
'table' => $this->getTable(),
'field' => 'connectedto',
'name' => __('Connected to'),
];
$tab[] = [
'id' => '14',
'table' => $this->getTable(),
'field' => 'ifconnectionstatus',
'name' => __('Connection'),
];
$tab[] = [
'id' => '15',
'table' => $this->getTable(),
'field' => 'lastup',
'name' => __('Port not connected since', 'fusioninventory'),
];
$tab[] = [
'id' => '16',
'table' => $this->getTable(),
'field' => 'ifalias',
'name' => __('Alias', 'fusioninventory'),
];
$tab[] = [
'id' => '17',
'table' => 'glpi_netpoints',
'field' => 'name',
'name' => _n('Network outlet', 'Network outlets', 1),
];
return $tab;
}
/**
* Load an optionnaly existing port
*
* @param integer $networkports_id
*/
function loadNetworkport($networkports_id) {
$networkport = new NetworkPort();
$networkport->getFromDB($networkports_id);
$this->portDB = $networkport->fields;
$a_fusports = $this->find(['networkports_id' => $networkports_id], [], 1);
if (count($a_fusports) > 0) {
$a_fusport = current($a_fusports);
foreach ($a_fusport as $key=>$value) {
if ($key == 'id') {
$this->plugin_fusinvsnmp_networkports_id = $value;
} else {
$this->portDB[$key] = $value;
}
}
}
}
/**
* Disconnect a port in DB
*
*@param $p_port Port id to disconnect
*@return nothing
**/
function disconnectDB($p_port) {
if ($p_port=='') {
return;
}
$nn = new NetworkPort_NetworkPort();
$contact_id = $nn->getOppositeContact($p_port);
if ($contact_id AND $nn->getFromDBForNetworkPort($contact_id)) {
$nn->delete($nn->fields, 1);
}
if ($nn->getFromDBForNetworkPort($p_port)) {
$nn->delete($nn->fields, 1);
}
}
/**
* Add vlan
*
*@param $p_number Vlan number
*@param $p_name Vlan name
*@return nothing
**/
function addVlan($p_number, $p_name) {
$this->portVlans[$p_number] = $p_name;
}
/**
* Get unique object fields by id of network port
*
* @global object $DB
* @param integer $id
* @return array
*/
static function getUniqueObjectfieldsByportID($id) {
global $DB;
$array = [];
$query = "SELECT *
FROM `glpi_networkports`
WHERE `id`='".$id."';";
if (($result = $DB->query($query))) {
$data = $DB->fetchArray($result);
$array["items_id"] = $data["items_id"];
$array["itemtype"] = $data["itemtype"];
}
if ($array["itemtype"] == NETWORKING_TYPE) {
$query = "SELECT *
FROM `glpi_networkequipments`
WHERE `id`='".$array["itemtype"]."'
LIMIT 0, 1;";
if (($result = $DB->query($query))) {
$data = $DB->fetchArray($result);
$array["name"] = $data["name"];
}
}
return $array;
}
/**
* Get a value
*
* @param string $name
* @return string
*/
function getValue($name) {
if (isset($this->portModif[$name])) {
return $this->portModif[$name];
} else if (isset($this->portDB[$name])) {
return $this->portDB[$name];
}
return '';
}
/**
* Get the network port id
*
* @return integer
*/
function getNetworkPortsID() {
if (isset($this->portDB['id'])) {
return $this->portDB['id'];
} else if (isset($this->portModif['id'])) {
return $this->portModif['id'];
}
return 0;
}
/**
* Function used to detect if port has multiple mac connected
*
* @param integer $networkports_id
* @return boolean
*/
static function isPortHasMultipleMac($networkports_id) {
$nw = new NetworkPort_NetworkPort();
$networkPort = new NetworkPort();
$is_multiple = false;
$opposite_port = $nw->getOppositeContact($networkports_id);
if ($opposite_port != ""
&& $opposite_port!= 0) {
$networkPort->getFromDB($opposite_port);
if ($networkPort->fields["itemtype"] == 'PluginFusioninventoryUnmanaged') {
$pfUnmanaged = new PluginFusioninventoryUnmanaged();
if ($pfUnmanaged->getFromDB($networkPort->fields['items_id'])) {
if ($pfUnmanaged->fields['hub'] == 1) {
$is_multiple = true;
}
}
}
}
return $is_multiple;
}
}

View File

@@ -0,0 +1,180 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the history of network port connections.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access this file directly");
}
/**
* Manage the history of network port connections.
*/
class PluginFusioninventoryNetworkPortConnectionLog extends CommonDBTM {
/**
* Display form
*
* @global object $DB
* @global array $CFG_GLPI
* @param array $input
*/
function showForm($input = []) {
global $DB, $CFG_GLPI;
$fi_path = Plugin::getWebDir('fusioninventory');
$NetworkPort = new NetworkPort();
echo "<table class='tab_cadre' cellpadding='5' width='950'>";
echo "<tr class='tab_bg_1'>";
echo "<th>";
echo __('PID', 'fusioninventory');
echo " <a href='".$fi_path."/front/agentprocess.form.php'>(".__('All').")</a>";
echo "</th>";
echo "<th>";
echo _n('Date', 'Dates', 1);
echo "</th>";
echo "<th>";
echo _n('Item', 'Items', 1);
echo "</th>";
echo "<th>";
echo __('Status');
echo "</th>";
echo "<th>";
echo _n('Item', 'Items', 1);
echo "</th>";
echo "</tr>";
$condition = '';
if (!isset($input['plugin_fusioninventory_agentprocesses_id'])) {
$condition = '';
} else {
$condition = "WHERE `plugin_fusioninventory_agentprocesses_id`='".
$input['plugin_fusioninventory_agentprocesses_id']."'";
if (isset($input['created'])) {
$condition .= " AND `creation`='".$input['created']."' ";
}
}
$query = "SELECT * FROM `".$this->getTable()."`
".$condition."
ORDER BY `date`DESC, `plugin_fusioninventory_agentprocesses_id` DESC";
if (!isset($input['process_number'])) {
$query .= " LIMIT 0, 500";
}
$result = $DB->query($query);
if ($result) {
while ($data=$DB->fetchArray($result)) {
echo "<tr class='tab_bg_1 center'>";
echo "<td>";
echo "<a href='".$fi_path."/front/agentprocess.form.php?h_process_number=".
$data['plugin_fusioninventory_agentprocesses_id']."'>".
$data['plugin_fusioninventory_agentprocesses_id']."</a>";
echo "</td>";
echo "<td>";
echo Html::convDateTime($data['date']);
echo "</td>";
echo "<td>";
$NetworkPort->getFromDB($data['networkports_id_source']);
$item = new $NetworkPort->fields["itemtype"];
$item->getFromDB($NetworkPort->fields["items_id"]);
$link1 = $item->getLink(1);
$link = "<a href=\"" . $CFG_GLPI["root_doc"] . "/front/networkport.form.php?id=".
$NetworkPort->fields["id"] . "\">";
if (rtrim($NetworkPort->fields["name"]) != "") {
$link .= $NetworkPort->fields["name"];
} else {
$link .= __('Without name');
}
$link .= "</a>";
echo $link." ".__('on', 'fusioninventory')." ".$link1;
echo "</td>";
echo "<td>";
if ($data['creation'] == '1') {
echo "<img src='".$fi_path."/pics/connection_ok.png'/>";
} else {
echo "<img src='".$fi_path."/pics/connection_notok.png'/>";
}
echo "</td>";
echo "<td>";
$NetworkPort->getFromDB($data['networkports_id_destination']);
$item = new $NetworkPort->fields["itemtype"];
$item->getFromDB($NetworkPort->fields["items_id"]);
$link1 = $item->getLink(1);
$link = "<a href=\"" . $CFG_GLPI["root_doc"] . "/front/networkport.form.php?id=".
$NetworkPort->fields["id"] . "\">";
if (rtrim($NetworkPort->fields["name"]) != "") {
$link .= $NetworkPort->fields["name"];
} else {
$link .= __('Without name');
}
$link .= "</a>";
echo $link." ".__('on', 'fusioninventory')." ".$link1;
echo "</td>";
echo "</tr>";
}
}
echo "</table>";
}
}

View File

@@ -0,0 +1,552 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the history of network port changes.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access this file directly");
}
/**
* Manage the history of network port changes.
*/
class PluginFusioninventoryNetworkPortLog extends CommonDBTM {
/**
* Get the tab name used for item
*
* @param object $item the item object
* @param integer $withtemplate 1 if is a template form
* @return string name of the tab
*/
function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) {
if ($item->fields['id'] > 0) {
return __('FusionInventory historical', 'fusioninventory');
}
return '';
}
/**
* Display the content of the tab
*
* @param object $item
* @param integer $tabnum number of the tab to display
* @param integer $withtemplate 1 if is a template form
* @return boolean
*/
static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) {
$pfNetworkPortLog = new self();
echo $pfNetworkPortLog->showHistory($item->fields['id']);
return true;
}
/**
* Insert port history with connection and disconnection
*
* @global object $DB
* @param string $status status of port ('make' or 'remove')
* @param array $array with values : $array["networkports_id"], $array["value"], $array["itemtype"]
* and $array["device_ID"]
*/
function insertConnection($status, $array) {
global $DB;
$input = [];
$input['date'] = date("Y-m-d H:i:s");
$input['networkports_id'] = $array['networkports_id'];
if ($status == "field") {
$DB->insert(
'glpi_plugin_fusioninventory_networkportlogs', [
'networkports_id' => $array['networkports_id'],
'plugin_fusioninventory_mappings_id' => $array['plugin_fusioninventory_mappings_id'],
'value_old' => $array('value_old'),
'value_new' => $array['value_new'],
'date_mod' => date("Y-m-d H:i:s")
]
);
}
}
/**
* Display form
*
* @global object $DB
* @param integer $id
* @param array $options
* @return true
*/
function showForm($id, $options = []) {
global $DB;
$this->initForm($id, $options);
$this->showFormHeader($options);
echo "<tr class='tab_bg_1'>";
echo "<td colspan='3'>";
echo __('List of fields to history', 'fusioninventory')." :";
echo "</td>";
echo "</tr>";
echo "<tr class='tab_bg_1'>";
$options = [];
$mapping = new PluginFusioninventoryMapping;
$maps = $mapping->find();
$listName = [];
foreach ($maps as $mapfields) {
// TODO: untested
$listName[$mapfields['itemtype']."-".$mapfields['name']]=
$mapping->getTranslation($mapfields);
}
if (!empty($listName)) {
asort($listName);
}
// Get list of fields configured for history
$iterator = $DB->request([
'FROM' => 'glpi_plugin_fusioninventory_configlogfields'
]);
$stmt = null;
if (count($iterator)) {
$delete = $DB->buildDelete(
'glpi_plugin_fusioninventory_configlogfields', [
'id' => new \QueryParam()
]
);
$stmt = $DB->prepare($delete);
}
while ($data = $iterator->next()) {
$type = '';
$name= '';
list($type, $name) = explode("-", $data['field']);
if (!isset($listName[$type."-".$name])) {
$stmt->bind_param('s', $data['id']);
$stmt->execute();
} else {
$options[$data['field']]=$listName[$type."-".$name];
}
unset($listName[$data['field']]);
}
if ($stmt != null) {
mysqli_stmt_close($stmt);
}
if (!empty($options)) {
asort($options);
}
echo "<td class='right' width='350'>";
if (count($listName)) {
echo "<select name='plugin_fusioninventory_extraction_to_add[]' multiple size='15'>";
foreach ($listName as $key => $val) {
//list ($item_type, $item) = explode("_", $key);
echo "<option value='$key'>" . $val . "</option>\n";
}
echo "</select>";
}
echo "</td><td class='center'>";
if (count($listName)) {
if (Session::haveRight('plugin_fusioninventory_configuration', UPDATE)) {
echo "<input type='submit' class=\"submit\" ".
"name='plugin_fusioninventory_extraction_add' value='" . __('Add') . " >>'>";
}
}
echo "<br /><br />";
if (!empty($options)) {
if (Session::haveRight('plugin_fusioninventory_configuration', UPDATE)) {
echo "<input type='submit' class=\"submit\" ".
"name='plugin_fusioninventory_extraction_delete' value='<< ".
__('Delete', 'fusioninventory') . "'>";
}
}
echo "</td><td class='left'>";
if (!empty($options)) {
echo "<select name='plugin_fusioninventory_extraction_to_delete[]' multiple size='15'>";
foreach ($options as $key => $val) {
//list ($item_type, $item) = explode("_", $key);
echo "<option value='$key'>" . $val . "</option>\n";
}
echo "</select>";
} else {
echo "&nbsp;";
}
echo "</td>";
echo "</tr>";
echo "<tr>";
echo "<th colspan='3'>";
echo __('Clean history', 'fusioninventory')." :";
echo "</th>";
echo "</tr>";
echo "<tr class='tab_bg_1'>";
echo "<td colspan='3' class='center'>";
if (Session::haveRight('plugin_fusioninventory_configuration', UPDATE)) {
echo "<input type='submit' class=\"submit\" name='Clean_history' ".
"value='".__('Clean')."' >";
}
echo "</td>";
echo "</tr>";
echo "<tr>";
echo "<th colspan='3'>";
echo "&nbsp;";
echo "</th>";
echo "</tr>";
$this->showFormButtons($options);
echo "<div id='tabcontent'></div>";
echo "<script type='text/javascript'>loadDefaultTab();</script>";
return true;
}
/**
* Cron task: clean networkport logs too old
*
* @global object $DB
*/
static function cronCleannetworkportlogs() {
global $DB;
$pfConfigLogField = new PluginFusioninventoryConfigLogField();
$pfNetworkPortLog = new PluginFusioninventoryNetworkPortLog();
$a_list = $pfConfigLogField->find();
if (count($a_list)) {
foreach ($a_list as $data) {
switch ($data['days']) {
case '-1':
$DB->delete(
$pfNetworkPortLog->getTable(), [
'plugin_fusioninventory_mappings_id' => $data['plugin_fusioninventory_mappings_id']
]
);
break;
case '0': // never delete
break;
default:
$DB->delete(
$pfNetworkPortLog->getTable(), [
'plugin_fusioninventory_mappings_id' => $data['plugin_fusioninventory_mappings_id'],
'date_mod' => new \QueryExpression(
"date_add(now(), interval - {$data['days']} day)"
)
]
);
break;
}
}
}
}
/**
* Add log of networkport
*
* @param integer $port_id
* @param string $value_new
* @param string $field
*/
static function networkport_addLog($port_id, $value_new, $field) {
$pfNetworkPort = new PluginFusioninventoryNetworkPort();
$pfNetworkPortLog = new PluginFusioninventoryNetworkPortLog();
$pfConfigLogField = new PluginFusioninventoryConfigLogField();
$pfMapping = new PluginFusioninventoryMapping();
$db_field = $field;
switch ($field) {
case 'ifname':
$db_field = 'name';
$field = 'ifName';
break;
case 'mac':
$db_field = 'mac';
$field = 'macaddr';
break;
case 'ifnumber':
$db_field = 'logical_number';
$field = 'ifIndex';
break;
case 'trunk':
$field = 'vlanTrunkPortDynamicStatus';
break;
case 'iftype':
$field = 'ifType';
break;
case 'duplex':
$field = 'portDuplex';
break;
}
$pfNetworkPort->loadNetworkport($port_id);
//echo $ptp->getValue($db_field);
if ($pfNetworkPort->getValue($db_field) != $value_new) {
$a_mapping = $pfMapping->get('NetworkEquipment', $field);
$days = $pfConfigLogField->getValue($a_mapping['id']);
if ((isset($days)) AND ($days != '-1')) {
$array = [];
$array["networkports_id"] = $port_id;
$array["plugin_fusioninventory_mappings_id"] = $a_mapping['id'];
$array["value_old"] = $pfNetworkPort->getValue($db_field);
$array["value_new"] = $value_new;
$pfNetworkPortLog->insertConnection("field", $array);
}
}
}
// $status = connection or disconnection
/**
* Add log when connect or disconnect
*
* @param string $status values possible: make|remove
* @param integer $ports_id
*/
static function addLogConnection($status, $ports_id) {
$pfNetworkPortConnectionLog = new PluginFusioninventoryNetworkPortConnectionLog();
$NetworkPort_NetworkPort=new NetworkPort_NetworkPort();
$input = [];
// Récupérer le port de la machine associé au port du switch
// Récupérer le type de matériel
$input["networkports_id_source"] = $ports_id;
$opposite_port = $NetworkPort_NetworkPort->getOppositeContact($ports_id);
if (!$opposite_port) {
return;
}
$input['networkports_id_destination'] = $opposite_port;
$input['date_mod'] = date("Y-m-d H:i:s");
if ($status == 'remove') {
$input['creation'] = 0;
} else if ($status == 'make') {
$input['creation'] = 1;
}
$pfNetworkPortConnectionLog->add($input);
}
/**
* Get the history list of the port
*
* @global object $DB
* @global array $CFG_GLPI
* @param integer $ID_port
* @return string the html prepared to display
*/
static function showHistory($ID_port) {
global $DB, $CFG_GLPI;
$np = new NetworkPort();
$query = "
SELECT * FROM(
SELECT * FROM (
SELECT `id`, `date_mod`, `plugin_fusioninventory_agentprocesses_id`,
`networkports_id_source`, `networkports_id_destination`,
`creation` as `field`, NULL as `value_old`, NULL as `value_new`
FROM `glpi_plugin_fusioninventory_networkportconnectionlogs`
WHERE `networkports_id_source`='".$ID_port."'
OR `networkports_id_destination`='".$ID_port."'
ORDER BY `date_mod` DESC
)
AS `DerivedTable1`
UNION ALL
SELECT * FROM (
SELECT `glpi_plugin_fusioninventory_networkportlogs`.`id`,
`date_mod` as `date_mod`, `plugin_fusioninventory_agentprocesses_id`,
`networkports_id` AS `networkports_id_source`,
NULL as `networkports_id_destination`,
`name` AS `field`, `value_old`, `value_new`
FROM `glpi_plugin_fusioninventory_networkportlogs`
LEFT JOIN `glpi_plugin_fusioninventory_mappings`
ON `glpi_plugin_fusioninventory_networkportlogs`.".
"`plugin_fusioninventory_mappings_id` =
`glpi_plugin_fusioninventory_mappings`.`id`
WHERE `networkports_id`='".$ID_port."'
ORDER BY `date_mod` DESC
)
AS `DerivedTable2`)
AS `MainTable`
ORDER BY `date_mod` DESC, `id` DESC";
$text = "<table class='tab_cadre' cellpadding='5' width='950'>";
$text .= "<tr class='tab_bg_1'>";
$text .= "<th colspan='8'>";
$text .= "Historique";
$text .= "</th>";
$text .= "</tr>";
$text .= "<tr class='tab_bg_1'>";
$text .= "<th>".__('Connection')."</th>";
$text .= "<th>"._n('Item', 'Items', 1)."</th>";
$text .= "<th>".__('Field')."</th>";
$text .= "<th></th>";
$text .= "<th></th>";
$text .= "<th></th>";
$text .= "<th>"._n('Date', 'Dates', 1)."</th>";
$text .= "</tr>";
$result=$DB->query($query);
if ($result) {
while ($data=$DB->fetchArray($result)) {
$text .= "<tr class='tab_bg_1'>";
if (!empty($data["networkports_id_destination"])) {
// Connections and disconnections
$imgfolder = Plugin::getWebDir('fusioninventory')."/pics";
if ($data['field'] == '1') {
$text .= "<td align='center'><img src='".$imgfolder."/connection_ok.png'/></td>";
} else {
$text .= "<td align='center'><img src='".$imgfolder.
"/connection_notok.png'/></td>";
}
if ($ID_port == $data["networkports_id_source"]) {
if ($np->getFromDB($data["networkports_id_destination"])) {
//if (isset($np->fields["items_id"])) {
$item = new $np->fields["itemtype"];
$item->getFromDB($np->fields["items_id"]);
$link1 = $item->getLink(1);
$link = "<a href=\"" . $CFG_GLPI["root_doc"].
"/front/networkport.form.php?id=" . $np->fields["id"] . "\">";
if (rtrim($np->fields["name"]) != "") {
$link .= $np->fields["name"];
} else {
$link .= __('Without name');
}
$link .= "</a>";
$text .= "<td align='center'>".$link." ".__('on', 'fusioninventory')." ".
$link1."</td>";
} else {
$text .= "<td align='center'><font color='#ff0000'>".__('Deleted').
"</font></td>";
}
} else if ($ID_port == $data["networkports_id_destination"]) {
$np->getFromDB($data["networkports_id_source"]);
if (isset($np->fields["items_id"])) {
$item = new $np->fields["itemtype"];
$item->getFromDB($np->fields["items_id"]);
$link1 = $item->getLink(1);
$link = "<a href=\"" . $CFG_GLPI["root_doc"]."/front/networkport.form.php?id=".
$np->fields["id"] . "\">";
if (rtrim($np->fields["name"]) != "") {
$link .= $np->fields["name"];
} else {
$link .= __('Without name');
}
$link .= "</a>";
$text .= "<td align='center'>".$link." ".__('on', 'fusioninventory')." ".
$link1."</td>";
} else {
$text .= "<td align='center'><font color='#ff0000'>".__('Deleted').
"</font></td>";
}
}
$text .= "<td align='center' colspan='4'></td>";
$text .= "<td align='center'>".Html::convDateTime($data["date_mod"])."</td>";
} else {
// Changes values
$text .= "<td align='center' colspan='2'></td>";
// $text .= "<td align='center'>".
// $FUSIONINVENTORY_MAPPING[NETWORKING_TYPE][$data["field"]]['name']."</td>";
$mapping = new PluginFusioninventoryMapping();
$mapfields = $mapping->get('NetworkEquipment', $data["field"]);
if ($mapfields != false) {
$text .= "<td align='center'>".
$mapping->getTranslation($mapfields)."</td>";
} else {
$text .= "<td align='center'></td>";
}
$text .= "<td align='center'>".$data["value_old"]."</td>";
$text .= "<td align='center'>-></td>";
$text .= "<td align='center'>".$data["value_new"]."</td>";
$text .= "<td align='center'>".Html::convDateTime($data["date_mod"])."</td>";
}
$text .= "</tr>";
}
}
$text .= "</table>";
return $text;
}
}

View File

@@ -0,0 +1,463 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the differents type of network ports.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author Vincent Mazzoni
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the differents type of network ports.
*/
class PluginFusioninventoryNetworkporttype extends CommonDBTM {
/**
* Initialize all port types
*
* @global object $DB
*/
function init() {
global $DB;
$input = [];
$input['1'] = 'other';
$input['2'] = 'regular1822';
$input['3'] = 'hdh1822';
$input['4'] = 'ddnX25';
$input['5'] = 'rfc877x25';
$input['6'] = 'ethernetCsmacd';
$input['7'] = 'iso88023Csmacd';
$input['8'] = 'iso88024TokenBus';
$input['9'] = 'iso88025TokenRing';
$input['10'] = 'iso88026Man';
$input['11'] = 'starLan';
$input['12'] = 'proteon10Mbit';
$input['13'] = 'proteon80Mbit';
$input['14'] = 'hyperchannel';
$input['15'] = 'fddi';
$input['16'] = 'lapb';
$input['17'] = 'sdlc';
$input['18'] = 'ds1';
$input['19'] = 'e1';
$input['20'] = 'basicISDN';
$input['21'] = 'primaryISDN';
$input['22'] = 'propPointToPointSerial';
$input['23'] = 'ppp';
$input['24'] = 'softwareLoopback';
$input['25'] = 'eon';
$input['26'] = 'ethernet3Mbit';
$input['27'] = 'nsip';
$input['28'] = 'slip';
$input['29'] = 'ultra';
$input['30'] = 'ds3';
$input['31'] = 'sip';
$input['32'] = 'frameRelay';
$input['33'] = 'rs232';
$input['34'] = 'para';
$input['35'] = 'arcnet';
$input['36'] = 'arcnetPlus';
$input['37'] = 'atm';
$input['38'] = 'miox25';
$input['39'] = 'sonet';
$input['40'] = 'x25ple';
$input['41'] = 'iso88022llc';
$input['42'] = 'localTalk';
$input['43'] = 'smdsDxi';
$input['44'] = 'frameRelayService';
$input['45'] = 'v35';
$input['46'] = 'hssi';
$input['47'] = 'hippi';
$input['48'] = 'modem';
$input['49'] = 'aal5';
$input['50'] = 'sonetPath';
$input['51'] = 'sonetVT';
$input['52'] = 'smdsIcip';
$input['53'] = 'propVirtual';
$input['54'] = 'propMultiplexor';
$input['55'] = 'ieee80212';
$input['56'] = 'fibreChannel';
$input['57'] = 'hippiInterface';
$input['58'] = 'frameRelayInterconnect';
$input['59'] = 'aflane8023';
$input['60'] = 'aflane8025';
$input['61'] = 'cctEmul';
$input['62'] = 'fastEther';
$input['63'] = 'isdn';
$input['64'] = 'v11';
$input['65'] = 'v36';
$input['66'] = 'g703at64k';
$input['67'] = 'g703at2mb';
$input['68'] = 'qllc';
$input['69'] = 'fastEtherFX';
$input['70'] = 'channel';
$input['71'] = 'ieee80211';
$input['72'] = 'ibm370parChan';
$input['73'] = 'escon';
$input['74'] = 'dlsw';
$input['75'] = 'isdns';
$input['76'] = 'isdnu';
$input['77'] = 'lapd';
$input['78'] = 'ipSwitch';
$input['79'] = 'rsrb';
$input['80'] = 'atmLogical';
$input['81'] = 'ds0';
$input['82'] = 'ds0Bundle';
$input['83'] = 'bsc';
$input['84'] = 'async';
$input['85'] = 'cnr';
$input['86'] = 'iso88025Dtr';
$input['87'] = 'eplrs';
$input['88'] = 'arap';
$input['89'] = 'propCnls';
$input['90'] = 'hostPad';
$input['91'] = 'termPad';
$input['92'] = 'frameRelayMPI';
$input['93'] = 'x213';
$input['94'] = 'adsl';
$input['95'] = 'radsl';
$input['96'] = 'sdsl';
$input['97'] = 'vdsl';
$input['98'] = 'iso88025CRFPInt';
$input['99'] = 'myrinet';
$input['100'] = 'voiceEM';
$input['101'] = 'voiceFXO';
$input['102'] = 'voiceFXS';
$input['103'] = 'voiceEncap';
$input['104'] = 'voiceOverIp';
$input['105'] = 'atmDxi';
$input['106'] = 'atmFuni';
$input['107'] = 'atmIma';
$input['108'] = 'pppMultilinkBundle';
$input['109'] = 'ipOverCdlc';
$input['110'] = 'ipOverClaw';
$input['111'] = 'stackToStack';
$input['112'] = 'virtualIpAddress';
$input['113'] = 'mpc';
$input['114'] = 'ipOverAtm';
$input['115'] = 'iso88025Fiber';
$input['116'] = 'tdlc';
$input['117'] = 'gigabitEthernet';
$input['118'] = 'hdlc';
$input['119'] = 'lapf';
$input['120'] = 'v37';
$input['121'] = 'x25mlp';
$input['122'] = 'x25huntGroup';
$input['123'] = 'trasnpHdlc';
$input['124'] = 'interleave';
$input['125'] = 'fast';
$input['126'] = 'ip';
$input['127'] = 'docsCableMaclayer';
$input['128'] = 'docsCableDownstream';
$input['129'] = 'docsCableUpstream';
$input['130'] = 'a12MppSwitch';
$input['131'] = 'tunnel';
$input['132'] = 'coffee';
$input['133'] = 'ces';
$input['134'] = 'atmSubInterface';
$input['135'] = 'l2vlan';
$input['136'] = 'l3ipvlan';
$input['137'] = 'l3ipxvlan';
$input['138'] = 'digitalPowerline';
$input['139'] = 'mediaMailOverIp';
$input['140'] = 'dtm';
$input['141'] = 'dcn';
$input['142'] = 'ipForward';
$input['143'] = 'msdsl';
$input['144'] = 'ieee1394';
$input['145'] = 'if-gsn';
$input['146'] = 'dvbRccMacLayer';
$input['147'] = 'dvbRccDownstream';
$input['148'] = 'dvbRccUpstream';
$input['149'] = 'atmVirtual';
$input['150'] = 'mplsTunnel';
$input['151'] = 'srp';
$input['152'] = 'voiceOverAtm';
$input['153'] = 'voiceOverFrameRelay';
$input['154'] = 'idsl';
$input['155'] = 'compositeLink';
$input['156'] = 'ss7SigLink';
$input['157'] = 'propWirelessP2P';
$input['158'] = 'frForward';
$input['159'] = 'rfc1483';
$input['160'] = 'usb';
$input['161'] = 'ieee8023adLag';
$input['162'] = 'bgppolicyaccounting';
$input['163'] = 'frf16MfrBundle';
$input['164'] = 'h323Gatekeeper';
$input['165'] = 'h323Proxy';
$input['166'] = 'mpls';
$input['167'] = 'mfSigLink';
$input['168'] = 'hdsl2';
$input['169'] = 'shdsl';
$input['170'] = 'ds1FDL';
$input['171'] = 'pos';
$input['172'] = 'dvbAsiIn';
$input['173'] = 'dvbAsiOut';
$input['174'] = 'plc';
$input['175'] = 'nfas';
$input['176'] = 'tr008';
$input['177'] = 'gr303RDT';
$input['178'] = 'gr303IDT';
$input['179'] = 'isup';
$input['180'] = 'propDocsWirelessMaclayer';
$input['181'] = 'propDocsWirelessDownstream';
$input['182'] = 'propDocsWirelessUpstream';
$input['183'] = 'hiperlan2';
$input['184'] = 'propBWAp2Mp';
$input['185'] = 'sonetOverheadChannel';
$input['186'] = 'digitalWrapperOverheadChannel';
$input['187'] = 'aal2';
$input['188'] = 'radioMAC';
$input['189'] = 'atmRadio';
$input['190'] = 'imt';
$input['191'] = 'mvl';
$input['192'] = 'reachDSL';
$input['193'] = 'frDlciEndPt';
$input['194'] = 'atmVciEndPt';
$input['195'] = 'opticalChannel';
$input['196'] = 'opticalTransport';
$input['197'] = 'propAtm';
$input['198'] = 'voiceOverCable';
$input['199'] = 'infiniband';
$input['200'] = 'teLink';
$input['201'] = 'q2931';
$input['202'] = 'virtualTg';
$input['203'] = 'sipTg';
$input['204'] = 'sipSig';
$input['205'] = 'docsCableUpstreamChannel';
$input['206'] = 'econet';
$input['207'] = 'pon155';
$input['208'] = 'pon622';
$input['209'] = 'bridge';
$input['210'] = 'linegroup';
$input['211'] = 'voiceEMFGD';
$input['212'] = 'voiceFGDEANA';
$input['213'] = 'voiceDID';
$input['214'] = 'mpegTransport';
$input['215'] = 'sixToFour';
$input['216'] = 'gtp';
$input['217'] = 'pdnEtherLoop1';
$input['218'] = 'pdnEtherLoop2';
$input['219'] = 'opticalChannelGroup';
$input['220'] = 'homepna';
$input['221'] = 'gfp';
$input['222'] = 'ciscoISLvlan';
$input['223'] = 'actelisMetaLOOP';
$input['224'] = 'fcipLink';
$input['225'] = 'rpr';
$input['226'] = 'qam';
$input['227'] = 'lmp';
$input['228'] = 'cblVectaStar';
$input['229'] = 'docsCableMCmtsDownstream';
$input['230'] = 'adsl2';
$input['231'] = 'macSecControlledIF';
$input['232'] = 'macSecUncontrolledIF';
$input['233'] = 'aviciOpticalEther';
$input['234'] = 'atmbond';
$install = 1;
$iterator = $DB->request([
'FROM' => 'glpi_plugin_fusioninventory_networkporttypes',
'WHERE' => ['import' => 1]
]);
if (count($iterator) > 0) {
$install = 0;
}
$it = new DBmysqlIterator($DB);
$it->buildQuery([
'FROM' => 'glpi_plugin_fusioninventory_networkporttypes',
'WHERE' => ['number' => new QueryParam()]
]);
$stmt_select = $DB->prepare($it->getSQL());
$to_import = [];
foreach ($input as $number=>$name) {
$stmt_select->bind_param('s', $number);
$stmt_select->execute();
if ($DB->numrows($stmt_select) == '0') {
$to_import[$number] = $name;
}
}
mysqli_stmt_close($stmt_select);
if (count($to_import)) {
$qparam = new \QueryParam();
$insert_qry = $DB->buildInsert(
'glpi_plugin_fusioninventory_networkporttypes', [
'name' => $qparam,
'number' => $qparam,
'othername' => $qparam,
'import' => $qparam
]
);
$stmt_insert = $DB->prepare($insert_qry);
foreach ($to_import as $number=>$name) {
$import = 0;
$othername = "$name ($number)";
if ($install == '1') {
switch ($number) {
case '6':
case '7':
case '71':
case '117':
case '62':
case '169':
case '56':
$import = 1;
break;
}
}
$stmt_insert->bind_param(
'ssss',
$name,
$number,
$othername,
$import
);
$stmt_insert->execute();
}
mysqli_stmt_close($stmt_insert);
}
}
/**
* Check is the type yet in database
*
* @param string $type
* @return boolean
*/
function isImportType($type) {
if (!strstr($type, 'gsn')) {
$type = str_replace("-", "", $type);
}
$a_ports = $this->find(
['OR' =>
['number' => $type,
'name' => $type,
'othername' => $type],
'import' => 1]);
if (count($a_ports) > 0) {
return true;
}
return false;
}
/**
* Display the types of network and what ports (with the types) we import in
* networkequipments
*/
function showNetworkporttype() {
$a_notimports = $this->find(['import' => 0]);
$a_imports = $this->find(['import' => 1]);
echo "<form name='form' method='post' action='".$this->getFormURL()."'>";
echo "<table class='tab_cadre_fixe'>";
echo "<tr class='tab_bg_1'>";
echo "<th colspan='3'>".
__('Ports types to import (for network equipments)', 'fusioninventory')."</th>";
echo "</tr>";
echo "<tr class='tab_bg_1'>";
if (Session::haveRight('plugin_fusioninventory_configuration', UPDATE)) {
echo "<td class='right'>";
if (count($a_notimports) > 0) {
echo "<select name='type_to_add[]' multiple size='5'>";
foreach ($a_notimports as $key => $data) {
echo "<option value='$key'>".$data['othername']."</option>";
}
echo "</select>";
}
echo "</td><td class='center'>";
if (count($a_notimports)) {
echo "<input type='submit' class='submit' name='type_add' value='".
__('Add')." >>'>";
}
echo "<br><br>";
if (count($a_imports)) {
echo "<input type='submit' class='submit' name='type_delete' value='<< ".
__('Delete', 'fusioninventory')."'>";
}
echo "</td><td>";
} else {
echo "<td colspan='2'></td>";
echo "<td class='center'>";
}
if (count($a_imports)) {
echo "<select name='type_to_delete[]' multiple size='5'>";
foreach ($a_imports as $key => $data) {
echo "<option value='$key'>".$data['othername']."</option>";
}
echo "</select>";
} else {
echo "&nbsp;";
}
echo "</td>";
echo "</tr>";
echo "</table>";
Html::closeForm();
}
}

View File

@@ -0,0 +1,186 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the printer extended information.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author Vincent Mazzoni
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access this file directly");
}
/**
* Manage the printer extended information.
*/
class PluginFusioninventoryPrinter extends PluginFusioninventoryItem {
/**
* The right name for this class
*
* @var string
*/
static $rightname = 'plugin_fusioninventory_printer';
public $itemtype = 'Printer';
/**
* Get name of this type by language of the user connected
*
* @param integer $nb number of elements
* @return string name of this type
*/
static function getTypeName($nb = 0) {
return '';
}
/**
* Get the type
*
* @return string
*/
static function getType() {
return 'Printer';
}
/**
* Get the tab name used for item
*
* @param object $item the item object
* @param integer $withtemplate 1 if is a template form
* @return string name of the tab
*/
function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) {
if ($this->canView()) {
return self::createTabEntry(__('FusionInventory SNMP', 'fusioninventory'));
}
return '';
}
/**
* Display the content of the tab
*
* @param object $item
* @param integer $tabnum number of the tab to display
* @param integer $withtemplate 1 if is a template form
* @return boolean
*/
static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) {
$fi_path = Plugin::getWebDir('fusioninventory');
if ($item->fields['id'] > 0) {
$pfPrinter = new PluginFusioninventoryPrinter();
$pfPrinter->showForm($item,
['target' => $fi_path.'/front/printer_info.form.php']);
echo '<div id="overDivYFix" STYLE="visibility:hidden">fusinvsnmp_1</div>';
$pfPrinterCartridge = new PluginFusioninventoryPrinterCartridge();
$pfPrinterCartridge->showForm($item,
['target' => $fi_path.'/front/printer_info.form.php']);
$pfPrinterLog = new PluginFusioninventoryPrinterLog();
$pfPrinterLog->showGraph($item->getID(),
['target' => $fi_path.'/front/printer_info.form.php']);
return true;
}
return false;
}
/**
* Update an existing printer with last_fusioninventory_update value
*/
function updateDB() {
parent::updateDB();
// update last_fusioninventory_update even if no other update
$this->setValue('last_fusioninventory_update', date("Y-m-d H:i:s"));
$this->updateDB();
}
/**
* Display extended printer information
*
* @param object $item
*/
static function showInfo($item) {
// Manage locks pictures
PluginFusioninventoryLock::showLockIcon('Printer');
$pfPrinter = new PluginFusioninventoryPrinter();
$a_printerextend = current($pfPrinter->find(['printers_id' => $item->getID()], [], 1));
if (empty($a_printerextend)) {
return;
}
echo '<table class="tab_glpi" width="100%">';
echo '<tr>';
echo '<th colspan="2">'.__('FusionInventory', 'fusioninventory').'</th>';
echo '</tr>';
echo '<tr class="tab_bg_1">';
echo '<td>';
echo __('Last inventory', 'fusioninventory');
echo '</td>';
echo '<td>';
echo Html::convDateTime($a_printerextend['last_fusioninventory_update']);
echo '</td>';
echo '</tr>';
echo '<tr class="tab_bg_1">';
echo '<td>';
echo __('Type');
echo '</td>';
echo '<td>';
echo "SNMP";
echo '</td>';
echo '</tr>';
echo "</table>";
}
}

View File

@@ -0,0 +1,146 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the printer cartridge filled by inventory
* like type, state of ink in cartridge, number pages...
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author Vincent Mazzoni
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access this file directly");
}
/**
* Manage the printer cartridge filled by inventory like type, state of
* ink in cartridge, number pages...
*/
class PluginFusioninventoryPrinterCartridge extends CommonDBTM {
/**
* Display form
*
* @global object $DB
* @param object $item Printer instance
* @param array $options
* @return true
*/
function showForm(Printer $item, $options = []) {
global $DB;
// ** Get link OID fields
$mapping_name=[];
$id = $item->getID();
$a_cartridges = $this->find(['printers_id' => $id]);
$printer = new Printer();
$printer->getFromDB($id);
$query_cartridges = "SELECT `id` FROM `glpi_cartridgeitems`
WHERE `id` NOT IN (SELECT `c`.`cartridgeitems_id`
FROM `glpi_cartridgeitems_printermodels` AS c, `glpi_printers` AS p
WHERE `c`.`printermodels_id`=`p`.`printermodels_id` and `p`.`id`='$id')";
$result_cartridges = $DB->query($query_cartridges);
$exclude_cartridges = [];
if ($result_cartridges !== false) {
while ($cartridge = $DB->fetchArray($result_cartridges)) {
$exclude_cartridges[] = $cartridge['id'];
}
}
echo "<div align='center'>";
echo "<table class='tab_cadre' cellpadding='5' width='950'>";
echo "<tr class='tab_bg_1'>";
echo "<th align='center' colspan='3'>";
echo __('Cartridge(s)', 'fusioninventory');
echo "</th>";
echo "</tr>";
asort($mapping_name);
$mapping = new PluginFusioninventoryMapping();
foreach ($a_cartridges as $a_cartridge) {
echo "<tr class='tab_bg_1'>";
echo "<td align='center'>";
$mapping->getFromDB($a_cartridge['plugin_fusioninventory_mappings_id']);
echo $mapping->getTranslation($mapping->fields);
echo " : ";
echo "</td>";
echo "<td align='center'>";
echo "<form method='post' action=\"".$options['target']."\">";
Dropdown::show('CartridgeItem', ['name' => 'cartridges_id',
'value' => $a_cartridge['cartridges_id'],
'comments' => false,
'entity' => $printer->fields['entities_id'],
'entity_sons' => $this->isRecursive(),
'used' => $exclude_cartridges]);
echo "&nbsp;<input type='hidden' name='id' value='".$a_cartridge["id"]."'/>";
echo "<input type='submit' name='update_cartridge' value=\"".__('Update')."\" class='submit'>";
Html::closeForm();
echo "</td>";
echo "<td align='center'>";
if ($a_cartridge['state'] == 100000) {
echo __('OK');
} else if ($a_cartridge['state'] < 0) {
$a_cartridge['state'] = $a_cartridge['state'] * -1;
echo $a_cartridge['state'];
echo ' '.__('remaining pages', 'fusioninventory');
} else if ($mapping->fields['name'] == 'paperrollinches') {
echo $a_cartridge['state']." inches";
} else if ($mapping->fields['name'] == 'paperrollcentimeters') {
echo $a_cartridge['state']." centimeters";
} else {
PluginFusioninventoryDisplay::bar($a_cartridge['state']);
}
echo "</td>";
echo "</tr>";
}
echo "</table>";
echo "</div>";
return true;
}
}

View File

@@ -0,0 +1,849 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the printer changes (history).
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access this file directly");
}
/**
* Manage the printer changes (history).
*/
class PluginFusioninventoryPrinterLog extends CommonDBTM {
/**
* Get search function for the class
*
* @return array
*/
function rawSearchOptions() {
$tab = [];
$tab[] = [
'id' => 'common',
'name' => __('History meter printer', 'fusioninventory')
];
$tab[] = [
'id' => '1',
'table' => "glpi_printers",
'field' => 'name',
'linkfield' => 'printers_id',
'name' => __('Name'),
'datatype' => 'itemlink',
'itemlink_type' => 'Printer',
];
$tab[] = [
'id' => '2',
'table' => $this->getTable(),
'field' => 'id',
'name' => 'id',
];
$tab[] = [
'id' => '24',
'table' => 'glpi_locations',
'field' => 'name',
'linkfield' => 'locations_id',
'name' => __('Location'),
'datatype' => 'itemlink',
'itemlink_type' => 'Location',
];
$tab[] = [
'id' => '19',
'table' => 'glpi_printertypes',
'field' => 'name',
'linkfield' => 'printertypes_id',
'name' => __('Type'),
'datatype' => 'itemlink',
'itemlink_type' => 'PrinterType',
];
// $tab[] = [
// 'id' => 2,
// 'table' => 'glpi_printermodels',
// 'field' => 'name',
// 'linkfield' => 'printermodels_id',
// 'name' => __('Model'),
// 'datatype' => 'itemptype',
// ];
$tab[] = [
'id' => '18',
'table' => 'glpi_states',
'field' => 'name',
'linkfield' => 'states_id',
'name' => __('Status'),
'datatype' => '>dropdown',
];
$tab[] = [
'id' => '20',
'table' => 'glpi_printers',
'field' => 'serial',
'linkfield' => 'printers_id',
'name' => __('Serial Number'),
];
$tab[] = [
'id' => '23',
'table' => 'glpi_printers',
'field' => 'otherserial',
'linkfield' => 'printers_id',
'name' => __('Inventory number'),
];
$tab[] = [
'id' => '21',
'table' => 'glpi_users',
'field' => 'name',
'linkfield' => 'users_id',
'name' => __('User'),
];
$tab[] = [
'id' => '3',
'table' => 'glpi_manufacturers',
'field' => 'name',
'linkfield' => 'manufacturers_id',
'name' => Manufacturer::getTypeName(1),
];
$joinparams = [
'jointype' => 'itemtype_item',
'specific_itemtype' => 'Printer',
];
$networkNameJoin = [
'jointype' => 'itemtype_item',
'specific_itemtype' => 'NetworkPort',
'beforejoin' => [
'table' => 'glpi_networkports',
'joinparams' => $joinparams,
],
];
$tab[] = [
'id' => '5',
'table' => 'glpi_ipaddresses',
'field' => 'name',
'name' => __('IP'),
'forcegroupby' => true,
'massiveaction' => false,
'joinparams' => [
'jointype' => 'itemtype_item',
'specific_itemtype' => 'NetworkName',
'beforejoin' => [
'table' => 'glpi_networknames',
'joinparams'
=> $networkNameJoin,
],
],
];
$tab[] = [
'id' => '6',
'table' => 'glpi_plugin_fusioninventory_printerlogs',
'field' => 'pages_total',
'linkfield' => 'id',
'name' => __('Total number of printed pages', 'fusioninventory'),
];
$tab[] = [
'id' => '7',
'table' => 'glpi_plugin_fusioninventory_printerlogs',
'field' => 'pages_n_b',
'linkfield' => 'id',
'name' => __('Number of printed black and white pages', 'fusioninventory'),
];
$tab[] = [
'id' => '8',
'table' => 'glpi_plugin_fusioninventory_printerlogs',
'field' => 'pages_color',
'linkfield' => 'id',
'name' => __('Number of printed color pages', 'fusioninventory'),
];
$tab[] = [
'id' => '9',
'table' => $this->getTable(),
'field' => 'pages_recto_verso',
'linkfield' => 'id',
'name' => __('Number of pages printed duplex', 'fusioninventory'),
];
$tab[] = [
'id' => '10',
'table' => $this->getTable(),
'field' => 'scanned',
'linkfield' => 'id',
'name' => __('Number of scanned pages', 'fusioninventory'),
];
$tab[] = [
'id' => '11',
'table' => $this->getTable(),
'field' => 'pages_total_print',
'linkfield' => 'id',
'name' => __('Total number of printed pages (print)', 'fusioninventory'),
];
$tab[] = [
'id' => '12',
'table' => $this->getTable(),
'field' => 'pages_n_b_print',
'linkfield' => 'id',
'name' => __('Number of printed black and white pages (print)', 'fusioninventory'),
];
$tab[] = [
'id' => '13',
'table' => $this->getTable(),
'field' => 'pages_color_print',
'linkfield' => 'id',
'name' => __('Number of printed color pages (print)', 'fusioninventory'),
];
$tab[] = [
'id' => '14',
'table' => $this->getTable(),
'field' => 'pages_total_copy',
'linkfield' => 'id',
'name' => __('Total number of printed pages (copy)', 'fusioninventory'),
];
$tab[] = [
'id' => '15',
'table' => $this->getTable(),
'field' => 'pages_n_b_copy',
'linkfield' => 'id',
'name' => __('Number of printed black and white pages (copy)', 'fusioninventory'),
];
$tab[] = [
'id' => '16',
'table' => $this->getTable(),
'field' => 'pages_color_copy',
'linkfield' => 'id',
'name' => __('Number of printed color pages (copy)', 'fusioninventory'),
];
$tab[] = [
'id' => '17',
'table' => $this->getTable(),
'field' => 'pages_total_fax',
'linkfield' => 'id',
'name' => __('Total number of printed pages (fax)', 'fusioninventory'),
];
return $tab;
}
/**
* Count number entries for the printer
*
* @global object $DB
* @param integer $printers_id
* @return integer
*/
function countAllEntries($printers_id) {
global $DB;
$num = 0;
$query = "SELECT count(DISTINCT `id`)
FROM ".$this->getTable()."
WHERE `printers_id` = '".$printers_id."';";
$result_num=$DB->query($query);
if ($result_num) {
$field = $DB->result($result_num, 0, 0);
if ($field) {
$num += $field;
}
}
return $num;
}
/**
* Get logs of printer
*
* @global object $DB
* @param integer $printers_id
* @param integer $begin
* @param integer $limit
* @return array|false
*/
function getEntries($printers_id, $begin, $limit) {
global $DB;
$datas=[];
$query = "SELECT *
FROM ".$this->getTable()."
WHERE `printers_id` = '".$printers_id."'
LIMIT ".$begin.", ".$limit.";";
$result=$DB->query($query);
if ($result) {
$i = 0;
while ($data=$DB->fetchAssoc($result)) {
$data['date'] = Html::convDateTime($data['date']);
$datas["$i"] = $data;
$i++;
}
return $datas;
}
return false;
}
/**
* Get printed pages statistics
*
* @global object $DB
* @param integer $printers_id
* @return array|false
*/
function stats($printers_id) {
global $DB;
$query = "SELECT MIN(`date`) AS `min_date`, MIN(`pages`) AS `min_pages`, ".
"MAX(`date`) AS `max_date`, MAX(`pages`) AS `max_pages`
FROM ".$this->getTable()."
WHERE `printers_id` = '".$printers_id."';";
$result = $DB->query($query);
if ($result) {
$fields = $DB->fetchAssoc($result);
if ($fields) {
$output = [];
$output['num_days'] =
ceil((strtotime($fields['max_date']) - strtotime($fields['min_date']))/(60*60*24));
$output['num_pages'] = $fields['max_pages'] - $fields['min_pages'];
$output['pages_per_day'] = round($output['num_pages'] / $output['num_days']);
return $output;
}
}
return false;
}
/**
* Display form
*
* @param integer $printers_id
* @param array $options
* @return boolean
*/
function showForm($printers_id, $options = []) {
if (!Session::haveRight('plugin_fusioninventory_printer', READ)) {
return false;
}
// display stats
$stats = $this->stats($printers_id);
if ($stats) {
$this->initForm($printers_id, $options);
$this->showFormHeader($options);
echo "<tr class='tab_bg_1'>";
echo "<td>".__('Total printed pages', 'fusioninventory')." : </td>";
echo "<td>".$stats["num_pages"]."</td></tr>";
echo "<tr class='tab_bg_1'>";
echo "<td>".__('Pages / day', 'fusioninventory')." : </td>";
echo "<td>".$stats["pages_per_day"]."</td></tr>";
echo "</table></div>";
}
// preparing to display history
if (!isset($_GET['start'])) {
$_GET['start'] = 0;
}
$numrows = $this->countAllEntries($printers_id);
$parameters = "id=".$_GET["id"]."&onglet=".$_SESSION["glpi_onglet"];
echo "<br>";
Html::printPager($_GET['start'], $numrows, $_SERVER['PHP_SELF'], $parameters);
$limit = $numrows;
if ($_SESSION["glpilist_limit"] < $numrows) {
$limit = $_SESSION["glpilist_limit"];
}
// Get history
$data = $this->getEntries($printers_id, $_GET['start'], $limit);
if (!($data)) {
return false;
}
echo "<div align='center'><form method='post' name='printer_history_form'
id='printer_history_form' action=\"".Toolbox::getItemTypeFormURL(__CLASS__)."\">";
echo "<table class='tab_cadre' cellpadding='5'><tr><th colspan='3'>";
echo __('History meter printer', 'fusioninventory')." :</th></tr>";
echo "<tr class='tab_bg_1'>";
echo "<th></th>";
echo "<th>"._n('Date', 'Dates', 1)." :</th>";
echo "<th>".__('Meter', 'fusioninventory')." :</th></tr>";
for ($i=0; $i<$limit; $i++) {
echo "<tr class='tab_bg_1'>";
echo "<td align='center'>";
Html::showCheckbox(['name' => "checked_$i", 'value' => 1]);
echo "</td>";
echo "<td align='center'>".$data["$i"]['date']."</td>";
echo "<td align='center'>".$data["$i"]['pages']."</td>";
echo "</td></tr>";
echo "<input type='hidden' name='ID_$i' value='".$data["$i"]['id']."'>";
}
if (!Session::haveRight('plugin_fusioninventory_printer', UPDATE)) {
return false;
}
echo "<input type='hidden' name='limit' value='".$limit."'>";
echo "<tr class='tab_bg_1'><td colspan='3'>";
echo "<div align='center'><a onclick= \"if (markAllRows('printer_history_form'))
return FALSE;\"
href='".$_SERVER['PHP_SELF']."?select=all'>".
__('Check All', 'fusioninventory')."</a>";
echo " - <a onclick= \"if (unMarkAllRows('printer_history_form')) return FALSE;\"
href='".$_SERVER['PHP_SELF']."?select=none'>".
__('Uncheck All', 'fusioninventory')."</a> ";
echo "<input type='submit' name='delete' value=\"".__('Delete', 'fusioninventory').
"\" class='submit' ></div></td></tr>";
echo "</table>";
Html::closeForm();
echo "</div>";
return true;
}
/**
* Display printer graph form
*
* @global object $DB
* @global array $CFG_GLPI
* @param integer $id the id of printer
* @param array $options
*/
function showGraph($id, $options = []) {
global $DB, $CFG_GLPI;
$printer = new Printer();
$where='';
$begin='';
$end='';
$timeUnit='day';
$graphField='pages_total';
$pagecounters = [];$graphType='day';
if (isset($_SESSION['glpi_plugin_fusioninventory_graph_begin'])) {
$begin = $_SESSION['glpi_plugin_fusioninventory_graph_begin'];
}
if ($begin == 'NULL' OR $begin == '') {
$begin = date("Y-m-01"); // first day of current month
}
if (isset($_SESSION['glpi_plugin_fusioninventory_graph_end'])) {
$end=$_SESSION['glpi_plugin_fusioninventory_graph_end'];
}
if (isset($_SESSION['glpi_plugin_fusioninventory_graph_type'])) {
$graphType = $_SESSION['glpi_plugin_fusioninventory_graph_type'];
}
if ($end == 'NULL' OR $end == '') {
$end = date("Y-m-d"); // today
}
if (isset($_SESSION['glpi_plugin_fusioninventory_graph_timeUnit'])) {
$timeUnit = $_SESSION['glpi_plugin_fusioninventory_graph_timeUnit'];
}
if (!isset($_SESSION['glpi_plugin_fusioninventory_graph_printersComp'])) {
$_SESSION['glpi_plugin_fusioninventory_graph_printersComp']=[];
}
if (isset($_SESSION['glpi_plugin_fusioninventory_graph_printerCompAdd'])) {
$printerCompAdd = $_SESSION['glpi_plugin_fusioninventory_graph_printerCompAdd'];
if (!key_exists($printerCompAdd,
$_SESSION['glpi_plugin_fusioninventory_graph_printersComp'])) {
$oPrinter = new Printer();
if ($oPrinter->getFromDB($printerCompAdd)) {
$_SESSION['glpi_plugin_fusioninventory_graph_printersComp'][$printerCompAdd] =
$oPrinter->getField('name');
}
}
} else if (isset($_SESSION['glpi_plugin_fusioninventory_graph_printerCompRemove'])) {
unset($_SESSION['glpi_plugin_fusioninventory_graph_printersComp'][$_SESSION['glpi_plugin_fusioninventory_graph_printerCompRemove']]);
}
$oPrinter = new Printer();
$printers = $_SESSION['glpi_plugin_fusioninventory_graph_printersComp'];
$printersView = $printers; // printers without the current printer
if (isset($printersView[$id])) {
unset($printersView[$id]);
} else {
if ($oPrinter->getFromDB($id)) {
$printers[$id] = $oPrinter->getField('name');
}
}
$printersList = '';
foreach ($printers as $printers_id=>$printername) {
if ($printersList != '') {
$printersList .= '<br/>';
}
if ($printers_id == $id) {
$printersList .= $printername;
} else {
$oPrinter->getFromDB($printers_id);
$printersList .= $oPrinter->getLink(1);
}
}
$printersIds = "";
foreach (array_keys($printers) as $printerId) {
if ($printersIds != '') {
$printersIds.=', ';
}
$printersIds .= $printerId;
}
$where = " WHERE `printers_id` IN(".$printersIds.")";
if ($begin!='' || $end!='') {
$where .= " AND " .self::getDateRequest("`date`", $begin, $end);
}
$group = '';
switch ($timeUnit) {
case 'day':
$group = "GROUP BY `printers_id`, `year`, `month`, `day`";
break;
case 'week':
$group = "GROUP BY `printers_id`, `year`, `month`, `week`";
break;
case 'month':
$group = "GROUP BY `printers_id`, `year`, `month`";
break;
case 'year':
$group = "GROUP BY `printers_id`, `year`";
break;
}
echo "<form method='post' name='snmp_form' id='snmp_form' action='".
Plugin::getWebDir('fusioninventory')."/front/printer_info.form.php'>";
echo "<table class='tab_cadre' cellpadding='5' width='950'>";
$mapping = new PluginFusioninventoryMapping();
$maps = $mapping->find(['itemtype' => 'Printer']);
foreach ($maps as $mapfields) {
if (!isset($mapfields["shortlocale"])) {
$mapfields["shortlocale"] = $mapfields["locale"];
}
$pagecounters[$mapfields['name']] = $mapping->getTranslation($mapfields);
}
echo "<tr class='tab_bg_1'>";
echo "<th colspan='4'>";
echo __('Printed page counter', 'fusioninventory');
echo "</th>";
echo "</tr>";
echo "<tr class='tab_bg_1'>";
echo "<td class='left'>".__('Start date')."&nbsp;:</td>";
echo "<td class='left'>";
Html::showDateField("graph_begin", ['value' => $begin]);
echo "</td>";
echo "<td class='left'>".__('Time unit', 'fusioninventory')."&nbsp;:</td>";
echo "<td class='left'>";
$elementsTime=['day' => _n('Day', 'Days', 1),
'week' => __('Week'),
'month'=> _n('Month', 'Months', 1),
'year' => __('Year', 'fusioninventory')];
Dropdown::showFromArray('graph_timeUnit', $elementsTime,
['value'=>$timeUnit]);
echo "</td>";
echo "</tr>";
echo "<tr class='tab_bg_1'>";
echo "<td class='left'>".__('End date')."&nbsp;:</td>";
echo "<td class='left'>";
Html::showDateField("graph_end", ['value' => $end]);
echo "</td>";
echo "<td class='left'>".__('Display', 'fusioninventory')."&nbsp;:</td>";
echo "<td class='left'>";
$elements=['total'=>__('Total counter', 'fusioninventory'),
'day'=>__('pages per day', 'fusioninventory')];
Dropdown::showFromArray('graph_type', $elements,
['value'=>$graphType]);
echo "</td>";
echo "</tr>";
echo "<tr class='tab_bg_2'>";
echo "<td class='center' colspan='4'>
<input type='submit' class='submit' name='graph_plugin_fusioninventory_printer_period'
value='" . __('Update') . "'/>";
echo "</td>";
echo "</tr>\n";
echo "<tr>";
echo "<th colspan='4'>".__('Printers to compare', 'fusioninventory')."</th>";
echo "</tr>";
echo "<tr class='tab_bg_1'>";
echo "<td class='left' rowspan='3'>".__('Printer')."&nbsp;:</td>";
echo "<td class='left' rowspan='3'>";
echo $printersList;
echo "</td>";
echo "<td class='left'>".__('Add a printer', 'fusioninventory')."&nbsp;:</td>";
echo "<td class='left'>";
$printersused = [];
foreach ($printersView as $printer_id=>$name) {
$printersused[] = $printer_id;
}
$printer->getFromDB($id);
Dropdown::show('Printer', ['name' =>'graph_printerCompAdd',
'entity' => $printer->fields['entities_id'],
'used' => $printersused]);
echo "&nbsp;<input type='submit' value=\"".__('Add')."\" class='submit' ".
"name='graph_plugin_fusioninventory_printer_add'>";
echo "</td>";
echo "</tr>\n";
echo "<tr class='tab_bg_1'>";
echo "<td class='left'>".__('Remove a printer', 'fusioninventory')."&nbsp;:</td>";
echo "<td class='left'>";
$printersTmp = $printersView;
$printersTmp[0] = "-----";
asort($printersTmp);
Dropdown::showFromArray('graph_printerCompRemove', $printersTmp);
echo "&nbsp;<input type='submit' value=\"".__('Delete', 'fusioninventory')."\" ".
"class='submit' name='graph_plugin_fusioninventory_printer_remove'>";
echo "</td>";
echo "</tr>\n";
echo "<tr class='tab_bg_1'>";
echo "<td colspan='2'></td>";
echo "</tr>";
echo "</table>";
Html::closeForm();
$elementsField=[
'pages_total' => $pagecounters['pagecountertotalpages'],
'pages_n_b' => $pagecounters['pagecounterblackpages'],
'pages_color' => $pagecounters['pagecountercolorpages'],
'pages_recto_verso' => $pagecounters['pagecounterrectoversopages'],
'scanned' => $pagecounters['pagecounterscannedpages'],
'pages_total_print' => $pagecounters['pagecountertotalpages_print'],
'pages_n_b_print' => $pagecounters['pagecounterblackpages_print'],
'pages_color_print' => $pagecounters['pagecountercolorpages_print'],
'pages_total_copy' => $pagecounters['pagecountertotalpages_copy'],
'pages_n_b_copy' => $pagecounters['pagecounterblackpages_copy'],
'pages_color_copy' => $pagecounters['pagecountercolorpages_copy'],
'pages_total_fax' => $pagecounters['pagecountertotalpages_fax']];
echo "<br/>";
$a_graph = [];
foreach ($elementsField as $graphField=>$name) {
$query = "SELECT `printers_id`, DAY(`date`)-1 AS `day`, WEEK(`date`) AS `week`,
MONTH(`date`) AS `month`, YEAR(`date`) AS `year`, `date`,
`$graphField`
FROM `glpi_plugin_fusioninventory_printerlogs`"
.$where.
" AND `".$graphField."` > 0 "
.$group;
$result = $DB->query($query);
if ($DB->numrows($result) == 0 AND $graphField != "pages_total") {
unset($elementsField[$graphField]);
}
}
foreach ($elementsField as $graphField=>$name) {
$query = "SELECT `printers_id`, DAY(`date`)-1 AS `day`, WEEK(`date`) AS `week`,
MONTH(`date`) AS `month`, YEAR(`date`) AS `year`, `date`,
`$graphField`
FROM `glpi_plugin_fusioninventory_printerlogs`"
.$where
.$group."
ORDER BY `year`, `month`, `day`, `printers_id`";
$input = [];
$result = $DB->query($query);
if ($result) {
if ($DB->numrows($result) != 0) {
$pages = [];
$data = [];
$date = '';
while ($data = $DB->fetchAssoc($result)) {
switch ($timeUnit) {
case 'day':
$split = explode(" ", $data['date']);
$date = $split[0];
break;
case 'week':
$split = explode(" ", $data['date']);
$date = $split[0];
break;
case 'month':
$split = explode(" ", $data['date']);
$split2 = explode("-", $split[0]);
$date = $split2[0]."-".$split2[1];
break;
case 'year':
$split = explode(" ", $data['date']);
$split2 = explode("-", $split[0]);
$date = $split2[0];
break;
}
if ($graphType == 'day') {
if (!isset($pages[$data['printers_id']])) {
$pages[$data['printers_id']] = $data[$graphField];
} else {
$y = $data[$graphField] - $pages[$data['printers_id']];
if ($y < 0) {
$y = 0;
}
$input[] = ['x' => $date,
'y' => $y];
if ($data[$graphField] > 0) {
$pages[$data['printers_id']] = $data[$graphField];
}
}
} else {
$input[] = ['x' => $date,
'y' => $data[$graphField]];
}
}
} else {
if ($graphType == 'day') {
$input[] = ['x' => date("Y-m-d"),
'y' => 0];
}
}
}
$continue = 1;
if (($continue == '0') OR ($continue == '-1')) {
echo "<table class='tab_cadre' cellpadding='5' width='900'>";
echo "<tr class='tab_bg_1'>";
echo "<th>";
echo $name;
echo "</th>";
echo "</tr>";
echo "<tr class='tab_bg_1'>";
echo "<td align='center'>";
if ($continue == '0') {
echo __('Too datas to display', 'fusioninventory');
}
echo "</td>";
echo "</tr>";
echo "</table><br/>";
} else {
if (count($input) > 0) {
$split = explode(' > ', $name);
$a_graph[] = [
'key' => $split[count($split) - 1],
'values' => $input
];
}
}
}
// Display graph
echo '<div id="chartPrinter">'.
'<svg style="height: 400px; width: 950px;"></svg>'.
'</div>';
echo "<script type='text/javascript'>
function drawGraph() {
var chart = nv.models.multiBarChart();
chart.yAxis
.tickFormat(d3.format(',0f'));
d3.select('#chartPrinter svg')
.datum(exampleData())
.transition().duration(500).call(chart);
nv.utils.windowResize(chart.update);
}
";
echo ' function exampleData() {
return '.json_encode($a_graph).'
}
drawGraph();
</script>';
}
public static function getDateRequest($field, $begin, $end) {
$sql = '';
if (!empty($begin)) {
$sql .= " $field >= '$begin' ";
}
if (!empty($end)) {
if (!empty($sql)) {
$sql .= " AND ";
}
$sql .= " $field <= ADDDATE('$end' , INTERVAL 1 DAY) ";
}
return " (".$sql.") ";
}
}

View File

@@ -0,0 +1,86 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the log reports of printers.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access this file directly");
}
/**
* Manage the log reports of printers.
*/
class PluginFusioninventoryPrinterLogReport extends CommonDBTM {
/**
* __contruct function where initialize some variables
*
* @global array $CFG_GLPI
*/
function __construct() {
global $CFG_GLPI;
$this->table = "glpi_plugin_fusioninventory_printers";
$CFG_GLPI['glpitablesitemtype']["PluginFusioninventoryPrinterLogReport"] = $this->table;
}
/**
* Get search function for the class
*
* @return array
*/
function rawSearchOptions() {
$pfPrinterLog = new PluginFusioninventoryPrinterLog();
$tab = $pfPrinterLog->rawSearchOptions();
foreach ($tab as $searchOptions) {
if ($searchOptions['table'] == PluginFusioninventoryPrinterLog::getTable()) {
$tab[$searchOptions['id']]['forcegroupby']='1';
}
}
return $tab;
}
}

View File

@@ -0,0 +1,575 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the profiles in plugin.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the profiles in plugin.
*/
class PluginFusioninventoryProfile extends Profile {
/**
* The right name for this class
*
* @var string
*/
static $rightname = "config";
/*
* Old profile names:
*
* agent
* remotecontrol
* configuration
* wol
* unmanaged
* task
* iprange
* credential
* credentialip
* existantrule
* importxml
* blacklist
* ESX
* configsecurity
* networkequipment
* printer
* model
* reportprinter
* reportnetworkequipment
* packages
* status
*/
/**
* Get the mapping old rights => new rights. Require it for upgrade from old
* version of plugin FusionInventory
*
* @return array
*/
static function getOldRightsMappings() {
$types = ['agent' => 'plugin_fusioninventory_agent',
'remotecontrol' => 'plugin_fusioninventory_remotecontrol',
'configuration' => 'plugin_fusioninventory_configuration',
'wol' => 'plugin_fusioninventory_wol',
'unmanaged' => 'plugin_fusioninventory_unmanaged',
'task' => 'plugin_fusioninventory_task',
'credential' => 'plugin_fusioninventory_credential',
'credentialip' => 'plugin_fusioninventory_credentialip',
'existantrule' => ['plugin_fusioninventory_ruleimport',
'plugin_fusioninventory_ruleentity',
'plugin_fusioninventory_rulelocation'],
'importxml' => 'plugin_fusioninventory_importxml',
'blacklist' => 'plugin_fusioninventory_blacklist',
'ESX' => 'plugin_fusioninventory_esx',
'configsecurity' => 'plugin_fusioninventory_configsecurity',
'networkequipment' => 'plugin_fusioninventory_networkequipment',
'printer' => 'plugin_fusioninventory_printer',
'reportprinter' => 'plugin_fusioninventory_reportprinter',
'reportnetworkequipment' => 'plugin_fusioninventory_reportnetworkequipment',
'packages' => 'plugin_fusioninventory_package',
'status' => 'plugin_fusioninventory_status',
'collect' => ['plugin_fusioninventory_collect',
'plugin_fusioninventory_rulecollect']];
return $types;
}
/**
* Get the tab name used for item
*
* @param object $item the item object
* @param integer $withtemplate 1 if is a template form
* @return string name of the tab
*/
function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) {
return self::createTabEntry('FusionInventory');
}
/**
* Display the content of the tab
*
* @param object $item
* @param integer $tabnum number of the tab to display
* @param integer $withtemplate 1 if is a template form
* @return boolean
*/
static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) {
$pfProfile = new self();
if ($item->fields['interface'] == 'central') {
$pfProfile->showForm($item->fields['id']);
} else {
$pfProfile->showFormSelf($item->fields['id']);
}
return true;
}
/**
* Display form
*
* @param integer $profiles_id
* @param array $options
* @return boolean
*/
function showForm($profiles_id, $options = []) {
$openform = true;
$closeform = true;
echo "<div class='firstbloc'>";
if (($canedit = Session::haveRightsOr(self::$rightname, [CREATE, UPDATE, PURGE]))
&& $openform) {
$profile = new Profile();
echo "<form method='post' action='".$profile->getFormURL()."'>";
}
$profile = new Profile();
$profile->getFromDB($profiles_id);
$rights = $this->getRightsGeneral();
$profile->displayRightsChoiceMatrix($rights, ['canedit' => $canedit,
'default_class' => 'tab_bg_2',
'title' => __('General', 'fusioninventory')]);
$rights = $this->getRightsRules();
$profile->displayRightsChoiceMatrix($rights, ['canedit' => $canedit,
'default_class' => 'tab_bg_2',
'title' => _n('Rule', 'Rules', 2)]);
$rights = $this->getRightsInventory();
$profile->displayRightsChoiceMatrix($rights, ['canedit' => $canedit,
'default_class' => 'tab_bg_2',
'title' => __('Inventory', 'fusioninventory')]);
$rights = $this->getRightsDeploy();
$profile->displayRightsChoiceMatrix($rights, ['canedit' => $canedit,
'default_class' => 'tab_bg_2',
'title' => __('Software deployment', 'fusioninventory')]);
if ($canedit
&& $closeform) {
echo "<div class='center'>";
echo Html::hidden('id', ['value' => $profiles_id]);
echo Html::submit(_sx('button', 'Save'), ['name' => 'update']);
echo "</div>\n";
Html::closeForm();
}
echo "</div>";
$this->showLegend();
return true;
}
/**
* Display profile form for helpdesk interface
*
* @param integer $profiles_id
* @param boolean $openform
* @param boolean $closeform
*/
function showFormSelf($profiles_id = 0, $openform = true, $closeform = true) {
echo "<div class='firstbloc'>";
if (($canedit = Session::haveRightsOr(self::$rightname, [CREATE, UPDATE, PURGE]))
&& $openform) {
$profile = new Profile();
echo "<form method='post' action='".$profile->getFormURL()."'>";
}
$profile = new Profile();
$profile->getFromDB($profiles_id);
$rights = [
['rights' => [READ => __('Read')],
'label' => __('Deploy packages on demand', 'fusioninventory'),
'field' => 'plugin_fusioninventory_selfpackage']
];
$profile->displayRightsChoiceMatrix($rights, ['canedit' => $canedit,
'default_class' => 'tab_bg_2',
'title' => __('Software deployment', 'fusioninventory')]);
if ($canedit
&& $closeform) {
echo "<div class='center'>";
echo Html::hidden('id', ['value' => $profiles_id]);
echo Html::submit(_sx('button', 'Save'), ['name' => 'update']);
echo "</div>\n";
Html::closeForm();
}
echo "</div>";
$this->showLegend();
}
/**
* Delete profiles
*/
static function uninstallProfile() {
$pfProfile = new self();
$a_rights = $pfProfile->getAllRights();
foreach ($a_rights as $data) {
ProfileRight::deleteProfileRights([$data['field']]);
}
}
/**
* Get all rights
*
* @return array
*/
function getAllRights() {
$a_rights = [];
$a_rights = array_merge($a_rights, $this->getRightsGeneral());
$a_rights = array_merge($a_rights, $this->getRightsInventory());
$a_rights = array_merge($a_rights, $this->getRightsRules());
$a_rights = array_merge($a_rights, $this->getRightsDeploy());
return $a_rights;
}
/**
* Get rights for rules part
*
* @return array
*/
function getRightsRules() {
$rights = [
['itemtype' => 'PluginFusioninventoryInventoryRuleImport',
'label' => __('Rules for import and link computers'),
'field' => 'plugin_fusioninventory_ruleimport'
],
['itemtype' => 'PluginFusioninventoryInventoryRuleEntity',
'label' => __('Entity rules', 'fusioninventory'),
'field' => 'plugin_fusioninventory_ruleentity'
],
['itemtype' => 'PluginFusioninventoryInventoryRuleImport',
'label' => __('Rules for import and link computers'),
'field' => 'plugin_fusioninventory_rulelocation'
],
['itemtype' => 'PluginFusioninventoryInventoryComputerBlacklist',
'label' => __('Fields blacklist', 'fusioninventory'),
'field' => 'plugin_fusioninventory_blacklist'
],
['itemtype' => 'PluginFusioninventoryCollectRule',
'label' => __('Computer information rules', 'fusioninventory'),
'field' => 'plugin_fusioninventory_rulecollect'
],
['itemtype' => 'PluginFusioninventoryIgnoredimportdevice',
'label' => __('Equipment ignored on import', 'fusioninventory'),
'field' => 'plugin_fusioninventory_ignoredimportdevice'
],
];
return $rights;
}
/**
* Get rights for deploy part
*
* @return array
*/
function getRightsDeploy() {
$rights = [
['itemtype' => 'PluginFusioninventoryDeployPackage',
'label' => __('Manage packages', 'fusioninventory'),
'field' => 'plugin_fusioninventory_package'],
['itemtype' => 'PluginFusioninventoryDeployPackage',
'label' => __('User interaction template', 'fusioninventory'),
'field' => 'plugin_fusioninventory_userinteractiontemplate'],
['itemtype' => 'PluginFusioninventoryDeployMirror',
'label' => __('Mirror servers', 'fusioninventory'),
'field' => 'plugin_fusioninventory_deploymirror'],
['itemtype' => 'PluginFusioninventoryDeployPackage',
'label' => __('Deploy packages on demand', 'fusioninventory'),
'field' => 'plugin_fusioninventory_selfpackage',
'rights' => [READ => __('Read')]]
];
return $rights;
}
/**
* Get rights for inventory part
*
* @return array
*/
function getRightsInventory() {
$rights = [
['itemtype' => 'PluginFusioninventoryIprange',
'label' => __('IP range configuration', 'fusioninventory'),
'field' => 'plugin_fusioninventory_iprange'],
['itemtype' => 'PluginFusioninventoryCredential',
'label' => __('Authentication for remote devices (VMware)', 'fusioninventory'),
'field' => 'plugin_fusioninventory_credential'],
['itemtype' => 'PluginFusioninventoryCredentialip',
'label' => __('Remote devices to inventory (VMware)', 'fusioninventory'),
'field' => 'plugin_fusioninventory_credentialip'],
['itemtype' => 'PluginFusioninventoryCredential',
'label' => __('VMware host', 'fusioninventory'),
'field' => 'plugin_fusioninventory_esx'],
['itemtype' => 'PluginFusioninventoryConfigSecurity',
'label' => __('SNMP credentials', 'fusioninventory'),
'field' => 'plugin_fusioninventory_configsecurity'],
['itemtype' => 'PluginFusioninventoryNetworkEquipment',
'label' => __('Network equipment SNMP', 'fusioninventory'),
'field' => 'plugin_fusioninventory_networkequipment'],
['itemtype' => 'PluginFusioninventoryPrinter',
'label' => __('Printer SNMP', 'fusioninventory'),
'field' => 'plugin_fusioninventory_printer'],
['itemtype' => 'PluginFusioninventoryUnmanaged',
'label' => __('Unmanaged devices', 'fusioninventory'),
'field' => 'plugin_fusioninventory_unmanaged'],
['itemtype' => 'PluginFusioninventoryInventoryComputerImportXML',
'label' => __('computer XML manual import', 'fusioninventory'),
'field' => 'plugin_fusioninventory_importxml'],
['rights' => [READ => __('Read')],
'label' => __('Printers report', 'fusioninventory'),
'field' => 'plugin_fusioninventory_reportprinter'],
['rights' => [READ => __('Read')],
'label' => __('Network report'),
'field' => 'plugin_fusioninventory_reportnetworkequipment'],
['itemtype' => 'PluginFusioninventoryLock',
'label' => __('Lock', 'fusioninventory'),
'field' => 'plugin_fusioninventory_lock']
];
return $rights;
}
/**
* Get general rights
*
* @return array
*/
function getRightsGeneral() {
$rights = [
['rights' => [READ => __('Read')],
'label' => __('Menu', 'fusioninventory'),
'field' => 'plugin_fusioninventory_menu'],
['itemtype' => 'PluginFusioninventoryAgent',
'label' => __('Agents', 'fusioninventory'),
'field' => 'plugin_fusioninventory_agent'],
['rights' => [READ => __('Read')],
'label' => __('Agent remote control', 'fusioninventory'),
'field' => 'plugin_fusioninventory_remotecontrol'],
['rights' => [READ => __('Read'), UPDATE => __('Update')],
'itemtype' => 'PluginFusioninventoryConfig',
'label' => __('Configuration', 'fusioninventory'),
'field' => 'plugin_fusioninventory_configuration'],
['itemtype' => 'PluginFusioninventoryTask',
'label' => _n('Task', 'Tasks', 2, 'fusioninventory'),
'field' => 'plugin_fusioninventory_task'],
['rights' => [READ => __('Read')],
'label' => __('Wake On LAN', 'fusioninventory'),
'field' => 'plugin_fusioninventory_wol'],
['itemtype' => 'PluginFusioninventoryDeployGroup',
'label' => __('Groups of computers', 'fusioninventory'),
'field' => 'plugin_fusioninventory_group'],
['itemtype' => 'PluginFusioninventoryCollect',
'label' => __('Computer information', 'fusioninventory'),
'field' => 'plugin_fusioninventory_collect']
];
return $rights;
}
/**
* Add the default profile
*
* @param integer $profiles_id
* @param array $rights
*/
static function addDefaultProfileInfos($profiles_id, $rights) {
$profileRight = new ProfileRight();
foreach ($rights as $right => $value) {
if (!countElementsInTable('glpi_profilerights',
['profiles_id' => $profiles_id, 'name' => $right])) {
$myright['profiles_id'] = $profiles_id;
$myright['name'] = $right;
$myright['rights'] = $value;
$profileRight->add($myright);
//Add right to the current session
$_SESSION['glpiactiveprofile'][$right] = $value;
}
}
}
/**
* Create first access (so default profile)
*
* @param integer $profiles_id id of profile
*/
static function createFirstAccess($profiles_id) {
include_once(PLUGIN_FUSIONINVENTORY_DIR."/inc/profile.class.php");
$profile = new self();
foreach ($profile->getAllRights() as $right) {
self::addDefaultProfileInfos($profiles_id,
[$right['field'] => ALLSTANDARDRIGHT]);
}
}
/**
* Delete rights stored in session
*/
static function removeRightsFromSession() {
$profile = new self();
foreach ($profile->getAllRights() as $right) {
if (isset($_SESSION['glpiactiveprofile'][$right['field']])) {
unset($_SESSION['glpiactiveprofile'][$right['field']]);
}
}
ProfileRight::deleteProfileRights([$right['field']]);
if (isset($_SESSION['glpimenu']['plugins']['types']['PluginFusioninventoryMenu'])) {
unset ($_SESSION['glpimenu']['plugins']['types']['PluginFusioninventoryMenu']);
}
if (isset($_SESSION['glpimenu']['plugins']['content']['pluginfusioninventorymenu'])) {
unset ($_SESSION['glpimenu']['plugins']['content']['pluginfusioninventorymenu']);
}
if (isset($_SESSION['glpimenu']['assets']['types']['PluginFusioninventoryUnmanaged'])) {
unset ($_SESSION['glpimenu']['plugins']['types']['PluginFusioninventoryUnmanaged']);
}
if (isset($_SESSION['glpimenu']['assets']['content']['pluginfusioninventoryunmanaged'])) {
unset ($_SESSION['glpimenu']['assets']['content']['pluginfusioninventoryunmanaged']);
}
}
/**
* Migration script for old rights from old version of plugin FusionInventory
*/
static function migrateProfiles() {
//Get all rights from the old table
$profiles = getAllDataFromTable(getTableForItemType(__CLASS__));
//Load mapping of old rights to their new equivalent
$oldrights = self::getOldRightsMappings();
//For each old profile : translate old right the new one
foreach ($profiles as $profile) {
switch ($profile['right']) {
case 'r' :
$value = READ;
break;
case 'w':
$value = ALLSTANDARDRIGHT;
break;
case 0:
default:
$value = 0;
break;
}
//Write in glpi_profilerights the new fusioninventory right
if (isset($oldrights[$profile['type']])) {
//There's one new right corresponding to the old one
if (!is_array($oldrights[$profile['type']])) {
self::addDefaultProfileInfos($profile['profiles_id'],
[$oldrights[$profile['type']] => $value]);
} else {
//One old right has been splitted into serveral new ones
foreach ($oldrights[$profile['type']] as $newtype) {
self::addDefaultProfileInfos($profile['profiles_id'],
[$newtype => $value]);
}
}
}
}
}
/**
* Init profiles during installation:
* - add rights in profile table for the current user's profile
* - current profile has all rights on the plugin
*/
static function initProfile() {
$pfProfile = new self();
$profile = new Profile();
$a_rights = $pfProfile->getAllRights();
foreach ($a_rights as $data) {
if (countElementsInTable("glpi_profilerights",
['name' => $data['field']]) == 0) {
ProfileRight::addProfileRights([$data['field']]);
$_SESSION['glpiactiveprofile'][$data['field']] = 0;
}
}
// Add all rights to current profile of the user
if (isset($_SESSION['glpiactiveprofile'])) {
$dataprofile = [];
$dataprofile['id'] = $_SESSION['glpiactiveprofile']['id'];
$profile->getFromDB($_SESSION['glpiactiveprofile']['id']);
foreach ($a_rights as $info) {
if (is_array($info)
&& ((!empty($info['itemtype'])) || (!empty($info['rights'])))
&& (!empty($info['label'])) && (!empty($info['field']))) {
if (isset($info['rights'])) {
$rights = $info['rights'];
} else {
$rights = $profile->getRightsFor($info['itemtype']);
}
foreach ($rights as $right => $label) {
$dataprofile['_'.$info['field']][$right] = 1;
$_SESSION['glpiactiveprofile'][$data['field']] = $right;
}
}
}
$profile->update($dataprofile);
}
}
}

View File

@@ -0,0 +1,407 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the import rules used for each import /
* update into GLPI.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the import rules used for each import / update into GLPI.
*/
class PluginFusioninventoryRulematchedlog extends CommonDBTM {
/**
* The right name for this class
*
* @var string
*/
static $rightname = 'plugin_fusioninventory_ruleimport';
/**
* Get name of this type by language of the user connected
*
* @param integer $nb number of elements
* @return string name of this type
*/
static function getTypeName($nb = 0) {
return '';
}
/**
* Count number of elements
*
* @param object $item
* @return integer
*/
static function countForItem(CommonDBTM $item) {
return countElementsInTable('glpi_plugin_fusioninventory_rulematchedlogs',
[
'itemtype' => $item->getType(),
'items_id' => $item->getField('id'),
]);
}
/**
* Get the tab name used for item
*
* @param object $item the item object
* @param integer $withtemplate 1 if is a template form
* @return string|array name of the tab
*/
function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) {
$array_ret = [];
if ($item->getType() == 'PluginFusioninventoryAgent') {
if (Session::haveRight('plugin_fusioninventory_agent', READ)) {
$array_ret[0] = self::createTabEntry(__('Import information', 'fusioninventory'));
}
} else {
$continue = true;
switch ($item->getType()) {
case 'PluginFusioninventoryAgent':
if (Session::haveRight('plugin_fusioninventory_agent', READ)) {
$array_ret[0] = self::createTabEntry(__('Import information', 'fusioninventory'));
}
break;
case 'PluginFusioninventoryUnmanaged':
$cnt = PluginFusioninventoryRulematchedlog::countForItem($item);
$array_ret[1] = self::createTabEntry(__('Import information', 'fusioninventory'), $cnt);
break;
case 'Computer':
case 'Monitor':
case 'NetworkEquipment':
case 'Peripheral':
case 'Phone':
case 'Printer':
$continue = PluginFusioninventoryToolbox::isAFusionInventoryDevice($item);
break;
default:
break;
}
if (!$continue) {
return [];
} else if (empty($array_ret)) {
$cnt = PluginFusioninventoryRulematchedlog::countForItem($item);
$array_ret[1] = self::createTabEntry(__('Import information', 'fusioninventory'), $cnt);
}
return $array_ret;
}
}
/**
* Display the content of the tab
*
* @param object $item
* @param integer $tabnum number of the tab to display
* @param integer $withtemplate 1 if is a template form
* @return boolean
*/
static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) {
$pfRulematchedlog = new self();
if ($tabnum == '0') {
if ($item->fields['id'] > 0) {
$pfRulematchedlog->showFormAgent($item->fields['id']);
return true;
}
} else if ($tabnum == '1') {
if ($item->fields['id'] > 0) {
$pfRulematchedlog->showForm($item->fields['id'], $item->getType());
$itemtype = '';
switch (get_class($item)) {
case 'Computer':
$itemtype = new PluginFusioninventoryInventoryComputerComputer();
break;
case 'Printer':
$itemtype = new PluginFusioninventoryPrinter();
break;
case 'NetworkEquipment':
$itemtype = new PluginFusioninventoryNetworkEquipment();
break;
}
return true;
}
}
return false;
}
/**
* Clean old data
*
* @global object $DB
* @param integer $items_id
* @param string $itemtype
*/
function cleanOlddata($items_id, $itemtype) {
global $DB;
$query = "SELECT `id` FROM `glpi_plugin_fusioninventory_rulematchedlogs`
WHERE `items_id` = '".$items_id."'
AND `itemtype` = '".$itemtype."'
ORDER BY `date` DESC
LIMIT 30, 50000";
$result = $DB->query($query);
while ($data=$DB->fetchArray($result)) {
$this->delete(['id'=>$data['id']]);
}
}
/**
* Display form
*
* @param integer $items_id
* @param string $itemtype
* @return true
*/
function showForm($items_id, $itemtype) {
global $DB;
$rule = new PluginFusioninventoryInventoryRuleImport();
$pfAgent = new PluginFusioninventoryAgent();
$class = PluginFusioninventoryItem::getFIItemClassInstance($itemtype);
if ($class) {
$class->showDownloadInventoryFile($items_id);
}
if (isset($_GET["start"])) {
$start = $_GET["start"];
} else {
$start = 0;
}
$params = ['FROM' => 'glpi_plugin_fusioninventory_rulematchedlogs',
'WHERE' => ['itemtype' => $itemtype,
'items_id' => intval($items_id)],
'COUNT' => 'cpt'
];
$iterator = $DB->request($params);
$number = $iterator->next()['cpt'];
// Display the pager
Html::printAjaxPager(self::getTypeName(2), $start, $number);
echo "<table class='tab_cadre_fixe' cellpadding='1'>";
echo "<tr>";
echo "<th colspan='5'>";
echo __('Rule import logs', 'fusioninventory');
echo "</th>";
echo "</tr>";
echo "<tr>";
echo "<th>";
echo _n('Date', 'Dates', 1);
echo "</th>";
echo "<th>";
echo __('Rule name', 'fusioninventory');
echo "</th>";
echo "<th>";
echo __('Agent', 'fusioninventory');
echo "</th>";
echo "<th>";
echo __('Module', 'fusioninventory');
echo "</th>";
echo "<th>";
echo _n('Criterion', 'Criteria', 2);
echo "</th>";
echo "</tr>";
$params = ['FROM' => 'glpi_plugin_fusioninventory_rulematchedlogs',
'WHERE' => ['itemtype' => $itemtype, 'items_id' => intval($items_id)],
'ORDER' => 'date DESC',
'START' => intval($start),
'LIMIT' => intval($_SESSION['glpilist_limit'])
];
foreach ($DB->request($params) as $data) {
echo "<tr class='tab_bg_1'>";
echo "<td align='center'>";
echo Html::convDateTime($data['date']);
echo "</td>";
echo "<td align='center'>";
if ($rule->getFromDB($data['rules_id'])) {
echo $rule->getLink(1);
}
echo "</td>";
echo "<td align='center'>";
if ($pfAgent->getFromDB($data['plugin_fusioninventory_agents_id'])) {
echo $pfAgent->getLink(1);
}
echo "</td>";
echo "<td>";
$a_methods = PluginFusioninventoryStaticmisc::getmethods();
foreach ($a_methods as $mdata) {
if ($mdata['method'] == $data['method']) {
echo $mdata['name'];
}
}
echo "</td>";
echo "<td>";
$criteria = importArrayFromDB($data['criteria']);
if (count($criteria) > 0) {
echo "<ul style='list-style-type:disc'>";
foreach ($criteria as $key=>$value) {
echo "<li>".$key.": ";
if (is_array($value)) {
echo implode("<br>", $value);
} else {
echo $value;
}
echo "</li>";
}
echo "</ul><hr class='criteriarule'>";
}
echo "</td>";
echo "</tr>";
}
echo "</table>";
// Display the pager
Html::printAjaxPager(self::getTypeName(2), $start, $number);
return true;
}
/**
* Display form for agent
*
* @param integer $agents_id
*/
function showFormAgent($agents_id) {
$rule = new PluginFusioninventoryInventoryRuleImport();
echo "<table class='tab_cadre_fixe' cellpadding='1'>";
echo "<tr>";
echo "<th colspan='5'>";
echo __('Rule import logs', 'fusioninventory');
echo "</th>";
echo "</tr>";
echo "<tr>";
echo "<th>";
echo _n('Date', 'Dates', 1);
echo "</th>";
echo "<th>";
echo __('Rule name', 'fusioninventory');
echo "</th>";
echo "<th>";
echo __('Item type');
echo "</th>";
echo "<th>";
echo _n('Item', 'Items', 1);
echo "</th>";
echo "<th>";
echo __('Module', 'fusioninventory');
echo "</th>";
echo "</tr>";
$allData = $this->find(['plugin_fusioninventory_agents_id' => $agents_id], ['date DESC']);
foreach ($allData as $data) {
echo "<tr class='tab_bg_1'>";
echo "<td align='center'>";
echo Html::convDateTime($data['date']);
echo "</td>";
echo "<td align='center'>";
if ($rule->getFromDB($data['rules_id'])) {
echo $rule->getLink(1);
}
echo "</td>";
echo "<td align='center'>";
$itemtype = $data['itemtype'];
$item = new $itemtype();
echo $item->getTypeName();
echo "</td>";
echo "<td align='center'>";
if ($item->getFromDB($data['items_id'])) {
echo $item->getLink(1);
}
echo "</td>";
echo "<td>";
$a_methods = PluginFusioninventoryStaticmisc::getmethods();
foreach ($a_methods as $mdata) {
if ($mdata['method'] == $data['method']) {
echo $mdata['name'];
}
}
echo "</td>";
echo "</tr>";
}
echo "</table>";
}
}

View File

@@ -0,0 +1,835 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the search engine. Same than GLPI search
* engine but with little modifications.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the search engine. Same than GLPI search engine but with little
* modifications.
*/
class PluginFusioninventorySearch extends CommonDBTM {
/**
* Define the form URL
*
* @var string
*/
public $formurl = 'monitoring/front/componentscatalog_rule.form.php';
/**
* Define the custom id field name
*
* @var string
*/
public $customIdVar = 'plugin_monitoring_componentscalalog_id';
/**
* Set the display the delete button to yes
*
* @var boolean
*/
public $displaydeletebuton = true;
/*
* ************************************************************************ *
* ************** Functions derived from Search of GLPI core ************** *
* ************************************************************************ *
*/
/**
* Specific constructDatas to manage the specific FusionInventoryComputer
* and replace with Computer for the Glpi built SQL queries.
*
* @return boolean
*/
static function constructDatas(array &$data, $onlycount = false) {
// Hack the built SQL query to use Computer rather than FusionInventoryComputer
$data['sql']['search'] = str_replace("`mainitemtype` = 'PluginFusioninventoryComputer'",
"`mainitemtype` = 'Computer'", $data['sql']['search']);
$data['sql']['search'] = str_replace("`itemtype` = 'PluginFusioninventoryComputer'",
"`itemtype` = 'Computer'", $data['sql']['search']);
Search::constructData($data, $onlycount);
}
/**
* Clone of Search::showList but only to have SQL query
*
* @global array $CFG_GLPI
* @param string $itemtype
* @param array $params
* @param integer $items_id_check
* @return boolean
*/
function constructSQL($itemtype, $params, $items_id_check = 0) {
global $CFG_GLPI;
/**
* the method Search::addMetaLeftJoin() on Software items uses
* getEntitiesRestrictRequest() which needs a list of active entities
* and ancestors at all costs.
*
* Since dynamic groups are not entity aware and Search::addMetaLeftJoin()
* does a recursive entities JOIN, the query is fixed with the root entity.
**/
if (!isset($_SESSION['glpiactiveentities_string'])) {
$entities = getSonsOf("glpi_entities", 0);
$_SESSION['glpiactiveentities_string'] = "'".implode("', '", $entities)."'";
}
if (!isset($_SESSION['glpiparententities'])) {
$_SESSION['glpiparententities'] = '';
}
// Instanciate an object to access method
$item = null;
if ($itemtype!='States' && class_exists($itemtype)) {
$item = new $itemtype();
}
// Default values of parameters
$p = [];
$p['link'] = [];//
$p['field'] = [];//
$p['contains'] = [];//
$p['searchtype'] = [];//
$p['sort'] = '1'; //
$p['order'] = 'ASC';//
$p['start'] = 0;//
$p['is_deleted'] = 0;
$p['export_all'] = 0;
$p['link2'] = '';//
$p['contains2'] = '';//
$p['field2'] = '';//
$p['itemtype2'] = '';
$p['searchtype2'] = '';
foreach ($params as $key => $val) {
$p[$key] = $val;
}
if ($p['export_all']) {
$p['start'] = 0;
}
// Manage defautll seachtype value : for SavedSearch compatibility
if (count($p['contains'])) {
foreach ($p['contains'] as $key => $val) {
if (!isset($p['searchtype'][$key])) {
$p['searchtype'][$key] = 'contains';
}
}
}
if (is_array($p['contains2']) && count($p['contains2'])) {
foreach ($p['contains2'] as $key => $val) {
if (!isset($p['searchtype2'][$key])) {
$p['searchtype2'][$key] = 'contains';
}
}
}
// $target = Toolbox::getItemTypeSearchURL($itemtype);
$limitsearchopt = Search::getCleanedOptions($itemtype);
if (isset($CFG_GLPI['union_search_type'][$itemtype])) {
$itemtable = $CFG_GLPI['union_search_type'][$itemtype];
} else {
$itemtable = getTableForItemType($itemtype);
}
$LIST_LIMIT = $_SESSION['glpilist_limit'];
// Set display type for export if define
$output_type = Search::HTML_OUTPUT;
if (isset($_GET['display_type'])) {
$output_type = $_GET['display_type'];
// Limit to 10 element
if ($_GET['display_type'] == GLOBAL_SEARCH) {
$LIST_LIMIT = GLOBAL_SEARCH_DISPLAY_COUNT;
}
}
// hack for States
if (isset($CFG_GLPI['union_search_type'][$itemtype])) {
$entity_restrict = true;
} else {
$entity_restrict = $item->isEntityAssign();
}
// $metanames = array();
// Get the items to display
// $toview = Search::addDefaultToView($itemtype);
// // Add items to display depending of personal prefs
// $displaypref = DisplayPreference::getForTypeUser($itemtype, Session::getLoginUserID());
// if (count($displaypref)) {
// foreach ($displaypref as $val) {
// array_push($toview,$val);
// }
// }
/* =========== Add for plugin Monitoring ============ */
$toview = [];
array_push($toview, 1);
// Add searched items
if (count($p['field'])>0) {
foreach ($p['field'] as $key => $val) {
if (!in_array($val, $toview) && $val!='all' && $val!='view') {
array_push($toview, $val);
}
}
}
// Add order item
if (!in_array($p['sort'], $toview)) {
array_push($toview, $p['sort']);
}
// // Special case for Ticket : put ID in front
// if ($itemtype=='Ticket') {
// array_unshift($toview, 2);
// }
// Clean toview array
$toview=array_unique($toview);
foreach ($toview as $key => $val) {
if (!isset($limitsearchopt[$val])) {
unset($toview[$key]);
}
}
// $toview_count = count($toview);
// Construct the request
//// 1 - SELECT
// request currentuser for SQL supervision, not displayed
$SELECT = "SELECT ".Search::addDefaultSelect($itemtype);
// Add select for all toview item
foreach ($toview as $key => $val) {
$SELECT .= Search::addSelect($itemtype, $val, $key, 0);
}
//// 2 - FROM AND LEFT JOIN
// Set reference table
$FROM = " FROM `$itemtable`";
// Init already linked tables array in order not to link a table several times
$already_link_tables = [];
// Put reference table
array_push($already_link_tables, $itemtable);
// Add default join
$COMMONLEFTJOIN = Search::addDefaultJoin($itemtype, $itemtable, $already_link_tables);
$FROM .= $COMMONLEFTJOIN;
$searchopt = [];
$searchopt[$itemtype] = &Search::getOptions($itemtype);
// Add all table for toview items
foreach ($toview as $key => $val) {
$FROM .= Search::addLeftJoin($itemtype, $itemtable, $already_link_tables,
$searchopt[$itemtype][$val]["table"],
$searchopt[$itemtype][$val]["linkfield"], 0, 0,
$searchopt[$itemtype][$val]["joinparams"]);
}
// Search all case :
if (in_array("all", $p['field'])) {
foreach ($searchopt[$itemtype] as $key => $val) {
// Do not search on Group Name
if (is_array($val)) {
$FROM .= Search::addLeftJoin($itemtype, $itemtable, $already_link_tables,
$searchopt[$itemtype][$key]["table"],
$searchopt[$itemtype][$key]["linkfield"], 0, 0,
$searchopt[$itemtype][$key]["joinparams"]);
}
}
}
//// 3 - WHERE
// default string
$COMMONWHERE = Search::addDefaultWhere($itemtype);
$first = empty($COMMONWHERE);
// Add deleted if item have it
if ($item && $item->maybeDeleted()) {
$LINK = " AND ";
if ($first) {
$LINK = " ";
$first = false;
}
$COMMONWHERE .= $LINK."`$itemtable`.`is_deleted` = '".$p['is_deleted']."' ";
}
// Remove template items
if ($item && $item->maybeTemplate()) {
$LINK = " AND ";
if ($first) {
$LINK = " ";
$first = false;
}
$COMMONWHERE .= $LINK."`$itemtable`.`is_template` = '0' ";
}
// Add Restrict to current entities
if ($entity_restrict) {
$LINK = " AND ";
if ($first) {
$LINK = " ";
$first = false;
}
if ($itemtype == 'Entity') {
$COMMONWHERE .= getEntitiesRestrictRequest($LINK, $itemtable, 'id', '', true);
} else if (isset($CFG_GLPI["union_search_type"][$itemtype])) {
// Will be replace below in Union/Recursivity Hack
$COMMONWHERE .= $LINK." ENTITYRESTRICT ";
} else {
$COMMONWHERE .= getEntitiesRestrictRequest($LINK, $itemtable, '', '',
$item->maybeRecursive());
}
}
$WHERE = "";
$HAVING = "";
// Add search conditions
// If there is search items
if ($_SESSION["glpisearchcount"][$itemtype]>0 && count($p['contains'])>0) {
for ($key=0; $key<$_SESSION["glpisearchcount"][$itemtype]; $key++) {
// if real search (strlen >0) and not all and view search
if (isset($p['contains'][$key]) && strlen($p['contains'][$key])>0) {
// common search
if ($p['field'][$key]!="all" && $p['field'][$key]!="view") {
$LINK = " ";
$NOT = 0;
$tmplink = "";
if (is_array($p['link']) && isset($p['link'][$key])) {
if (strstr($p['link'][$key], "NOT")) {
$tmplink = " ".str_replace(" NOT", "", $p['link'][$key]);
$NOT = 1;
} else {
$tmplink = " ".$p['link'][$key];
}
} else {
$tmplink = " AND ";
}
if (isset($searchopt[$itemtype][$p['field'][$key]]["usehaving"])) {
// Manage Link if not first item
if (!empty($HAVING)) {
$LINK = $tmplink;
}
// Find key
$item_num = array_search($p['field'][$key], $toview);
$HAVING .= Search::addHaving($LINK, $NOT, $itemtype, $p['field'][$key],
$p['searchtype'][$key], $p['contains'][$key], 0,
$item_num);
} else {
// Manage Link if not first item
if (!empty($WHERE)) {
$LINK = $tmplink;
}
$WHERE .= Search::addWhere($LINK, $NOT, $itemtype, $p['field'][$key],
$p['searchtype'][$key], $p['contains'][$key]);
}
// view and all search
} else {
$LINK = " OR ";
$NOT = 0;
$globallink = " AND ";
if (is_array($p['link']) && isset($p['link'][$key])) {
switch ($p['link'][$key]) {
case "AND" :
$LINK = " OR ";
$globallink = " AND ";
break;
case "AND NOT" :
$LINK = " AND ";
$NOT = 1;
$globallink = " AND ";
break;
case "OR" :
$LINK = " OR ";
$globallink = " OR ";
break;
case "OR NOT" :
$LINK = " AND ";
$NOT = 1;
$globallink = " OR ";
break;
}
} else {
$tmplink =" AND ";
}
// Manage Link if not first item
if (!empty($WHERE)) {
$WHERE .= $globallink;
}
$WHERE .= " ( ";
$first2 = true;
$items = [];
if ($p['field'][$key]=="all") {
$items = $searchopt[$itemtype];
} else { // toview case : populate toview
foreach ($toview as $key2 => $val2) {
$items[$val2] = $searchopt[$itemtype][$val2];
}
}
foreach ($items as $key2 => $val2) {
if (is_array($val2)) {
// Add Where clause if not to be done in HAVING CLAUSE
if (!isset($val2["usehaving"])) {
$tmplink = $LINK;
if ($first2) {
$tmplink = " ";
$first2 = false;
}
$WHERE .= Search::addWhere($tmplink, $NOT, $itemtype, $key2,
$p['searchtype'][$key], $p['contains'][$key]);
}
}
}
$WHERE .= " ) ";
}
}
}
}
//// 4 - ORDER
$ORDER = " ORDER BY `id` ";
foreach ($toview as $key => $val) {
if ($p['sort']==$val) {
$ORDER = Search::addOrderBy($itemtype, $p['sort'], $p['order'], $key);
}
}
//// 5 - META SEARCH
// Preprocessing
if ($_SESSION["glpisearchcount2"][$itemtype]>0 && is_array($p['itemtype2'])) {
// a - SELECT
for ($i=0; $i<$_SESSION["glpisearchcount2"][$itemtype]; $i++) {
if (isset($p['itemtype2'][$i])
&& !empty($p['itemtype2'][$i])
&& isset($p['contains2'][$i])
&& strlen($p['contains2'][$i])>0) {
$SELECT .= Search::addSelect($p['itemtype2'][$i], $p['field2'][$i], $i, 1,
$p['itemtype2'][$i]);
}
}
// b - ADD LEFT JOIN
// Already link meta table in order not to linked a table several times
$already_link_tables2 = [];
// Link reference tables
for ($i=0; $i<$_SESSION["glpisearchcount2"][$itemtype]; $i++) {
if (isset($p['itemtype2'][$i])
&& !empty($p['itemtype2'][$i])
&& isset($p['contains2'][$i])
&& strlen($p['contains2'][$i])>0) {
if (!in_array(getTableForItemType($p['itemtype2'][$i]), $already_link_tables2)) {
$FROM .= Search::addMetaLeftJoin($itemtype, $p['itemtype2'][$i],
$already_link_tables2,
(($p['contains2'][$i]=="NULL")
|| (strstr($p['link2'][$i], "NOT"))));
}
}
}
// Link items tables
for ($i=0; $i<$_SESSION["glpisearchcount2"][$itemtype]; $i++) {
if (isset($p['itemtype2'][$i])
&& !empty($p['itemtype2'][$i])
&& isset($p['contains2'][$i])
&& strlen($p['contains2'][$i])>0) {
if (!isset($searchopt[$p['itemtype2'][$i]])) {
$searchopt[$p['itemtype2'][$i]] = &Search::getOptions($p['itemtype2'][$i]);
}
if (!in_array($searchopt[$p['itemtype2'][$i]][$p['field2'][$i]]["table"]."_".
$p['itemtype2'][$i],
$already_link_tables2)) {
$FROM .= Search::addLeftJoin($p['itemtype2'][$i],
getTableForItemType($p['itemtype2'][$i]),
$already_link_tables2,
$searchopt[$p['itemtype2'][$i]][$p['field2'][$i]]["table"],
$searchopt[$p['itemtype2'][$i]][$p['field2'][$i]]["linkfield"],
1, $p['itemtype2'][$i],
$searchopt[$p['itemtype2'][$i]][$p['field2'][$i]]["joinparams"]);
}
}
}
}
//// 6 - Add item ID
// Add ID to the select
if (!empty($itemtable)) {
$SELECT .= "`$itemtable`.`id` AS id ";
}
//// 7 - Manage GROUP BY
$GROUPBY = "";
// Meta Search / Search All / Count tickets
if ($_SESSION["glpisearchcount2"][$itemtype]>0
|| !empty($HAVING)
|| in_array('all', $p['field'])) {
$GROUPBY = " GROUP BY `$itemtable`.`id`";
}
if (empty($GROUPBY)) {
foreach ($toview as $key2 => $val2) {
if (!empty($GROUPBY)) {
break;
}
if (isset($searchopt[$itemtype][$val2]["forcegroupby"])) {
$GROUPBY = " GROUP BY `$itemtable`.`id`";
}
}
}
// Specific search for others item linked (META search)
if (is_array($p['itemtype2'])) {
for ($key=0; $key<$_SESSION["glpisearchcount2"][$itemtype]; $key++) {
if (isset($p['itemtype2'][$key])
&& !empty($p['itemtype2'][$key])
&& isset($p['contains2'][$key])
&& strlen($p['contains2'][$key])>0) {
$LINK = "";
// For AND NOT statement need to take into account all the group by items
if (strstr($p['link2'][$key], "AND NOT")
|| isset($searchopt[$p['itemtype2'][$key]][$p['field2'][$key]]["usehaving"])) {
$NOT = 0;
if (strstr($p['link2'][$key], "NOT")) {
$tmplink = " ".str_replace(" NOT", "", $p['link2'][$key]);
$NOT = 1;
} else {
$tmplink = " ".$p['link2'][$key];
}
if (!empty($HAVING)) {
$LINK = $tmplink;
}
$HAVING .= Search::addHaving($LINK, $NOT, $p['itemtype2'][$key],
$p['field2'][$key], $p['searchtype2'][$key],
$p['contains2'][$key], 1, $key);
} else { // Meta Where Search
$LINK = " ";
$NOT = 0;
// Manage Link if not first item
if (is_array($p['link2'])
&& isset($p['link2'][$key])
&& strstr($p['link2'][$key], "NOT")) {
$tmplink = " ".str_replace(" NOT", "", $p['link2'][$key]);
$NOT = 1;
} else if (is_array($p['link2']) && isset($p['link2'][$key])) {
$tmplink = " ".$p['link2'][$key];
} else {
$tmplink = " AND ";
}
if (!empty($WHERE)) {
$LINK = $tmplink;
}
$WHERE .= Search::addWhere($LINK, $NOT, $p['itemtype2'][$key], $p['field2'][$key],
$p['searchtype2'][$key], $p['contains2'][$key], 1);
}
}
}
}
// Use a ReadOnly connection if available and configured to be used
$DBread = DBConnection::getReadConnection();
// If no research limit research to display item and compute number of
// item using simple request
$nosearch = true;
for ($i=0; $i<$_SESSION["glpisearchcount"][$itemtype]; $i++) {
if (isset($p['contains'][$i]) && strlen($p['contains'][$i])>0) {
$nosearch = false;
}
}
if ($_SESSION["glpisearchcount2"][$itemtype]>0) {
$nosearch = false;
}
$LIMIT = "";
$numrows = 0;
//No search : count number of items using a simple count(ID) request and LIMIT search
if ($nosearch) {
$LIMIT = " LIMIT ".$p['start'].", ".$LIST_LIMIT;
// Force group by for all the type -> need to count only on table ID
if (!isset($searchopt[$itemtype][1]['forcegroupby'])) {
$count = "count(*)";
} else {
$count = "count(DISTINCT `$itemtable`.`id`)";
}
// request currentuser for SQL supervision, not displayed
$query_num = "SELECT $count
FROM `$itemtable`".
$COMMONLEFTJOIN;
$first = true;
if (!empty($COMMONWHERE)) {
$LINK = " AND ";
if ($first) {
$LINK = " WHERE ";
$first = false;
}
$query_num .= $LINK.$COMMONWHERE;
}
// Union Search :
if (isset($CFG_GLPI["union_search_type"][$itemtype])) {
$tmpquery = $query_num;
$numrows = 0;
foreach ($CFG_GLPI[$CFG_GLPI["union_search_type"][$itemtype]] as $ctype) {
$ctable = getTableForItemType($ctype);
$citem = new $ctype();
if ($citem->canView()) {
// State case
if ($itemtype == 'States') {
$query_num = str_replace($CFG_GLPI["union_search_type"][$itemtype],
$ctable, $tmpquery);
$query_num .= " AND $ctable.`states_id` > '0' ";
// Add deleted if item have it
if ($citem && $citem->maybeDeleted()) {
$query_num .= " AND `$ctable`.`is_deleted` = '0' ";
}
// Remove template items
if ($citem && $citem->maybeTemplate()) {
$query_num .= " AND `$ctable`.`is_template` = '0' ";
}
} else {// Ref table case
$reftable = getTableForItemType($itemtype);
$replace = "FROM `$reftable`
INNER JOIN `$ctable`
ON (`$reftable`.`items_id` =`$ctable`.`id`
AND `$reftable`.`itemtype` = '$ctype')";
$query_num = str_replace("FROM `".$CFG_GLPI["union_search_type"][$itemtype]."`",
$replace, $tmpquery);
$query_num = str_replace($CFG_GLPI["union_search_type"][$itemtype], $ctable,
$query_num);
}
$query_num = str_replace("ENTITYRESTRICT",
getEntitiesRestrictRequest('', $ctable, '', '',
$citem->maybeRecursive()),
$query_num);
$result_num = $DBread->query($query_num);
$numrows += $DBread->result($result_num, 0, 0);
}
}
} else {
$result_num = $DBread->query($query_num);
$numrows = $DBread->result($result_num, 0, 0);
}
}
// If export_all reset LIMIT condition
if ($p['export_all']) {
$LIMIT = "";
}
if (!empty($WHERE) || !empty($COMMONWHERE)) {
if (!empty($COMMONWHERE)) {
$WHERE = ' WHERE '.$COMMONWHERE.(!empty($WHERE)?' AND ( '.$WHERE.' )':'');
} else {
$WHERE = ' WHERE '.$WHERE.' ';
}
$first = false;
}
if (!empty($HAVING)) {
$HAVING = ' HAVING '.$HAVING;
}
/* =========== Add for plugin Monitoring ============ */
if (($items_id_check > 0)) {
if ($itemtype == "PluginMonitoringNetworkport") {
if ($WHERE == '') {
$WHERE .= " WHERE `".getTableForItemType($itemtype)."`.`networkports_id`='".
$items_id_check."' ";
} else {
$WHERE .= " AND `".getTableForItemType($itemtype)."`.`networkports_id`='".
$items_id_check."' ";
}
} else {
$WHERE .= " AND `".getTableForItemType($itemtype)."`.`id`='".$items_id_check."' ";
}
}
// Create QUERY
if (isset($CFG_GLPI["union_search_type"][$itemtype])) {
$first = true;
$QUERY = "";
foreach ($CFG_GLPI[$CFG_GLPI["union_search_type"][$itemtype]] as $ctype) {
$ctable = getTableForItemType($ctype);
$citem = new $ctype();
if ($citem->canView()) {
if ($first) {
$first = false;
} else {
$QUERY .= " UNION ";
}
$tmpquery = "";
// State case
if ($itemtype == 'States') {
$tmpquery = $SELECT.", '$ctype' AS TYPE ".
$FROM.
$WHERE;
$tmpquery = str_replace($CFG_GLPI["union_search_type"][$itemtype],
$ctable, $tmpquery);
$tmpquery .= " AND `$ctable`.`states_id` > '0' ";
// Add deleted if item have it
if ($citem && $citem->maybeDeleted()) {
$tmpquery .= " AND `$ctable`.`is_deleted` = '0' ";
}
// Remove template items
if ($citem && $citem->maybeTemplate()) {
$tmpquery .= " AND `$ctable`.`is_template` = '0' ";
}
} else {// Ref table case
$reftable = getTableForItemType($itemtype);
$tmpquery = $SELECT.", '$ctype' AS TYPE,
`$reftable`.`id` AS refID, "."
`$ctable`.`entities_id` AS ENTITY ".
$FROM.
$WHERE;
$replace = "FROM `$reftable`"."
INNER JOIN `$ctable`"."
ON (`$reftable`.`items_id`=`$ctable`.`id`"."
AND `$reftable`.`itemtype` = '$ctype')";
$tmpquery = str_replace("FROM `".$CFG_GLPI["union_search_type"][$itemtype]."`",
$replace, $tmpquery);
$tmpquery = str_replace($CFG_GLPI["union_search_type"][$itemtype], $ctable,
$tmpquery);
}
$tmpquery = str_replace("ENTITYRESTRICT",
getEntitiesRestrictRequest('', $ctable, '', '',
$citem->maybeRecursive()),
$tmpquery);
// SOFTWARE HACK
if ($ctype == 'Software') {
$tmpquery = str_replace("glpi_softwares.serial", "''", $tmpquery);
$tmpquery = str_replace("glpi_softwares.otherserial", "''", $tmpquery);
}
$QUERY .= $tmpquery;
}
}
if (empty($QUERY)) {
echo Search::showError($output_type);
return;
}
$QUERY .= str_replace($CFG_GLPI["union_search_type"][$itemtype].".", "", $ORDER) . $LIMIT;
} else {
$QUERY = $SELECT.
$FROM.
$WHERE.
$GROUPBY.
$HAVING.
$ORDER.
$LIMIT;
}
$DBread->query("SET SESSION group_concat_max_len = 4096;");
$result = $DBread->query($QUERY);
/// Check group concat limit : if warning : increase limit
if ($result2 = $DBread->query('SHOW WARNINGS')) {
if ($DBread->numrows($result2) > 0) {
$data = $DBread->fetchAssoc($result2);
if ($data['Code'] == 1260) {
$DBread->query("SET SESSION group_concat_max_len = 4194304;");
$result = $DBread->query($QUERY);
}
}
}
// Get it from database and DISPLAY
if ($result) {
return $result;
} else {
return false;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,116 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the network discovery import.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access this file directly");
}
/**
* Manage the network discovery import.
*/
class PluginFusioninventorySnmpmodelImportExport extends CommonGLPI {
/**
* Import discovery devices
*
* @param array $arrayinventory
* @param string $device_id
*/
function import_netdiscovery($arrayinventory, $device_id) {
PluginFusioninventoryCommunication::addLog(
'Function PluginFusioninventorySnmpmodelImportExport->import_netdiscovery().');
$ptap = new PluginFusioninventoryStateDiscovery();
$pta = new PluginFusioninventoryAgent();
$agent = $pta->infoByKey($device_id);
if (isset($arrayinventory['AGENT']['START'])) {
$ptap->updateState($arrayinventory['PROCESSNUMBER'],
['start_time' => date("Y-m-d H:i:s")], $agent['id']);
} else if (isset($arrayinventory['AGENT']['END'])) {
$ptap->updateState($arrayinventory['PROCESSNUMBER'],
['end_time' => date("Y-m-d H:i:s")], $agent['id']);
} else if (isset($arrayinventory['AGENT']['EXIT'])) {
$ptap->endState($arrayinventory['PROCESSNUMBER'], date("Y-m-d H:i:s"), $agent['id']);
} else if (isset($arrayinventory['AGENT']['NBIP'])) {
$ptap->updateState($arrayinventory['PROCESSNUMBER'],
['nb_ip' => $arrayinventory['AGENT']['NBIP']], $agent['id']);
}
if (isset($arrayinventory['AGENT']['AGENTVERSION'])) {
$agent['last_contact'] = date("Y-m-d H:i:s");
$pta->update($agent);
}
$_SESSION['glpi_plugin_fusioninventory_agentid'] = $agent['id'];
$count_discovery_devices = 0;
if (isset($arrayinventory['DEVICE'])) {
if (is_int(key($arrayinventory['DEVICE']))) {
$count_discovery_devices = count($arrayinventory['DEVICE']);
} else {
$count_discovery_devices = 1;
}
}
if ($count_discovery_devices != "0") {
$ptap->updateState($_SESSION['glpi_plugin_fusioninventory_processnumber'],
['nb_found' => $count_discovery_devices], $agent['id']);
if (is_int(key($arrayinventory['DEVICE']))) {
foreach ($arrayinventory['DEVICE'] as $discovery) {
if (count($discovery) > 0) {
$pfCommunicationNetworkDiscovery =
new PluginFusioninventoryCommunicationNetworkDiscovery();
$pfCommunicationNetworkDiscovery->sendCriteria($discovery);
}
}
} else {
$pfCommunicationNetworkDiscovery =
new PluginFusioninventoryCommunicationNetworkDiscovery();
$pfCommunicationNetworkDiscovery->sendCriteria($arrayinventory['DEVICE']);
}
}
}
}

View File

@@ -0,0 +1,293 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the network discovery state.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access this file directly");
}
/**
* Manage the network discovery state.
*/
class PluginFusioninventoryStateDiscovery extends CommonDBTM {
/**
* The right name for this class
*
* @var string
*/
static $rightname = 'plugin_fusioninventory_task';
/**
* Update state of discovery
*
* @param integer $p_number
* @param array $a_input
* @param integer $agent_id
*/
function updateState($p_number, $a_input, $agent_id) {
$data = $this->find(
['plugin_fusioninventory_taskjob_id' => $p_number,
'plugin_fusioninventory_agents_id' => $agent_id]);
if (count($data) == "0") {
$input = [];
$input['plugin_fusioninventory_taskjob_id'] = $p_number;
$input['plugin_fusioninventory_agents_id'] = $agent_id;
$id = $this->add($input);
$this->getFromDB($id);
$data[$id] = $this->fields;
}
foreach ($data as $process_id=>$input) {
foreach ($a_input as $field=>$value) {
if ($field == 'nb_ip'
|| $field == 'nb_found'
|| $field == 'nb_error'
|| $field == 'nb_exists'
|| $field == 'nb_import') {
$input[$field] = $data[$process_id][$field] + $value;
} else {
$input[$field] = $value;
}
}
$this->update($input);
}
// If discovery and query are finished, we will end Process
$this->getFromDB($process_id);
$doEnd = 1;
if (($this->fields['threads'] != '0')
&& ($this->fields['end_time'] == '')) {
$doEnd = 0;
}
if ($doEnd == '1') {
$this->endState($p_number, date("Y-m-d H:i:s"), $agent_id);
}
}
/**
* End the state process
*
* @param integer $p_number
* @param string $date_end
* @param integer $agent_id
*/
function endState($p_number, $date_end, $agent_id) {
$data = $this->find(
['plugin_fusioninventory_taskjob_id' => $p_number,
'plugin_fusioninventory_agents_id' => $agent_id]);
foreach ($data as $input) {
$input['end_time'] = $date_end;
$this->update($input);
}
}
/**
* Display the discovery state
*
* @global object $DB
* @global array $CFG_GLPI
* @param array $options
*/
function display($options = []) {
global $DB, $CFG_GLPI;
$pfAgent = new PluginFusioninventoryAgent();
$pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
$pfTaskjoblog = new PluginFusioninventoryTaskjoblog();
$pfStateInventory = new PluginFusioninventoryStateInventory();
$pfTaskjob = new PluginFusioninventoryTaskjob();
$start = 0;
if (isset($_REQUEST["start"])) {
$start = $_REQUEST["start"];
}
// Total Number of events
$querycount = "SELECT count(*) AS cpt FROM `glpi_plugin_fusioninventory_taskjobstates`
LEFT JOIN `glpi_plugin_fusioninventory_taskjobs`
ON `plugin_fusioninventory_taskjobs_id` = `glpi_plugin_fusioninventory_taskjobs`.`id`
WHERE `method` = 'networkdiscovery'
GROUP BY `uniqid`
ORDER BY `uniqid` DESC ";
$resultcount = $DB->query($querycount);
$number = $DB->numrows($resultcount);
// Display the pager
Html::printPager($start, $number, Plugin::getWebDir('fusioninventory')."/front/statediscovery.php", '');
echo "<table class='tab_cadre_fixe'>";
echo "<tr class='tab_bg_1'>";
echo "<th>".__('Unique id', 'fusioninventory')."</th>";
echo "<th>".__('Task job', 'fusioninventory')."</th>";
echo "<th>".__('Agent', 'fusioninventory')."</th>";
echo "<th>".__('Status')."</th>";
echo "<th>".__('Starting date', 'fusioninventory')."</th>";
echo "<th>".__('Ending date', 'fusioninventory')."</th>";
echo "<th>".__('Total duration')."</th>";
echo "<th>".__('Threads number', 'fusioninventory')."</th>";
echo "<th>".__('Total discovery devices', 'fusioninventory')."</th>";
echo "<th>".__('Devices not imported', 'fusioninventory')."</th>";
echo "<th>".__('Devices linked', 'fusioninventory')."</th>";
echo "<th>".__('Devices imported', 'fusioninventory')."</th>";
echo "</tr>";
$sql = "SELECT `glpi_plugin_fusioninventory_taskjobstates`.*
FROM `glpi_plugin_fusioninventory_taskjobstates`
LEFT JOIN `glpi_plugin_fusioninventory_taskjobs`
ON `plugin_fusioninventory_taskjobs_id` = `glpi_plugin_fusioninventory_taskjobs`.`id`
WHERE `method` = 'networkdiscovery'
GROUP BY `uniqid`
ORDER BY `uniqid` DESC
LIMIT ".intval($start).", " . intval($_SESSION['glpilist_limit']);
$result=$DB->query($sql);
while ($data=$DB->fetchArray($result)) {
echo "<tr class='tab_bg_1'>";
echo "<td>".$data['uniqid']."</td>";
$pfTaskjob->getFromDB($data['plugin_fusioninventory_taskjobs_id']);
echo "<td>";
$link = $pfTaskjob->getLink();
$link = str_replace('.form', '', $link);
echo $link;
echo "</td>";
$pfAgent->getFromDB($data['plugin_fusioninventory_agents_id']);
echo "<td>".$pfAgent->getLink(1)."</td>";
$nb_found = 0;
$nb_threads = 0;
$start_date = "";
$end_date = "";
$notimporteddevices= 0;
$updateddevices = 0;
$createddevices = 0;
$a_taskjobstates = $pfTaskjobstate->find(['uniqid' => $data['uniqid']]);
foreach ($a_taskjobstates as $datastate) {
$a_taskjoblog = $pfTaskjoblog->find(['plugin_fusioninventory_taskjobstates_id' => $datastate['id']]);
foreach ($a_taskjoblog as $taskjoblog) {
if (strstr($taskjoblog['comment'], " ==devicesfound==")) {
$nb_found += str_replace(" ==devicesfound==", "", $taskjoblog['comment']);
} else if (strstr($taskjoblog['comment'], "==importdenied==")) {
$notimporteddevices++;
} else if (strstr($taskjoblog['comment'], "==updatetheitem==")) {
$updateddevices++;
} else if (strstr($taskjoblog['comment'], "==addtheitem==")) {
$createddevices++;
} else if ($taskjoblog['state'] == "1") {
$nb_threads = str_replace(" threads", "", $taskjoblog['comment']);
$start_date = $taskjoblog['date'];
}
if (($taskjoblog['state'] == "2")
OR ($taskjoblog['state'] == "3")
OR ($taskjoblog['state'] == "4")
OR ($taskjoblog['state'] == "5")) {
if (!strstr($taskjoblog['comment'], 'Merged with ')) {
$end_date = $taskjoblog['date'];
}
}
}
}
// State
echo "<td>";
switch ($data['state']) {
case 0:
echo __('Prepared', 'fusioninventory');
break;
case 1:
case 2:
echo __('Started', 'fusioninventory');
break;
case 3:
echo __('Finished tasks', 'fusioninventory');
break;
}
echo "</td>";
echo "<td>".Html::convDateTime($start_date)."</td>";
echo "<td>".Html::convDateTime($end_date)."</td>";
if ($end_date == '') {
$end_date = date("Y-m-d H:i:s");
}
if ($start_date == '') {
echo "<td>-</td>";
} else {
$interval = '';
if (phpversion() >= 5.3) {
$date1 = new DateTime($start_date);
$date2 = new DateTime($end_date);
$interval = $date1->diff($date2);
$display_date = '';
if ($interval->h > 0) {
$display_date .= $interval->h."h ";
} else if ($interval->i > 0) {
$display_date .= $interval->i."min ";
}
echo "<td>".$display_date.$interval->s."s</td>";
} else {
$interval = $pfStateInventory->dateDiff($start_date, $end_date);
}
}
echo "<td>".$nb_threads."</td>";
echo "<td>".$nb_found."</td>";
echo "<td>".$notimporteddevices."</td>";
echo "<td>".$updateddevices."</td>";
echo "<td>".$createddevices."</td>";
echo "</tr>";
}
echo "</table>";
}
}

View File

@@ -0,0 +1,256 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the network inventory state.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access this file directly");
}
/**
* Manage the network inventory state.
*/
class PluginFusioninventoryStateInventory extends CommonDBTM {
/**
* The right name for this class
*
* @var string
*/
static $rightname = 'plugin_fusioninventory_task';
/**
* __contruct function where add variable in $CFG_GLPI
*
* @global array $CFG_GLPI
*/
function __construct() {
global $CFG_GLPI;
$CFG_GLPI['glpitablesitemtype']['PluginFusioninventoryStateInventory'] =
'glpi_plugin_fusioninventory_taskjobstates';
}
/**
* Display network inventory state
*
* @global object $DB
* @global array $CFG_GLPI
* @param array $options
*/
function display($options = []) {
global $DB, $CFG_GLPI;
$pfAgent = new PluginFusioninventoryAgent();
$pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
$pfTaskjoblog = new PluginFusioninventoryTaskjoblog();
$pfTaskjob = new PluginFusioninventoryTaskjob();
$start = 0;
if (isset($_REQUEST["start"])) {
$start = $_REQUEST["start"];
}
// Total Number of events
$querycount = "SELECT count(*) AS cpt FROM `glpi_plugin_fusioninventory_taskjobstates`
LEFT JOIN `glpi_plugin_fusioninventory_taskjobs`
ON `plugin_fusioninventory_taskjobs_id` = `glpi_plugin_fusioninventory_taskjobs`.`id`
WHERE `method` = 'networkinventory'
GROUP BY `uniqid`
ORDER BY `uniqid` DESC ";
$resultcount = $DB->query($querycount);
$number = $DB->numrows($resultcount);
// Display the pager
Html::printPager($start, $number, Plugin::getWebDir('fusioninventory')."/front/stateinventory.php", '');
echo "<table class='tab_cadre_fixe'>";
echo "<tr class='tab_bg_1'>";
echo "<th>".__('Unique id', 'fusioninventory')."</th>";
echo "<th>".__('Task job', 'fusioninventory')."</th>";
echo "<th>".__('Agent', 'fusioninventory')."</th>";
echo "<th>".__('Status')."</th>";
echo "<th>".__('Starting date', 'fusioninventory')."</th>";
echo "<th>".__('Ending date', 'fusioninventory')."</th>";
echo "<th>".__('Total duration')."</th>";
echo "<th>".__('Number per second', 'fusioninventory')."</th>";
echo "<th>".__('Threads number', 'fusioninventory')."</th>";
echo "<th>".__('To inventory', 'fusioninventory')."</th>";
echo "<th>".__('Error(s)', 'fusioninventory')."</th>";
echo "</tr>";
$sql = "SELECT `glpi_plugin_fusioninventory_taskjobstates`.*
FROM `glpi_plugin_fusioninventory_taskjobstates`
LEFT JOIN `glpi_plugin_fusioninventory_taskjobs`
ON `plugin_fusioninventory_taskjobs_id` = `glpi_plugin_fusioninventory_taskjobs`.`id`
WHERE `method` = 'networkinventory'
GROUP BY `uniqid`
ORDER BY `uniqid` DESC
LIMIT ".intval($start).", " . intval($_SESSION['glpilist_limit']);
$result=$DB->query($sql);
while ($data=$DB->fetchArray($result)) {
echo "<tr class='tab_bg_1'>";
echo "<td>".$data['uniqid']."</td>";
$pfTaskjob->getFromDB($data['plugin_fusioninventory_taskjobs_id']);
echo "<td>";
$link = $pfTaskjob->getLink();
$link = str_replace('.form', '', $link);
echo $link;
echo "</td>";
$pfAgent->getFromDB($data['plugin_fusioninventory_agents_id']);
echo "<td>".$pfAgent->getLink(1)."</td>";
$nb_query = 0;
$nb_threads = 0;
$start_date = "";
$end_date = "";
$nb_errors = 0;
$a_taskjobstates = $pfTaskjobstate->find(['uniqid' => $data['uniqid']]);
foreach ($a_taskjobstates as $datastate) {
$a_taskjoblog = $pfTaskjoblog->find(['plugin_fusioninventory_taskjobstates_id' => $datastate['id']]);
foreach ($a_taskjoblog as $taskjoblog) {
if (strstr($taskjoblog['comment'], " ==devicesqueried==")) {
$nb_query += str_replace(" ==devicesqueried==", "", $taskjoblog['comment']);
} else if (strstr($taskjoblog['comment'], " No response from remote host")) {
$nb_errors++;
} else if ($taskjoblog['state'] == "1") {
$nb_threads = str_replace(" threads", "", $taskjoblog['comment']);
$start_date = $taskjoblog['date'];
}
if (($taskjoblog['state'] == "2")
OR ($taskjoblog['state'] == "3")
OR ($taskjoblog['state'] == "4")
OR ($taskjoblog['state'] == "5")) {
if (!strstr($taskjoblog['comment'], 'Merged with ')) {
$end_date = $taskjoblog['date'];
}
}
}
}
// State
echo "<td>";
switch ($data['state']) {
case 0:
echo __('Prepared', 'fusioninventory');
break;
case 1:
case 2:
echo __('Started', 'fusioninventory');
break;
case 3:
echo __('Finished tasks', 'fusioninventory');
break;
}
echo "</td>";
echo "<td>".Html::convDateTime($start_date)."</td>";
echo "<td>".Html::convDateTime($end_date)."</td>";
if ($end_date == '') {
$end_date = date("Y-m-d H:i:s");
}
if ($start_date == '') {
echo "<td>-</td>";
echo "<td>-</td>";
} else {
$date1 = new DateTime($start_date);
$date2 = new DateTime($end_date);
$interval = $date1->diff($date2);
$display_date = '';
if ($interval->h > 0) {
$display_date .= $interval->h."h ";
} else if ($interval->i > 0) {
$display_date .= $interval->i."min ";
}
echo "<td>".$display_date.$interval->s."s</td>";
echo "<td>".round(($nb_query - $nb_errors) /
(strtotime($end_date) - strtotime($start_date)), 2)."</td>";
}
echo "<td>".$nb_threads."</td>";
echo "<td>".$nb_query."</td>";
echo "<td>".$nb_errors."</td>";
echo "</tr>";
}
echo "</table>";
}
/**
* Display diff between 2 dates, so the time elapsed of execution
*
* @param string $date1
* @param string $date2
*/
function dateDiff($date1, $date2) {
$timestamp1 = strtotime($date1);
$timestamp2 = strtotime($date2);
$interval = [];
$timestamp = $timestamp2 - $timestamp1;
$nb_min = floor($timestamp / 60);
$interval['s'] = $timestamp - ($nb_min * 60);
$nb_hour = floor($nb_min / 60);
$interval['i'] = $nb_min - ($nb_hour * 60);
$display_date = '';
if ($nb_hour > 0) {
$display_date .= $nb_hour."h ";
} else if ($interval['i'] > 0) {
$display_date .= $interval['i']."min ";
}
echo "<td>".$display_date.$interval['s']."s</td>";
}
}

View File

@@ -0,0 +1,782 @@
<?php
/**
* FusionInventory
*
* Copyright (C) 2010-2016 by the FusionInventory Development Team.
*
* http://www.fusioninventory.org/
* https://github.com/fusioninventory/fusioninventory-for-glpi
* http://forge.fusioninventory.org/
*
* ------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of FusionInventory project.
*
* FusionInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FusionInventory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.
*
* ------------------------------------------------------------------------
*
* This file is used to manage the specifications of each module and for
* the task configuration.
*
* ------------------------------------------------------------------------
*
* @package FusionInventory
* @author David Durieux
* @copyright Copyright (c) 2010-2016 FusionInventory team
* @license AGPL License 3.0 or (at your option) any later version
* http://www.gnu.org/licenses/agpl-3.0-standalone.html
* @link http://www.fusioninventory.org/
* @link https://github.com/fusioninventory/fusioninventory-for-glpi
*
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Manage the specifications of each module and for the task configuration.
*/
class PluginFusioninventoryStaticmisc {
/**
* Get task methods of this plugin fusioninventory
*
* @return array('module'=>'value', 'method'=>'value')
* module value name of plugin
* method value name of method
*/
static function task_methods() {
$a_tasks = [
[ 'module' => 'fusioninventory',
'classname' => 'PluginFusioninventoryWakeonlan',
'method' => 'wakeonlan',
'name' => __('Wake On LAN', 'fusioninventory'),
'use_rest' => false
],
[ 'module' => 'fusioninventory',
'method' => 'inventory',
'selection_type' => 'devices',
'hidetask' => 1,
'name' => __('Computer Inventory', 'fusioninventory'),
'use_rest' => false
],
[ 'module' => 'fusioninventory',
'classname' => 'PluginFusioninventoryInventoryComputerESX',
'method' => 'InventoryComputerESX',
'selection_type' => 'devices',
'name' => __('VMware host remote inventory', 'fusioninventory'),
'task' => 'ESX',
'use_rest' => true
],
[ 'module' => 'fusioninventory',
'classname' => 'PluginFusioninventoryNetworkDiscovery',
'method' => 'networkdiscovery',
'name' => __('Network discovery', 'fusioninventory')
],
[ 'module' => 'fusioninventory',
'classname' => 'PluginFusioninventoryNetworkInventory',
'method' => 'networkinventory',
'name' => __('Network inventory (SNMP)', 'fusioninventory')
],
[ 'module' => 'fusioninventory',
'classname' => 'PluginFusioninventoryDeployCommon',
'method' => 'deployinstall',
'name' => __('Package deploy', 'fusioninventory'),
'task' => "DEPLOY",
'use_rest' => true
],
[ 'module' => 'fusioninventory',
'classname' => 'PluginFusioninventoryCollect',
'method' => 'collect',
'name' => __('Collect data', 'fusioninventory'),
'task' => "Collect",
'use_rest' => true
]
];
return $a_tasks;
}
/**
* Display methods availables
*
* @return array
*/
static function getModulesMethods() {
$methods = PluginFusioninventoryStaticmisc::getmethods();
$modules_methods = [];
$modules_methods[''] = "------";
foreach ($methods as $method) {
if (!((isset($method['hidetask']) AND $method['hidetask'] == '1'))) {
if (isset($method['name'])) {
$modules_methods[$method['method']] = $method['name'];
} else {
$modules_methods[$method['method']] = $method['method'];
}
}
}
return $modules_methods;
}
/**
* Get types of datas available to select for taskjob definition for WakeOnLan method
*
* @param array $a_itemtype types yet added for definitions
* @return array('itemtype'=>'value', 'itemtype'=>'value'...)
* itemtype itemtype of object
* value name of the itemtype
*/
static function task_definitiontype_wakeonlan($a_itemtype) {
$a_itemtype['Computer'] = Computer::getTypeName();
$a_itemtype['PluginFusioninventoryDeployGroup']
= PluginFusioninventoryDeployGroup::getTypeName();
return $a_itemtype;
}
/**
* Get all devices of definition type 'Computer' defined in
* task_definitiontype_wakeonlan
*
* @param string $title (not used)
* @return string unique html element id
*/
static function task_definitionselection_Computer_wakeonlan($title) {
$options = [];
$options['entity'] = $_SESSION['glpiactive_entity'];
$options['entity_sons'] = 1;
$options['name'] = 'definitionselectiontoadd';
$rand = Dropdown::show("Computer", $options);
return $rand;
}
/**
* Get all devices of definition type 'PluginFusioninventoryDeployGroup'
* defined in task_definitiontype_wakeonlan
*
* @param string $title (not used)
* @return string unique html element id
*/
static function task_definitionselection_PluginFusioninventoryDeployGroup_wakeonlan($title) {
$options = [];
$options['entity'] = $_SESSION['glpiactive_entity'];
$options['entity_sons'] = 1;
$options['name'] = 'definitionselectiontoadd';
return Dropdown::show("PluginFusioninventoryDeployGroup", $options);
}
/**
* Get all methods of this plugin
*
* @return array('module'=>'value', 'method'=>'value')
* module value name of plugin
* method value name of method
*
*/
static function getmethods() {
$a_methods = call_user_func(['PluginFusioninventoryStaticmisc', 'task_methods']);
$a_modules = PluginFusioninventoryModule::getAll();
foreach ($a_modules as $data) {
$class = $class= PluginFusioninventoryStaticmisc::getStaticMiscClass($data['directory']);
if (is_callable([$class, 'task_methods'])) {
$a_methods = array_merge($a_methods,
call_user_func([$class, 'task_methods']));
}
}
return $a_methods;
}
/**
* Get name of the staticmisc class for a module
*
* @param string $module the module name
* @return string the name of the staticmisc class associated with it
*/
static function getStaticMiscClass($module) {
return "Plugin".ucfirst($module)."Staticmisc";
}
/**
* Get types of datas available to select for taskjob definition for ESX method
*
* @param array $a_itemtype array types yet added for definitions
* @return array('itemtype'=>'value', 'itemtype'=>'value'...)
* itemtype itemtype of object
* value name of the itemtype
*/
static function task_definitiontype_InventoryComputerESX($a_itemtype) {
$a_itemtype['PluginFusioninventoryCredentialIp'] =
PluginFusioninventoryCredentialIp::getTypeName();
return $a_itemtype;
}
/**
* Get all devices of definition type 'PluginFusioninventoryCredentialIp'
* defined in task_definitiontype_InventoryComputerESX
*
* @global object $DB
* @param string (not used)
* @return string unique html element id
*/
static function task_definitionselection_PluginFusioninventoryCredentialIp_InventoryComputerESX($title) {
global $DB;
$query = "SELECT `a`.`id`, `a`.`name`
FROM `glpi_plugin_fusioninventory_credentialips` as `a`
LEFT JOIN `glpi_plugin_fusioninventory_credentials` as `c`
ON `c`.`id` = `a`.`plugin_fusioninventory_credentials_id`
WHERE `c`.`itemtype`='PluginFusioninventoryInventoryComputerESX'";
$query.= getEntitiesRestrictRequest(' AND', 'a');
$results = $DB->query($query);
$agents = [];
//$agents['.1'] = __('All');
while ($data = $DB->fetchArray($results)) {
$agents[$data['id']] = $data['name'];
}
if (!empty($agents)) {
return Dropdown::showFromArray('definitionselectiontoadd', $agents);
}
}
//------------------------------------------ Actions-------------------------------------//
/**
* Get action types for InventoryComputerESX
*
* @param array $a_itemtype
* @return array
*/
static function task_actiontype_InventoryComputerESX($a_itemtype) {
return ['' => Dropdown::EMPTY_VALUE ,
'PluginFusioninventoryAgent' => __('Agents', 'fusioninventory')];
}
/**
* Get all devices of action type 'PluginFusioninventoryCredentialIp'
* defined in task_actiontype_InventoryComputerESX
*
* @global object $DB
* @return string unique html element id
*/
static function task_actionselection_PluginFusioninventoryCredentialIp_InventoryComputerESX() {
global $DB;
$options = [];
$options['name'] = 'definitionactiontoadd';
$query = "SELECT `a`.`id`, `a`.`name`
FROM `glpi_plugin_fusioninventory_credentialips` as `a`
LEFT JOIN `glpi_plugin_fusioninventory_credentials` as `c`
ON `c`.`id` = `a`.`plugin_fusioninventory_credentials_id`
WHERE `c`.`itemtype`='PluginFusioninventoryInventoryComputerESX'";
$query.= getEntitiesRestrictRequest(' AND', 'glpi_plugin_fusioninventory_credentialips');
$results = $DB->query($query);
$credentialips = [];
while ($data = $DB->fetchArray($results)) {
$credentialips[$data['id']] = $data['name'];
}
return Dropdown::showFromArray('actionselectiontoadd', $credentialips);
}
/**
* Get all devices of action type 'PluginFusioninventoryAgent'
* defined in task_actiontype_InventoryComputerESX
*
* @return string unique html element id
*/
static function task_actionselection_PluginFusioninventoryAgent_InventoryComputerESX() {
$array = [];
$pfAgentmodule = new PluginFusioninventoryAgentmodule();
$array1 = $pfAgentmodule->getAgentsCanDo(strtoupper("InventoryComputerESX"));
foreach ($array1 as $id => $data) {
$array[$id] = $data['name'];
}
asort($array);
return Dropdown::showFromArray('actionselectiontoadd', $array);
}
//------------------------------------------ ---------------------------------------------//
//------------------------------------------ REST PARAMS---------------------------------//
//------------------------------------------ -------------------------------------------//
/**
* Get ESX task parameters to send to the agent
* For the moment it's hardcoded, but in a future release it may be in DB
*
* @param integer $entities_id id of the entity
* @return array
*/
static function task_ESX_getParameters($entities_id) {
return ['periodicity' => 3600, 'delayStartup' => 3600, 'task' => 'ESX',
"remote" => PluginFusioninventoryAgentmodule::getUrlForModule('ESX', $entities_id)];
}
//------------------------------- Network tools ------------------------------------//
// *** NETWORKDISCOVERY ***
/**
* Definition types for network discovery
*
* @param array $a_itemtype
* @return array
*/
static function task_definitiontype_networkdiscovery($a_itemtype) {
$a_itemtype['PluginFusioninventoryIPRange'] = __('IP Ranges', 'fusioninventory');
return $a_itemtype;
}
/**
* Get all ip ranges of definition type 'PluginFusioninventoryIPRange'
* defined in task_definitiontype_networkdiscovery
*
* @param string $title (not used)
* @return string unique html element id
*/
static function task_definitionselection_PluginFusioninventoryIPRange_networkdiscovery($title) {
$options = [];
$options['entity'] = $_SESSION['glpiactive_entity'];
$options['entity_sons'] = 1;
$options['name'] = 'definitionselectiontoadd';
$rand = Dropdown::show("PluginFusioninventoryIPRange", $options);
return $rand;
}
// *** NETWORKINVENTORY ***
/**
* Definition types for network inventory
*
* @param array $a_itemtype
* @return array
*/
static function task_definitiontype_networkinventory($a_itemtype) {
$a_itemtype['PluginFusioninventoryIPRange'] = __('IP Ranges', 'fusioninventory');
$a_itemtype['NetworkEquipment'] = NetworkEquipment::getTypeName();
$a_itemtype['Printer'] = Printer::getTypeName();
return $a_itemtype;
}
/**
* Get all ip ranges of definition type 'PluginFusioninventoryIPRange'
* defined in task_definitiontype_networkinventory
*
* @param string $title (not used)
* @return string unique html element id
*/
static function task_definitionselection_PluginFusioninventoryIPRange_networkinventory($title) {
$rand = PluginFusioninventoryStaticmisc::task_definitionselection_PluginFusioninventoryIPRange_networkdiscovery($title);
return $rand;
}
/**
* Get all devices of definition type 'NetworkEquipment'
* defined in task_definitiontype_networkinventory
*
* @param string $title (not used)
* @return string unique html element id
*/
static function task_definitionselection_NetworkEquipment_networkinventory($title) {
$options = [];
$options['entity'] = $_SESSION['glpiactive_entity'];
$options['entity_sons'] = 1;
$options['name'] = 'definitionselectiontoadd';
$rand = Dropdown::show("NetworkEquipment", $options);
return $rand;
}
/**
* Get all devices of definition type 'Printer'
* defined in task_definitiontype_networkinventory
*
* @param string $title (not used)
* @return string unique html element id
*/
static function task_definitionselection_Printer_networkinventory($title) {
$options = [];
$options['entity'] = $_SESSION['glpiactive_entity'];
$options['entity_sons'] = 1;
$options['name'] = 'definitionselectiontoadd';
$rand = Dropdown::show("Printer", $options);
return $rand;
}
/**
* Get agents allowed to do network discovery
*
* @return array
*/
static function task_networkdiscovery_agents() {
$array = [];
$array["-.1"] = __('Auto managenement dynamic of agents', 'fusioninventory');
$pfAgentmodule = new PluginFusioninventoryAgentmodule();
$array1 = $pfAgentmodule->getAgentsCanDo('NETWORKDISCOVERY');
foreach ($array1 as $id => $data) {
$array["PluginFusioninventoryAgent-".$id] =
__('Auto managenement dynamic of agents', 'fusioninventory')." - ".$data['name'];
}
return $array;
}
/**
* Get types of actions for network inventory
*
* @return array
*/
static function task_action_networkinventory() {
$a_itemtype = [];
$a_itemtype[] = "Printer";
$a_itemtype[] = "NetworkEquipment";
$a_itemtype[] = 'PluginFusioninventoryIPRange';
return $a_itemtype;
}
/**
* Get selection type for network inventory
*
* @param string $itemtype
* @return string
*/
static function task_selection_type_networkinventory($itemtype) {
$selection_type = '';
switch ($itemtype) {
case 'PluginFusioninventoryIPRange':
$selection_type = 'iprange';
break;
case "Printer";
case "NetworkEquipment";
$selection_type = 'devices';
break;
}
return $selection_type;
}
/**
* Get selection type for network discovery
*
* @param string $itemtype
* @return array
*/
static function task_selection_type_networkdiscovery($itemtype) {
$selection_type = '';
switch ($itemtype) {
case 'PluginFusioninventoryIPRange':
$selection_type = 'iprange';
break;
}
return $selection_type;
}
/* Deploy definitions */
/**
* Get definition types for deploy install
*
* @param string $a_itemtype
* @return array
*/
static function task_definitiontype_deployinstall($a_itemtype) {
return ['' => Dropdown::EMPTY_VALUE,
'PluginFusioninventoryDeployPackage' => __('Package')];
}
/**
* Get all packages of definition type 'PluginFusioninventoryDeployPackage'
* defined in task_definitiontype_deployinstall
*
* @param string $title (not used)
* @return string unique html element id
*/
static function task_definitionselection_PluginFusioninventoryDeployPackage_deployinstall() {
$options['entity'] = $_SESSION['glpiactive_entity'];
$options['entity_sons'] = 1;
$options['name'] = 'definitionselectiontoadd';
return Dropdown::show("PluginFusioninventoryDeployPackage", $options);
}
/* Deploy Actions */
/**
* Get types of action for deployinstall
*
* @param array $a_itemtype
* @return array
*/
static function task_actiontype_deployinstall($a_itemtype) {
return ['' => Dropdown::EMPTY_VALUE,
'Computer' => __('Computers'),
'PluginFusioninventoryDeployGroup' => PluginFusioninventoryDeployGroup::getTypeName(),
'Group' => __('Group')
];
}
/**
* Get all computers of action type 'Computer'
* defined in task_actiontype_deployinstall
*
* @return string unique html element id
*/
static function task_actionselection_Computer_deployinstall() {
$options = [];
$options['entity'] = $_SESSION['glpiactive_entity'];
$options['entity_sons'] = 1;
$options['name'] = 'actionselectiontoadd';
$options['condition'] =
implode( " ",
[
'`id` IN ( ',
' SELECT agents.`computers_id`',
' FROM `glpi_plugin_fusioninventory_agents` as agents',
' LEFT JOIN `glpi_plugin_fusioninventory_agentmodules` as module',
' ON module.modulename = "DEPLOY"',
' WHERE',
' ( module.is_active=1',
' AND module.exceptions NOT LIKE CONCAT(\'%"\',agents.`id`,\'"%\') )',
' OR ( module.is_active=0',
' AND module.exceptions LIKE CONCAT(\'%"\',agents.`id`,\'"%\') )',
')'
]
);
return Dropdown::show("Computer", $options);
}
/**
* Get all computers of action type 'Group'
* defined in task_actiontype_deployinstall
*
* @return string unique html element id
*/
static function task_actionselection_Group_deployinstall() {
$options = [];
$options['entity'] = $_SESSION['glpiactive_entity'];
$options['entity_sons'] = 1;
$options['name'] = 'actionselectiontoadd';
return Dropdown::show("Group", $options);
}
/**
* Get all computers of action type 'PluginFusioninventoryDeployGroup'
* defined in task_actiontype_deployinstall
*
* @return string unique html element id
*/
static function task_actionselection_PluginFusioninventoryDeployGroup_deployinstall() {
$options = [];
$options['entity'] = $_SESSION['glpiactive_entity'];
$options['entity_sons'] = 1;
$options['name'] = 'actionselectiontoadd';
return Dropdown::show("PluginFusioninventoryDeployGroup", $options);
}
/**
* Get Deploy paramaters: url for communication with server
*
* @param integer $entities_id
* @return array
*/
static function task_deploy_getParameters($entities_id) {
return [
"task" => "Deploy",
"remote" => PluginFusioninventoryAgentmodule::getUrlForModule('Deploy', $entities_id)
];
}
/* Collect */
/**
* Get definition types of collect
*
* @param array $a_itemtype
* @return array
*/
static function task_definitiontype_collect($a_itemtype) {
return ['' => Dropdown::EMPTY_VALUE,
'PluginFusioninventoryCollect' => __('Collect information', 'fusioninventory')];
}
/**
* Get all collects of definition type 'PluginFusioninventoryCollect'
* defined in task_definitiontype_collect
*
* @param string (not used)
* @return string unique html element id
*/
static function task_definitionselection_PluginFusioninventoryCollect_collect() {
$options['entity'] = $_SESSION['glpiactive_entity'];
$options['entity_sons'] = 1;
$options['name'] = 'definitionselectiontoadd';
return Dropdown::show("PluginFusioninventoryCollect", $options);
}
/**
* Get action types for collect
*
* @param array $a_itemtype
* @return array
*/
static function task_actiontype_collect($a_itemtype) {
return ['' => Dropdown::EMPTY_VALUE,
'Computer' => __('Computers'),
'PluginFusioninventoryDeployGroup' => PluginFusioninventoryDeployGroup::getTypeName(),
'Group' => __('Group')
];
}
/**
* Get all computers of action type 'Computer'
* defined in task_actiontype_collect
*
* @return string unique html element id
*/
static function task_actionselection_Computer_collect() {
$options = [];
$options['entity'] = $_SESSION['glpiactive_entity'];
$options['entity_sons'] = 1;
$options['name'] = 'actionselectiontoadd';
$options['condition'] =
implode( " ",
[
'`id` IN ( ',
' SELECT agents.`computers_id`',
' FROM `glpi_plugin_fusioninventory_agents` as agents',
' LEFT JOIN `glpi_plugin_fusioninventory_agentmodules` as module',
' ON module.modulename = "Collect"',
' WHERE',
' ( module.is_active=1',
' AND module.exceptions NOT LIKE CONCAT(\'%"\',agents.`id`,\'"%\') )',
' OR ( module.is_active=0',
' AND module.exceptions LIKE CONCAT(\'%"\',agents.`id`,\'"%\') )',
')'
]
);
return Dropdown::show("Computer", $options);
}
/**
* Get all computers of action type 'Group'
* defined in task_actiontype_collect
*
* @return string unique html element id
*/
static function task_actionselection_Group_collect() {
$options = [];
$options['entity'] = $_SESSION['glpiactive_entity'];
$options['entity_sons'] = 1;
$options['name'] = 'actionselectiontoadd';
return Dropdown::show("Group", $options);
}
/**
* Get all computers of action type 'PluginFusioninventoryDeployGroup'
* defined in task_actiontype_collect
*
* @return string unique html element id
*/
static function task_actionselection_PluginFusioninventoryDeployGroup_collect() {
$options = [];
$options['entity'] = $_SESSION['glpiactive_entity'];
$options['entity_sons'] = 1;
$options['name'] = 'actionselectiontoadd';
return Dropdown::show("PluginFusioninventoryDeployGroup", $options);
}
/**
*
* Get collect parameters (URL to dialog with server)
*
* @param integer $entities_id
* @return array
*/
static function task_collect_getParameters($entities_id) {
return [
"task" => "Collect",
"remote" => PluginFusioninventoryAgentmodule::getUrlForModule('Collect', $entities_id)
];
}
}

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More