clean_cross_side_scripting_deep() static public method

Prevent from XSS Clean code
static public clean_cross_side_scripting_deep ( $value ) : clean
$value array or string: item to prevent (array or string)
return clean item
Ejemplo n.º 1
0
 /**
  * Solution of a ticket for an authenticated user
  *
  * @param $params    array of options (ticket, id2name)
  * @param $protocol        the communication protocol used
  *
  * @return array of hashtable as glpi.getTicket
  **/
 static function methodsetTicketSolution($params, $protocol)
 {
     global $DB, $CFG_GLPI;
     if (isset($params['help'])) {
         return array('ticket' => 'integer,mandatory', 'id2name' => 'bool,optional', 'type' => 'integer,optional', 'solution' => 'text,mandatory', 'help' => 'bool,optional');
     }
     if (!Session::getLoginUserID()) {
         return self::Error($protocol, WEBSERVICES_ERROR_NOTAUTHENTICATED);
     }
     $ticket = new Ticket();
     if (!isset($params['ticket'])) {
         return self::Error($protocol, WEBSERVICES_ERROR_MISSINGPARAMETER, '', 'ticket');
     }
     if (!isset($params['solution'])) {
         return self::Error($protocol, WEBSERVICES_ERROR_MISSINGPARAMETER, '', 'solution');
     }
     if (isset($params['type']) && !is_numeric($params['type'])) {
         return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', 'type=' . $params['type']);
     }
     if (!$ticket->can($params['ticket'], 'r')) {
         return self::Error($protocol, WEBSERVICES_ERROR_NOTFOUND, '', 'ticket');
     }
     if (!$ticket->getFromDB($params['ticket'])) {
         return self::Error($protocol, WEBSERVICES_ERROR_NOTFOUND, '', 'solution');
     }
     $input = array('id' => $ticket->getField('id'), 'solution' => addslashes(Toolbox::clean_cross_side_scripting_deep($params['solution'])), 'status' => Ticket::SOLVED);
     if (isset($params['type'])) {
         $input['solutiontypes_id'] = $params['type'];
     }
     if (!$ticket->canSolve($params['ticket'], 'w')) {
         return self::Error($protocol, WEBSERVICES_ERROR_NOTALLOWED);
     }
     if ($ticket->update($input)) {
         unset($params['solution'], $params['type']);
         return self::methodGetTicket($params, $protocol);
     }
     return self::Error($protocol, WEBSERVICES_ERROR_FAILED, '', self::getDisplayError());
 }
Ejemplo n.º 2
0
-------------------------------------------------------------------------

LICENSE

This file is part of GLPI.

GLPI is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

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

You should have received a copy of the GNU General Public License
along with GLPI. If not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------
*/
/** @file
* @brief
*/
$AJAX_INCLUDE = 1;
include '../inc/includes.php';
header("Content-Type: text/html; charset=UTF-8");
Html::header_nocache();
Session::checkLoginUser();
if (isset($_POST['name'])) {
    echo "<input type='text' " . (isset($_POST["size"]) ? " size='" . $_POST["size"] . "' " : "") . " " . (isset($_POST["maxlength"]) ? "maxlength='" . $_POST["maxlength"] . "' " : "") . " name='" . $_POST['name'] . "' value=\"" . Html::cleanInputText(Toolbox::clean_cross_side_scripting_deep(rawurldecode(stripslashes($_POST["data"])))) . "\">";
}
Ejemplo n.º 3
0
 /**
  * Get ldap query results and clean them at the same time
  *
  * @param link    the directory connection
  * @param result  the query results
  *
  * @return an array which contains ldap query results
  **/
 static function get_entries_clean($link, $result)
 {
     return Toolbox::clean_cross_side_scripting_deep(ldap_get_entries($link, $result));
 }
Ejemplo n.º 4
0
 static function selectGroupOnAdd($item)
 {
     global $CFG_GLPI, $DB;
     if (isset($item->input['_auto_import']) || isset($item->input['bypassgrouponadd'])) {
         return;
     }
     $peGroup_group = new self();
     if ($_SESSION['glpiactiveprofile']['interface'] == 'central') {
         $peConfig = new PluginEscalationConfig();
         if ($peConfig->getValue('workflow', $item->fields['entities_id']) == '1') {
             if (isset($_POST['_groups_id_assign']) && $_POST['_groups_id_assign'] > 0) {
                 if (isset($_SESSION['plugin_escalation_files'])) {
                     $_FILES = $_SESSION['plugin_escalation_files'];
                 }
                 return;
             } else {
                 $group = new Group();
                 Html::header(__('Administration'), '', "maintain", "ticket");
                 if (isset($_POST['dropdown__groups_id_requester']) && $_POST['dropdown__groups_id_requester'] > 0) {
                     $_SESSION['plugin_escalation_groups_id_requester'] = $_POST['dropdown__groups_id_requester'];
                 }
                 if (isset($_FILES)) {
                     foreach ($_FILES['filename']['tmp_name'] as $numfile => $datafile) {
                         if ($datafile != '') {
                             $split = explode("/", $datafile);
                             Document::renameForce($datafile, GLPI_DOC_DIR . "/_tmp/" . end($split));
                             $_FILES['filename']['tmp_name'][$numfile] = GLPI_DOC_DIR . "/_tmp/" . end($split);
                         }
                     }
                     $_SESSION['plugin_escalation_files'] = $_FILES;
                 }
                 echo '<form action="' . $CFG_GLPI['root_doc'] . '/front/ticket.form.php"
               enctype="multipart/form-data" name="form_ticket" method="post">';
                 echo "<table class='tab_cadre_fixe'>";
                 echo "<tr class='tab_bg_1'>";
                 echo "<th colspan='2'>Sélection du groupe de techniciens</th>";
                 echo "</tr>";
                 echo "<tr class='tab_bg_1'>";
                 echo "<td>";
                 echo __('Group in charge of the ticket') . "&nbsp;:";
                 echo "</td>";
                 echo "<td>";
                 $a_groups = array();
                 foreach ($_SESSION['glpigroups'] as $groups_id) {
                     $group->getFromDB($groups_id);
                     $a_groups[$groups_id] = $group->getName();
                     $queryg = "SELECT * FROM `" . $peGroup_group->getTable() . "`\n                     WHERE `groups_id_source` = '" . $groups_id . "' ";
                     $resultg = $DB->query($queryg);
                     while ($datag = $DB->fetch_array($resultg)) {
                         $group->getFromDB($datag['groups_id_destination']);
                         $a_groups[$groups_id . "_" . $datag['groups_id_destination']] = "&nbsp;&nbsp;&nbsp;> " . $group->getName();
                     }
                 }
                 $rand = Dropdown::showFromArray("_groups_id_assign_escalation", $a_groups);
                 $params = array('groups_id' => '__VALUE__', 'entity' => $_POST['entities_id'], 'rand' => $rand);
                 Ajax::updateItemOnSelectEvent("dropdown__groups_id_assign" . $rand, "show_assignuser{$rand}", $CFG_GLPI["root_doc"] . "/plugins/escalation/ajax/dropdownUserassign.php", $params);
                 echo "</tr>";
                 echo "<tr class='tab_bg_1'>";
                 echo "<td colspan='2'>";
                 foreach ($_POST as $key => $value) {
                     if (is_array($value)) {
                         foreach ($value as $keyy => $valuee) {
                             echo '<input type="hidden" name="' . $key . '[' . $keyy . ']" value="' . $valuee . '" />';
                         }
                     } else {
                         if ($key == 'content') {
                             $value = Html::cleanPostForTextArea(Toolbox::clean_cross_side_scripting_deep($value));
                             echo '<textarea name="' . $key . '" style="display:none;">' . $value . '</textarea>';
                         } else {
                             if ($key == 'dropdown__groups_id_requester') {
                                 echo '<input type="hidden" name="_groups_id_requester" value="' . $value . '" />';
                             } else {
                                 $value = Html::cleanInputText(Toolbox::clean_cross_side_scripting_deep(stripslashes($value)));
                                 echo '<input type="hidden" name="' . $key . '" value="' . $value . '" />';
                             }
                         }
                     }
                 }
                 if (!isset($_POST['_users_id_assign']) or $_POST['_users_id_assign'] == '0') {
                     echo "<span id='show_assignuser{$rand}'></span>";
                 }
                 echo "</td>";
                 echo "</tr>";
                 echo "<tr class='tab_bg_1'>";
                 echo "<td colspan='2' align='center'>";
                 echo "<input type='submit' name='add' value=\"" . __('Add') . "\" class='submit'>";
                 echo "</td>";
                 echo "</tr>";
                 echo "</table>";
                 Html::closeForm();
                 Html::footer();
                 exit;
             }
         }
     }
 }
 /**
  * @param $cfg_ocs
  * @param $ocsComputer
  * @param $computers_id
  * @param $entities_id
  */
 static function importNetwork($cfg_ocs, $ocsComputer, $computers_id, $entities_id)
 {
     global $DB;
     // Group by DESCRIPTION, MACADDR, TYPE, TYPEMIB, SPEED, VIRTUALDEV
     // to get an array in IPADDRESS
     $ocsNetworks = array();
     foreach ($ocsComputer as $ocsNetwork) {
         $key = $ocsNetwork['DESCRIPTION'] . $ocsNetwork['MACADDR'] . $ocsNetwork['TYPE'] . $ocsNetwork['TYPEMIB'] . $ocsNetwork['SPEED'] . $ocsNetwork['VIRTUALDEV'];
         if (!isset($ocsNetworks[$key])) {
             $ocsNetworks[$key] = $ocsNetwork;
             $ocsNetworks[$key]['IPADDRESS'] = array($ocsNetwork['IPADDRESS']);
         } else {
             $ocsNetworks[$key]['IPADDRESS'][] = $ocsNetwork['IPADDRESS'];
         }
     }
     $network_ports = array();
     $network_ifaces = array();
     foreach ($ocsNetworks as $line) {
         $line = Toolbox::clean_cross_side_scripting_deep(Toolbox::addslashes_deep($line));
         $mac = $line['MACADDR'];
         if (!isset($network_ports[$mac])) {
             $network_ports[$mac] = array('virtual' => array());
         }
         $name = PluginOcsinventoryngOcsServer::encodeOcsDataInUtf8($cfg_ocs["ocs_db_utf8"], $line['DESCRIPTION']);
         if (!empty($line['IPADDRESS'])) {
             $ip = $line['IPADDRESS'];
         } else {
             $ip = false;
         }
         $networkport_type = new PluginOcsinventoryngNetworkPortType();
         $networkport_type->getFromTypeAndTypeMIB($line);
         $speed = NetworkPortEthernet::transformPortSpeed($line['SPEED'], false);
         if (!empty($speed)) {
             $networkport_type->fields['speed'] = $speed;
         }
         $values = array('name' => $name, 'type' => array_push($network_ifaces, $networkport_type) - 1, 'ip' => $ip, 'result' => $line);
         // Virtual dev can be :
         //    1°) specifically defined from OCS
         //    2°) if there is already one main device
         //    3°) if the networkport is issued by VMWare
         if (isset($line['VIRTUALDEV']) && $line['VIRTUALDEV'] == '1' || isset($network_ports[$mac]['main']) || preg_match('/^vm(k|nic)([0-9]+)$/', $name)) {
             $network_ports[$mac]['virtual'][] = $values;
         } else {
             $network_ports[$mac]['main'] = $values;
         }
     }
     $already_known_ports = array();
     $already_known_ifaces = array();
     foreach ($network_ports as $mac => $ports) {
         if (isset($ports['main'])) {
             $main = $ports['main'];
             $type = $network_ifaces[$main['type']];
             // First search for the Network Card
             $item_device = new Item_DeviceNetworkCard();
             $item_device->getFromDBByQuery("INNER JOIN `glpi_devicenetworkcards`\n                               ON (`glpi_devicenetworkcards`.`designation`='" . $main['name'] . "')\n                        WHERE `glpi_items_devicenetworkcards`.`itemtype`='Computer'\n                           AND `glpi_items_devicenetworkcards`.`items_id`='{$computers_id}'\n                           AND `glpi_items_devicenetworkcards`.`mac`='{$mac}'\n                           AND `glpi_items_devicenetworkcards`.`devicenetworkcards_id`=\n                               `glpi_devicenetworkcards`.`id`");
             // If not found, then, create it
             if ($item_device->isNewItem()) {
                 $deviceNetworkCard = new DeviceNetworkCard();
                 $device_input = array('designation' => $main['name'], 'bandwidth' => $type->fields['speed'], 'entities_id' => $entities_id);
                 $net_id = $deviceNetworkCard->import($device_input);
                 if ($net_id) {
                     $item_device->add(array('items_id' => $computers_id, 'itemtype' => 'Computer', 'entities_id' => $entities_id, 'devicenetworkcards_id' => $net_id, 'mac' => $mac, '_no_history' => !$cfg_ocs['history_network'], 'is_dynamic' => 1, 'is_deleted' => 0));
                 }
             }
             if (!$item_device->isNewItem()) {
                 $already_known_ifaces[] = $item_device->getID();
             }
             if ($type->fields['instantiation_type'] == __CLASS__) {
                 $result = $main['result'];
                 $inst_input = array('TYPE' => $result['TYPE'], 'TYPEMIB' => $result['TYPEMIB'], 'speed' => $result['SPEED']);
             } else {
                 $inst_input = $type->fields;
                 foreach (array('id', 'name', 'OCS_TYPE', 'OCS_TYPEMIB', 'instantiation_type', 'comment') as $field) {
                     unset($inst_input[$field]);
                 }
             }
             $inst_input['items_devicenetworkcards_id'] = $item_device->getID();
             $networkports_id = self::updateNetworkPort($mac, $main['name'], $computers_id, $type->fields['instantiation_type'], $inst_input, $main['ip'], false, $cfg_ocs['history_network'], $already_known_ports);
             if ($networkports_id < 0) {
                 continue;
             }
             $already_known_ports[] = $networkports_id;
         } else {
             $networkports_id = 0;
         }
         foreach ($ports['virtual'] as $port) {
             $inst_input = array('networkports_id_alias' => $networkports_id);
             $id = self::updateNetworkPort($mac, $port['name'], $computers_id, 'NetworkPortAlias', $inst_input, $port['ip'], true, $cfg_ocs['history_network'], $already_known_ports);
             if ($id > 0) {
                 $already_known_ports[] = $id;
             }
         }
     }
     $query = "SELECT `id`\n                FROM `glpi_networkports`\n                WHERE `itemtype` = 'Computer'\n                   AND `items_id` = '{$computers_id}'\n                   AND `is_dynamic` = '1'";
     if (count($already_known_ports) > 0) {
         $query .= " AND `id` NOT IN ('" . implode("', '", $already_known_ports) . "')";
     }
     $network_ports = new NetworkPort();
     foreach ($DB->request($query) as $line) {
         $network_ports->delete($line, true, $cfg_ocs['history_network']);
     }
     $query = "SELECT `id`\n                FROM `glpi_items_devicenetworkcards`\n                WHERE `itemtype` = 'Computer'\n                   AND `items_id` = '{$computers_id}'\n                   AND `is_dynamic` = '1'";
     if (count($already_known_ifaces) > 0) {
         $query .= " AND `id` NOT IN ('" . implode("', '", $already_known_ifaces) . "')";
     }
     $item_device = new Item_DeviceNetworkCard();
     foreach ($DB->request($query) as $line) {
         $item_device->delete($line, true, $cfg_ocs['history_network']);
     }
 }
Ejemplo n.º 6
0
             $nb = count($data);
             $data = Toolbox::clean_cross_side_scripting_deep(Toolbox::addslashes_deep($data));
             $hardware[$data["ID"]] = $data["DEVICEID"];
             echo "{$i}/{$nb}\r";
         }
     }
     echo "  {$nb} computers in OCS\n";
 }
 echo "+ Search links with no computer in OCS\n";
 $query = "SELECT `id`, `ocsid`, `ocs_deviceid`\n                FROM `glpi_plugin_ocsinventoryng_ocslinks`\n                WHERE `plugin_ocsinventoryng_ocsservers_id` = '{$ocsservers_id}'";
 $result = $DB->query($query);
 $nb = $DB->numrows($result);
 if ($nb > 0) {
     for ($i = 1; $data = $DB->fetch_array($result); $i++) {
         $nbchk++;
         $data = Toolbox::clean_cross_side_scripting_deep(Toolbox::addslashes_deep($data));
         if (isset($hardware[$data["ocsid"]])) {
             echo "{$i}/{$nb}\r";
         } else {
             printf("%12d : %s\n", $data['id'], $data['ocs_deviceid']);
             if (isset($_GET['clean'])) {
                 $query_del = "DELETE\n                                FROM `glpi_plugin_ocsinventoryng_ocslinks`\n                                WHERE `id` = '" . $data["id"] . "'";
                 if ($DB->query($query_del)) {
                     $nbdel++;
                 }
             } else {
                 $nbtodo++;
             }
         }
     }
     echo "  {$nb} links checked\n";
 /**
  * @param $item            CommonDBTM object
  * @param $options   array
  * @param $simple          (false by default)
  **/
 function getDatasForObject(CommonDBTM $item, array $options, $simple = false)
 {
     global $CFG_GLPI, $DB;
     $objettype = strtolower($item->getType());
     $datas["##{$objettype}.title##"] = $item->getField('name');
     $datas["##{$objettype}.content##"] = $item->getField('content');
     $datas["##{$objettype}.description##"] = $item->getField('content');
     $datas["##{$objettype}.id##"] = sprintf("%07d", $item->getField("id"));
     if ($_SESSION['glpiticket_timeline'] == 1) {
         $datas["##{$objettype}.url##"] = $this->formatURL($options['additionnaloption']['usertype'], $objettype . "_" . $item->getField("id") . "_" . $item->getType() . '$1');
     } else {
         $datas["##{$objettype}.url##"] = $this->formatURL($options['additionnaloption']['usertype'], $objettype . "_" . $item->getField("id"));
     }
     $tab = '$2';
     if ($_SESSION['glpiticket_timeline'] == 1) {
         $tab = '$1';
     }
     $datas["##{$objettype}.urlapprove##"] = $this->formatURL($options['additionnaloption']['usertype'], $objettype . "_" . $item->getField("id") . "_" . $item->getType() . $tab);
     $entity = new Entity();
     if ($entity->getFromDB($this->getEntity())) {
         $datas["##{$objettype}.entity##"] = $entity->getField('completename');
         $datas["##{$objettype}.shortentity##"] = $entity->getField('name');
     }
     $datas["##{$objettype}.storestatus##"] = $item->getField('status');
     $datas["##{$objettype}.status##"] = $item->getStatus($item->getField('status'));
     $datas["##{$objettype}.urgency##"] = $item->getUrgencyName($item->getField('urgency'));
     $datas["##{$objettype}.impact##"] = $item->getImpactName($item->getField('impact'));
     $datas["##{$objettype}.priority##"] = $item->getPriorityName($item->getField('priority'));
     $datas["##{$objettype}.time##"] = $item->getActionTime($item->getField('actiontime'));
     $datas["##{$objettype}.creationdate##"] = Html::convDateTime($item->getField('date'));
     $datas["##{$objettype}.closedate##"] = Html::convDateTime($item->getField('closedate'));
     $datas["##{$objettype}.solvedate##"] = Html::convDateTime($item->getField('solvedate'));
     $datas["##{$objettype}.duedate##"] = Html::convDateTime($item->getField('due_date'));
     $datas["##{$objettype}.category##"] = '';
     if ($item->getField('itilcategories_id')) {
         $datas["##{$objettype}.category##"] = Dropdown::getDropdownName('glpi_itilcategories', $item->getField('itilcategories_id'));
     }
     $datas["##{$objettype}.authors##"] = '';
     $datas['authors'] = array();
     if ($item->countUsers(CommonITILActor::REQUESTER)) {
         $users = array();
         foreach ($item->getUsers(CommonITILActor::REQUESTER) as $tmpusr) {
             $uid = $tmpusr['users_id'];
             $user_tmp = new User();
             if ($uid && $user_tmp->getFromDB($uid)) {
                 $users[] = $user_tmp->getName();
                 $tmp = array();
                 $tmp['##author.id##'] = $uid;
                 $tmp['##author.name##'] = $user_tmp->getName();
                 if ($user_tmp->getField('locations_id')) {
                     $tmp['##author.location##'] = Dropdown::getDropdownName('glpi_locations', $user_tmp->getField('locations_id'));
                 } else {
                     $tmp['##author.location##'] = '';
                 }
                 if ($user_tmp->getField('usertitles_id')) {
                     $tmp['##author.title##'] = Dropdown::getDropdownName('glpi_usertitles', $user_tmp->getField('usertitles_id'));
                 } else {
                     $tmp['##author.title##'] = '';
                 }
                 if ($user_tmp->getField('usercategories_id')) {
                     $tmp['##author.category##'] = Dropdown::getDropdownName('glpi_usercategories', $user_tmp->getField('usercategories_id'));
                 } else {
                     $tmp['##author.category##'] = '';
                 }
                 $tmp['##author.email##'] = $user_tmp->getDefaultEmail();
                 $tmp['##author.mobile##'] = $user_tmp->getField('mobile');
                 $tmp['##author.phone##'] = $user_tmp->getField('phone');
                 $tmp['##author.phone2##'] = $user_tmp->getField('phone2');
                 $datas['authors'][] = $tmp;
             } else {
                 // Anonymous users only in xxx.authors, not in authors
                 $users[] = $tmpusr['alternative_email'];
             }
         }
         $datas["##{$objettype}.authors##"] = implode(', ', $users);
     }
     $datas["##{$objettype}.openbyuser##"] = '';
     if ($item->getField('users_id_recipient')) {
         $user_tmp = new User();
         $user_tmp->getFromDB($item->getField('users_id_recipient'));
         $datas["##{$objettype}.openbyuser##"] = $user_tmp->getName();
     }
     $datas["##{$objettype}.lastupdater##"] = '';
     if ($item->getField('users_id_lastupdater')) {
         $user_tmp = new User();
         $user_tmp->getFromDB($item->getField('users_id_lastupdater'));
         $datas["##{$objettype}.lastupdater##"] = $user_tmp->getName();
     }
     $datas["##{$objettype}.assigntousers##"] = '';
     if ($item->countUsers(CommonITILActor::ASSIGN)) {
         $users = array();
         foreach ($item->getUsers(CommonITILActor::ASSIGN) as $tmp) {
             $uid = $tmp['users_id'];
             $user_tmp = new User();
             if ($user_tmp->getFromDB($uid)) {
                 $users[$uid] = $user_tmp->getName();
             }
         }
         $datas["##{$objettype}.assigntousers##"] = implode(', ', $users);
     }
     $datas["##{$objettype}.assigntosupplier##"] = '';
     if ($item->countSuppliers(CommonITILActor::ASSIGN)) {
         $suppliers = array();
         foreach ($item->getSuppliers(CommonITILActor::ASSIGN) as $tmp) {
             $uid = $tmp['suppliers_id'];
             $supplier_tmp = new Supplier();
             if ($supplier_tmp->getFromDB($uid)) {
                 $suppliers[$uid] = $supplier_tmp->getName();
             }
         }
         $datas["##{$objettype}.assigntosupplier##"] = implode(', ', $suppliers);
     }
     $datas["##{$objettype}.groups##"] = '';
     if ($item->countGroups(CommonITILActor::REQUESTER)) {
         $groups = array();
         foreach ($item->getGroups(CommonITILActor::REQUESTER) as $tmp) {
             $gid = $tmp['groups_id'];
             $groups[$gid] = Dropdown::getDropdownName('glpi_groups', $gid);
         }
         $datas["##{$objettype}.groups##"] = implode(', ', $groups);
     }
     $datas["##{$objettype}.observergroups##"] = '';
     if ($item->countGroups(CommonITILActor::OBSERVER)) {
         $groups = array();
         foreach ($item->getGroups(CommonITILActor::OBSERVER) as $tmp) {
             $gid = $tmp['groups_id'];
             $groups[$gid] = Dropdown::getDropdownName('glpi_groups', $gid);
         }
         $datas["##{$objettype}.observergroups##"] = implode(', ', $groups);
     }
     $datas["##{$objettype}.observerusers##"] = '';
     if ($item->countUsers(CommonITILActor::OBSERVER)) {
         $users = array();
         foreach ($item->getUsers(CommonITILActor::OBSERVER) as $tmp) {
             $uid = $tmp['users_id'];
             $user_tmp = new User();
             if ($uid && $user_tmp->getFromDB($uid)) {
                 $users[] = $user_tmp->getName();
             } else {
                 $users[] = $tmp['alternative_email'];
             }
         }
         $datas["##{$objettype}.observerusers##"] = implode(', ', $users);
     }
     $datas["##{$objettype}.assigntogroups##"] = '';
     if ($item->countGroups(CommonITILActor::ASSIGN)) {
         $groups = array();
         foreach ($item->getGroups(CommonITILActor::ASSIGN) as $tmp) {
             $gid = $tmp['groups_id'];
             $groups[$gid] = Dropdown::getDropdownName('glpi_groups', $gid);
         }
         $datas["##{$objettype}.assigntogroups##"] = implode(', ', $groups);
     }
     $datas["##{$objettype}.solution.type##"] = '';
     if ($item->getField('solutiontypes_id')) {
         $datas["##{$objettype}.solution.type##"] = Dropdown::getDropdownName('glpi_solutiontypes', $item->getField('solutiontypes_id'));
     }
     $datas["##{$objettype}.solution.description##"] = Toolbox::unclean_cross_side_scripting_deep($item->getField('solution'));
     // Complex mode
     if (!$simple) {
         $datas['log'] = array();
         // Use list_limit_max or load the full history ?
         foreach (Log::getHistoryData($item, 0, $CFG_GLPI['list_limit_max']) as $data) {
             $tmp = array();
             $tmp["##{$objettype}.log.date##"] = $data['date_mod'];
             $tmp["##{$objettype}.log.user##"] = $data['user_name'];
             $tmp["##{$objettype}.log.field##"] = $data['field'];
             $tmp["##{$objettype}.log.content##"] = $data['change'];
             $datas['log'][] = $tmp;
         }
         $datas["##{$objettype}.numberoflogs##"] = count($datas['log']);
         // Get unresolved items
         $restrict = "`" . $item->getTable() . "`.`status`\n                        NOT IN ('" . implode("', '", array_merge($item->getSolvedStatusArray(), $item->getClosedStatusArray())) . "'\n                               )";
         if ($item->maybeDeleted()) {
             $restrict .= " AND `" . $item->getTable() . "`.`is_deleted` = '0' ";
         }
         $datas["##{$objettype}.numberofunresolved##"] = countElementsInTableForEntity($item->getTable(), $this->getEntity(), $restrict);
         // Document
         $query = "SELECT `glpi_documents`.*\n                   FROM `glpi_documents`\n                   LEFT JOIN `glpi_documents_items`\n                     ON (`glpi_documents`.`id` = `glpi_documents_items`.`documents_id`)\n                   WHERE `glpi_documents_items`.`itemtype` =  '" . $item->getType() . "'\n                         AND `glpi_documents_items`.`items_id` = '" . $item->getField('id') . "'";
         $datas["documents"] = array();
         $addtodownloadurl = '';
         if ($item->getType() == 'Ticket') {
             $addtodownloadurl = "%2526tickets_id=" . $item->fields['id'];
         }
         if ($result = $DB->query($query)) {
             while ($data = $DB->fetch_assoc($result)) {
                 $tmp = array();
                 $tmp['##document.id##'] = $data['id'];
                 $tmp['##document.name##'] = $data['name'];
                 $tmp['##document.weblink##'] = $data['link'];
                 $tmp['##document.url##'] = $this->formatURL($options['additionnaloption']['usertype'], "document_" . $data['id']);
                 $downloadurl = "/front/document.send.php?docid=" . $data['id'];
                 $tmp['##document.downloadurl##'] = $this->formatURL($options['additionnaloption']['usertype'], $downloadurl . $addtodownloadurl);
                 $tmp['##document.heading##'] = Dropdown::getDropdownName('glpi_documentcategories', $data['documentcategories_id']);
                 $tmp['##document.filename##'] = $data['filename'];
                 $datas['documents'][] = $tmp;
             }
         }
         $datas["##{$objettype}.urldocument##"] = $this->formatURL($options['additionnaloption']['usertype'], $objettype . "_" . $item->getField("id") . '_Document_Item$1');
         $datas["##{$objettype}.numberofdocuments##"] = count($datas['documents']);
         //costs infos
         $costtype = $item->getType() . 'Cost';
         $costs = $costtype::getCostsSummary($costtype, $item->getField("id"));
         $datas["##{$objettype}.costfixed##"] = $costs['costfixed'];
         $datas["##{$objettype}.costmaterial##"] = $costs['costmaterial'];
         $datas["##{$objettype}.costtime##"] = $costs['costtime'];
         $datas["##{$objettype}.totalcost##"] = $costs['totalcost'];
         $restrict = "`" . $item->getForeignKeyField() . "`='" . $item->getField('id') . "'";
         $restrict .= " ORDER BY `begin_date` DESC, `id` ASC";
         $costs = getAllDatasFromTable(getTableForItemType($costtype), $restrict);
         $datas['costs'] = array();
         foreach ($costs as $cost) {
             $tmp = array();
             $tmp['##cost.name##'] = $cost['name'];
             $tmp['##cost.comment##'] = $cost['comment'];
             $tmp['##cost.datebegin##'] = Html::convDate($cost['begin_date']);
             $tmp['##cost.dateend##'] = Html::convDate($cost['end_date']);
             $tmp['##cost.time##'] = $item->getActionTime($cost['actiontime']);
             $tmp['##cost.costtime##'] = Html::formatNumber($cost['cost_time']);
             $tmp['##cost.costfixed##'] = Html::formatNumber($cost['cost_fixed']);
             $tmp['##cost.costmaterial##'] = Html::formatNumber($cost['cost_material']);
             $tmp['##cost.totalcost##'] = CommonITILCost::computeTotalCost($cost['actiontime'], $cost['cost_time'], $cost['cost_fixed'], $cost['cost_material']);
             $tmp['##cost.budget##'] = Dropdown::getDropdownName('glpi_budgets', $cost['budgets_id']);
             $datas['costs'][] = $tmp;
         }
         $datas["##{$objettype}.numberofcosts##"] = count($datas['costs']);
         //Task infos
         $tasktype = $item->getType() . 'Task';
         $taskobj = new $tasktype();
         $restrict = "`" . $item->getForeignKeyField() . "`='" . $item->getField('id') . "'";
         if ($taskobj->maybePrivate() && (!isset($options['additionnaloption']['show_private']) || !$options['additionnaloption']['show_private'])) {
             $restrict .= " AND `is_private` = '0'";
         }
         $restrict .= " ORDER BY `date` DESC, `id` ASC";
         $tasks = getAllDatasFromTable($taskobj->getTable(), $restrict);
         $datas['tasks'] = array();
         foreach ($tasks as $task) {
             $tmp = array();
             $tmp['##task.id##'] = $task['id'];
             if ($taskobj->maybePrivate()) {
                 $tmp['##task.isprivate##'] = Dropdown::getYesNo($task['is_private']);
             }
             $tmp['##task.author##'] = Html::clean(getUserName($task['users_id']));
             $tmp_taskcatinfo = Dropdown::getDropdownName('glpi_taskcategories', $task['taskcategories_id'], true, true, false);
             $tmp['##task.categoryid##'] = $task['taskcategories_id'];
             $tmp['##task.category##'] = $tmp_taskcatinfo['name'];
             $tmp['##task.categorycomment##'] = $tmp_taskcatinfo['comment'];
             $tmp['##task.date##'] = Html::convDateTime($task['date']);
             $tmp['##task.description##'] = $task['content'];
             $tmp['##task.time##'] = Ticket::getActionTime($task['actiontime']);
             $tmp['##task.status##'] = Planning::getState($task['state']);
             $tmp['##task.user##'] = Html::clean(getUserName($task['users_id_tech']));
             $tmp['##task.group##'] = Html::clean(Toolbox::clean_cross_side_scripting_deep(Dropdown::getDropdownName("glpi_groups", $task['groups_id_tech'])), true, 2, false);
             $tmp['##task.begin##'] = "";
             $tmp['##task.end##'] = "";
             if (!is_null($task['begin'])) {
                 $tmp['##task.begin##'] = Html::convDateTime($task['begin']);
                 $tmp['##task.end##'] = Html::convDateTime($task['end']);
             }
             $datas['tasks'][] = $tmp;
         }
         $datas["##{$objettype}.numberoftasks##"] = count($datas['tasks']);
     }
     return $datas;
 }
Ejemplo n.º 8
0
 /**
  * Show OcsLink of an item
  *
  * @param $item                   CommonDBTM object
  * @param $withtemplate  integer  withtemplate param (default '')
  *
  * @return nothing
  **/
 static function showForItem(CommonDBTM $item, $withtemplate = '')
 {
     global $DB, $CFG_GLPI;
     $target = Toolbox::getItemTypeFormURL(__CLASS__);
     if (in_array($item->getType(), array('Computer'))) {
         $items_id = $item->getField('id');
         if (!empty($items_id) && $item->fields["is_dynamic"] && Session::haveRight("plugin_ocsinventoryng_view", READ)) {
             $query = "SELECT *\n                      FROM `glpi_plugin_ocsinventoryng_ocslinks`\n                      WHERE `computers_id` = '{$items_id}' " . getEntitiesRestrictRequest("AND", "glpi_plugin_ocsinventoryng_ocslinks");
             $result = $DB->query($query);
             if ($DB->numrows($result) > 0) {
                 $data = $DB->fetch_assoc($result);
                 $data = Toolbox::clean_cross_side_scripting_deep(Toolbox::addslashes_deep($data));
                 if (count($data)) {
                     $ocs_config = PluginOcsinventoryngOcsServer::getConfig(PluginOcsinventoryngOcsServer::getByMachineID($items_id));
                     echo "<div class='center'>";
                     echo "<form method='post' action=\"{$target}\">";
                     echo "<input type='hidden' name='id' value='{$items_id}'>";
                     echo "<table class='tab_cadre_fixe'>";
                     echo "<tr><th colspan = '4'>OCS Inventory NG</th>";
                     echo "<tr class='tab_bg_1'>";
                     $colspan = 4;
                     if (Session::haveRight("plugin_ocsinventoryng_view", READ) && Session::haveRight("plugin_ocsinventoryng_sync", UPDATE)) {
                         $colspan = 2;
                         echo "<td class='center'>" . __('Automatic update OCSNG', 'ocsinventoryng') . "</td>";
                         echo "<td class='left'>";
                         Dropdown::showYesNo("use_auto_update", $data["use_auto_update"]);
                         echo "</td>";
                     }
                     echo "<td class='center' colspan='" . $colspan . "'>";
                     printf(__('%1$s: %2$s'), __('OCSNG TAG', 'ocsinventoryng'), $data['tag']);
                     echo "</td></tr>";
                     if (Session::haveRight("plugin_ocsinventoryng_sync", UPDATE)) {
                         echo "<tr class='tab_bg_1'>";
                         $colspan = 4;
                         echo "<td class='center' colspan='2'>";
                         echo "<input type='hidden' name='resynch_id' value='" . $data["id"] . "'>";
                         echo "<input class=submit type='submit' name='force_ocs_resynch' value=\"" . _sx('button', 'Force synchronization', 'ocsinventoryng') . "\">";
                         echo "</td>";
                         //echo "<tr class='tab_bg_1'>";
                         echo "<td class='center' colspan='2'>";
                         echo "<input type='hidden' name='link_id' value='" . $data["id"] . "'>";
                         echo "<input class=submit type='submit' name='update' value=\"" . _sx('button', 'Save') . "\">";
                         echo "</td></tr>";
                     }
                     echo "</table>\n";
                     Html::closeForm();
                     echo "</div>";
                 }
             }
         }
     }
 }
 function updateModel($xml, $message, $result)
 {
     global $DB;
     $pfMapping = new PluginFusioninventoryMapping();
     if ($message == '1') {
         $_SESSION["MESSAGE_AFTER_REDIRECT"] = __('Model already exists', 'fusioninventory');
     }
     // Update model oids
     // Get list of oids in DB
     $a_oidsDB = array();
     $models_data = $DB->fetch_assoc($result);
     $pfModelMib = new PluginFusioninventorySnmpmodelMib();
     $pfModel = new PluginFusioninventorySnmpmodel();
     $pfModel->getFromDB($models_data['id']);
     $input = array();
     $input['id'] = $pfModel->fields['id'];
     $input['comment'] = Toolbox::clean_cross_side_scripting_deep(Toolbox::addslashes_deep((string) $xml->comments));
     $pfModel->update($input);
     $a_devices = array();
     if (isset($xml->devices)) {
         foreach ($xml->devices->sysdescr as $child) {
             $a_devices[] = (string) $child;
         }
     }
     $pfSnmpmodeldevice = new PluginFusioninventorySnmpmodeldevice();
     $pfSnmpmodeldevice->updateDevicesForModel($pfModel->fields['id'], $a_devices);
     $a_oids = $pfModelMib->find("`plugin_fusioninventory_snmpmodels_id`='" . $models_data['id'] . "'");
     foreach ($a_oids as $data) {
         $oid = Dropdown::getDropdownName("glpi_plugin_fusioninventory_snmpmodelmiboids", $data['plugin_fusioninventory_snmpmodelmiboids_id']);
         $oid_name = '';
         if ($data['plugin_fusioninventory_mappings_id'] != 0) {
             $pfMapping->getFromDB($data['plugin_fusioninventory_mappings_id']);
             $oid_name = $pfMapping->fields["name"];
         }
         $a_oidsDB[$oid . "-" . $oid_name] = $data['id'];
     }
     $mapping_type = '';
     foreach ($xml->oidlist->oidobject as $child) {
         $input = array();
         if (isset($a_oidsDB[$child->oid . "-" . $child->mapping_name])) {
             // Update oid
             $pfModelMib->getFromDB($a_oidsDB[$child->oid . "-" . $child->mapping_name]);
             $input = $pfModelMib->fields;
         }
         $input["plugin_fusioninventory_snmpmodels_id"] = $models_data['id'];
         $input['plugin_fusioninventory_snmpmodelmibobjects_id'] = 0;
         if (isset($child->object)) {
             $input['plugin_fusioninventory_snmpmodelmibobjects_id'] = Dropdown::importExternal("PluginFusioninventorySnmpmodelMibObject", $child->object);
         }
         $input['plugin_fusioninventory_snmpmodelmiboids_id'] = Dropdown::importExternal("PluginFusioninventorySnmpmodelMibOid", $child->oid);
         $input['oid_port_counter'] = 0;
         if (isset($child->portcounter)) {
             $input['oid_port_counter'] = $child->portcounter;
         }
         $input['oid_port_dyn'] = 0;
         if (isset($child->dynamicport)) {
             $input['oid_port_dyn'] = $child->dynamicport;
         }
         $input["vlan"] = 0;
         if (isset($child->vlan)) {
             $input["vlan"] = $child->vlan;
         }
         $input["is_active"] = 0;
         if (isset($child->activation)) {
             $input["is_active"] = $child->activation;
         }
         if (isset($mapping_type)) {
             unset($mapping_type);
         }
         if (isset($child->mapping_type)) {
             $mapping_type = '';
             if (is_numeric($child->mapping_type)) {
                 switch ($child->mapping_type) {
                     case '1':
                         $mapping_type = "Computer";
                         break;
                     case '2':
                         $mapping_type = "NetworkEquipment";
                         break;
                     case '3':
                         $mapping_type = "Printer";
                         break;
                 }
             } else {
                 $mapping_type = $child->mapping_type;
             }
         }
         $input["plugin_fusioninventory_mappings_id"] = 0;
         if (isset($child->mapping_name)) {
             if ($child->mapping_name != '') {
                 $a_mappings = $pfMapping->get($mapping_type, $child->mapping_name);
                 $input["plugin_fusioninventory_mappings_id"] = $a_mappings['id'];
             }
         }
         $input["plugin_fusioninventory_mappings_id"] = 0;
         if (isset($child->mapping_name)) {
             if ($child->mapping_name != '') {
                 $a_mappings = $pfMapping->get($mapping_type, $child->mapping_name);
                 $input["plugin_fusioninventory_mappings_id"] = $a_mappings['id'];
             }
         }
         $input["plugin_fusioninventory_snmpmodelmiblabels"] = 0;
         if (isset($a_oidsDB[$child->oid . "-" . $child->mapping_name])) {
             // Update oid
             $pfModelMib->update($input);
             unset($a_oidsDB[$child->oid . "-" . $child->mapping_name]);
         } else {
             // Add
             $pfModelMib->add($input);
         }
     }
     // Delete OID not in the XML
     foreach ($a_oidsDB as $mibs_id) {
         $pfModelMib->delete(array('id' => $mibs_id), 1);
     }
 }
Ejemplo n.º 10
0
 function cleanValue($value)
 {
     $value = Html::clean($value);
     $value = Toolbox::clean_cross_side_scripting_deep($value);
     $value = Toolbox::addslashes_deep($value);
     return $value;
 }
Ejemplo n.º 11
0
 /**
  *
  * Import peripherals from OCS
  * @since 1.0
  * @param $cfg_ocs OCSNG mode configuration
  * @param $computers_id computer's id in GLPI
  * @param $ocsid computer's id in OCS
  * @param $ocsservers_id OCS server id
  * @param $entity the entity in which the peripheral will be created
  * @param $dohistory record in history link between peripheral and computer
  */
 static function importPeripheral($cfg_ocs, $computers_id, $ocsservers_id, $ocsComputer, $entity, $dohistory)
 {
     global $DB;
     $already_processed = array();
     $p = new Peripheral();
     $conn = new Computer_Item();
     if (isset($ocsComputer["INPUTS"])) {
         if (count($ocsComputer["INPUTS"]) > 0) {
             foreach ($ocsComputer["INPUTS"] as $peripheral) {
                 if ($peripheral["CAPTION"] !== '') {
                     $peripherals[] = $peripheral;
                 }
             }
             if (count($peripherals) > 0) {
                 foreach ($peripherals as $peripheral) {
                     $peripheral = Toolbox::clean_cross_side_scripting_deep(Toolbox::addslashes_deep($peripheral));
                     $periph = array();
                     $periph["name"] = self::encodeOcsDataInUtf8($cfg_ocs["ocs_db_utf8"], $peripheral["CAPTION"]);
                     //Look for a monitor with the same name (and serial if possible) already connected
                     //to this computer
                     $query = "SELECT `p`.`id`, `gci`.`is_deleted`\n                                       FROM `glpi_printers` as `p`, `glpi_computers_items` as `gci`\n                                       WHERE `p`.`id` = `gci`.`items_id`\n                                       AND `gci`.`is_dynamic`='1'\n                                       AND `computers_id`='{$computers_id}'\n                                       AND `itemtype`='Peripheral'\n                                       AND `p`.`name`='" . $periph["name"] . "'";
                     $results = $DB->query($query);
                     $id = false;
                     $lock = false;
                     if ($DB->numrows($results) > 0) {
                         $id = $DB->result($results, 0, 'id');
                         $lock = $DB->result($results, 0, 'is_deleted');
                     }
                     if (!$id) {
                         // Clean peripheral object
                         $p->reset();
                         if ($peripheral["MANUFACTURER"] != "NULL") {
                             $periph["brand"] = self::encodeOcsDataInUtf8($cfg_ocs["ocs_db_utf8"], $peripheral["MANUFACTURER"]);
                         }
                         if ($peripheral["INTERFACE"] != "NULL") {
                             $periph["comment"] = self::encodeOcsDataInUtf8($cfg_ocs["ocs_db_utf8"], $peripheral["INTERFACE"]);
                         }
                         $periph["peripheraltypes_id"] = Dropdown::importExternal('PeripheralType', $peripheral["TYPE"]);
                         $id_periph = 0;
                         if ($cfg_ocs["import_periph"] == 1) {
                             //Config says : manage peripherals as global
                             //check if peripherals already exists in GLPI
                             $periph["is_global"] = 1;
                             $query = "SELECT `id`\n                                           FROM `glpi_peripherals`\n                                           WHERE `name` = '" . $periph["name"] . "'\n                                           AND `is_global` = '1'\n                                           AND `entities_id` = '{$entity}'";
                             $result_search = $DB->query($query);
                             if ($DB->numrows($result_search) > 0) {
                                 //Periph is already in GLPI
                                 //Do not import anything just get periph ID for link
                                 $id_periph = $DB->result($result_search, 0, "id");
                             } else {
                                 $input = $periph;
                                 if ($cfg_ocs["states_id_default"] > 0) {
                                     $input["states_id"] = $cfg_ocs["states_id_default"];
                                 }
                                 $input["entities_id"] = $entity;
                                 $id_periph = $p->add($input);
                             }
                         } else {
                             if ($cfg_ocs["import_periph"] == 2) {
                                 //Config says : manage peripherals as single units
                                 //Import all peripherals as non global.
                                 $input = $periph;
                                 $input["is_global"] = 0;
                                 if ($cfg_ocs["states_id_default"] > 0) {
                                     $input["states_id"] = $cfg_ocs["states_id_default"];
                                 }
                                 $input["entities_id"] = $entity;
                                 $id_periph = $p->add($input);
                             }
                         }
                         if ($id_periph) {
                             $already_processed[] = $id_periph;
                             $conn = new Computer_Item();
                             if ($connID = $conn->add(array('computers_id' => $computers_id, 'itemtype' => 'Peripheral', 'items_id' => $id_periph, '_no_history' => !$dohistory, 'is_dynamic' => 1))) {
                                 //Update column "is_deleted" set value to 0 and set status to default
                                 $input = array();
                                 $input["id"] = $id_periph;
                                 $input["is_deleted"] = 0;
                                 $input["entities_id"] = $entity;
                                 if ($cfg_ocs["states_id_default"] > 0) {
                                     $input["states_id"] = $cfg_ocs["states_id_default"];
                                 }
                                 $p->update($input);
                             }
                         }
                     } else {
                         $already_processed[] = $id;
                     }
                 }
             }
         }
     }
     //Look for all peripherals, not locked, not linked to the computer anymore
     $query = "SELECT `id`\n                      FROM `glpi_computers_items`\n                      WHERE `itemtype`='Peripheral'\n                         AND `computers_id`='{$computers_id}'\n                         AND `is_dynamic`='1'\n                         AND `is_deleted`='0'";
     if (!empty($already_processed)) {
         $query .= "AND `items_id` NOT IN (" . implode(',', $already_processed) . ")";
     }
     foreach ($DB->request($query) as $data) {
         // Delete all connexions
         //Get OCS configuration
         $ocs_config = PluginOcsinventoryngOcsServer::getConfig($ocsservers_id);
         //Get the management mode for this device
         $mode = PluginOcsinventoryngOcsServer::getDevicesManagementMode($ocs_config, 'Peripheral');
         $decoConf = $ocs_config["deconnection_behavior"];
         //Change status if :
         // 1 : the management mode IS NOT global
         // 2 : a deconnection's status have been defined
         // 3 : unique with serial
         if ($mode >= 2 && strlen($decoConf) > 0) {
             //Delete periph from glpi
             if ($decoConf == "delete") {
                 $query = "DELETE\n             FROM `glpi_computers_items`\n             WHERE `id`='" . $data['id'] . "'";
                 $result = $DB->query($query);
                 //Put periph in dustbin
             } else {
                 if ($decoConf == "trash") {
                     $query = "UPDATE\n             `glpi_computers_items`\n             SET `is_deleted` = 1\n             WHERE `id`='" . $data['id'] . "'";
                     $result = $DB->query($query);
                 }
             }
         }
         // foreach ($DB->request($query) as $data){
         // Delete all connexions
         // $conn->delete(array('id'             => $data['id'],
         // '_ocsservers_id' => $ocsservers_id), true);
     }
 }
Ejemplo n.º 12
0
 static function protectData($data)
 {
     if (Toolbox::get_magic_quotes_gpc()) {
         $data = Toolbox::stripslashes_deep($data);
     }
     $data = Toolbox::addslashes_deep($data);
     $data = Toolbox::clean_cross_side_scripting_deep($data);
     return $data;
 }
Ejemplo n.º 13
0
 function displayField($name, $fieldname, $valuedisplay, $value = '', $checked = '')
 {
     if ($value == '') {
         $value = $valuedisplay;
     }
     $type = 'checkbox';
     $inputname = 'checked[]';
     if (strstr($fieldname, 'requester') || strstr($fieldname, 'assign')) {
         $type = 'radio';
         $inputname = $fieldname;
         $fieldname = $value;
     }
     echo "<tr class='tab_bg_3'>";
     echo "<td>";
     echo "<input type='" . $type . "' name='" . $inputname . "' value='" . $fieldname . "' " . $checked . " />";
     echo "</td>";
     echo "<td>";
     echo $name;
     echo "</td>";
     echo "<td>";
     echo $valuedisplay;
     if ($type == 'checkbox') {
         $value = Html::cleanInputText(Toolbox::clean_cross_side_scripting_deep(stripslashes($value)));
         echo '<input type="hidden" name="' . $fieldname . '" value="' . $value . '" />';
     }
     echo "</td>";
     echo "</tr>";
 }
Ejemplo n.º 14
0
 /**
  * Convert simple text content to rich text content, init html editor
  *
  * @since version 0.85
  *
  * @param $name       name of textarea
  * @param $content    content to convert in html
  * @param $rand
  *
  * @return $content
  **/
 function setRichTextContent($name, $content, $rand)
 {
     // Init html editor
     Html::initEditorSystem($name, $rand);
     // If no html
     if ($content == strip_tags($content)) {
         $content = $this->convertTagToImage($content);
     }
     // If content does not contain <br> or <p> html tag, use nl2br
     $content = Html::entity_decode_deep($content);
     if (!preg_match("/<br\\s?\\/?>/", $content) && !preg_match("/<p>/", $content)) {
         $content = nl2br($content);
     }
     return Toolbox::clean_cross_side_scripting_deep($content);
 }
Ejemplo n.º 15
0
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

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

You should have received a copy of the GNU General Public License
along with GLPI. If not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------
*/
/** @file
* @brief
*/
include '../../../inc/includes.php';
header("Content-Type: text/html; charset=UTF-8");
Html::header_nocache();
Session::checkLoginUser();
if (isset($_POST['name'])) {
    $step = 1;
    if (!isset($_REQUEST['force_integer'])) {
        $step = PLUGIN_ORDER_NUMBER_STEP;
    }
    $class = "";
    if (isset($_REQUEST['class'])) {
        $class = "class='" . $_REQUEST['class'] . "'";
    }
    $data = Html::cleanInputText(Toolbox::clean_cross_side_scripting_deep(rawurldecode(stripslashes($_POST["data"]))));
    echo "<input type='number' step='{$step}' name='" . $_POST['name'] . "' value='{$data}' {$class}>";
}
Ejemplo n.º 16
0
 /**
  *
  * Import peripherals from OCS
  * @since 1.0
  * @param $cfg_ocs OCSNG mode configuration
  * @param $computers_id computer's id in GLPI
  * @param $ocsid computer's id in OCS
  * @param $ocsservers_id OCS server id
  * @param $entity the entity in which the peripheral will be created
  * @param $dohistory record in history link between peripheral and computer
  */
 static function importPeripheral($cfg_ocs, $computers_id, $ocsservers_id, $ocsid, $entity, $dohistory)
 {
     global $PluginOcsinventoryngDBocs, $DB;
     self::checkOCSconnection($ocsservers_id);
     if ($cfg_ocs["import_periph"]) {
         $already_processed = array();
         $p = new Peripheral();
         $conn = new Computer_Item();
         $query = "SELECT DISTINCT `CAPTION`, `MANUFACTURER`, `INTERFACE`, `TYPE`\n                   FROM `inputs`\n                   WHERE `HARDWARE_ID` = '{$ocsid}'\n                   AND `CAPTION` <> ''";
         $result = $PluginOcsinventoryngDBocs->query($query);
         if ($PluginOcsinventoryngDBocs->numrows($result) > 0) {
             while ($line = $PluginOcsinventoryngDBocs->fetch_array($result)) {
                 $line = Toolbox::clean_cross_side_scripting_deep(Toolbox::addslashes_deep($line));
                 $periph = array();
                 $periph["name"] = self::encodeOcsDataInUtf8($cfg_ocs["ocs_db_utf8"], $line["CAPTION"]);
                 //Look for a monitor with the same name (and serial if possible) already connected
                 //to this computer
                 $query = "SELECT `p`.`id`, `gci`.`is_deleted`\n                         FROM `glpi_printers` as `p`, `glpi_computers_items` as `gci`\n                         WHERE `p`.`id` = `gci`.`items_id`\n                            AND `gci`.`is_dynamic`='1'\n                            AND `computers_id`='{$computers_id}'\n                            AND `itemtype`='Peripheral'\n                            AND `p`.`name`='" . $periph["name"] . "'";
                 $results = $DB->query($query);
                 $id = false;
                 $lock = false;
                 if ($DB->numrows($results) > 0) {
                     $id = $DB->result($results, 0, 'id');
                     $lock = $DB->result($results, 0, 'is_deleted');
                 }
                 if (!$id) {
                     // Clean peripheral object
                     $p->reset();
                     if ($line["MANUFACTURER"] != "NULL") {
                         $periph["brand"] = self::encodeOcsDataInUtf8($cfg_ocs["ocs_db_utf8"], $line["MANUFACTURER"]);
                     }
                     if ($line["INTERFACE"] != "NULL") {
                         $periph["comment"] = self::encodeOcsDataInUtf8($cfg_ocs["ocs_db_utf8"], $line["INTERFACE"]);
                     }
                     $periph["peripheraltypes_id"] = Dropdown::importExternal('PeripheralType', $line["TYPE"]);
                     $id_periph = 0;
                     if ($cfg_ocs["import_periph"] == 1) {
                         //Config says : manage peripherals as global
                         //check if peripherals already exists in GLPI
                         $periph["is_global"] = 1;
                         $query = "SELECT `id`\n                               FROM `glpi_peripherals`\n                               WHERE `name` = '" . $periph["name"] . "'\n                                  AND `is_global` = '1'\n                                  AND `entities_id` = '{$entity}'";
                         $result_search = $DB->query($query);
                         if ($DB->numrows($result_search) > 0) {
                             //Periph is already in GLPI
                             //Do not import anything just get periph ID for link
                             $id_periph = $DB->result($result_search, 0, "id");
                         } else {
                             $input = $periph;
                             if ($cfg_ocs["states_id_default"] > 0) {
                                 $input["states_id"] = $cfg_ocs["states_id_default"];
                             }
                             $input["entities_id"] = $entity;
                             $id_periph = $p->add($input);
                         }
                     } else {
                         if ($cfg_ocs["import_periph"] == 2) {
                             //Config says : manage peripherals as single units
                             //Import all peripherals as non global.
                             $input = $periph;
                             $input["is_global"] = 0;
                             if ($cfg_ocs["states_id_default"] > 0) {
                                 $input["states_id"] = $cfg_ocs["states_id_default"];
                             }
                             $input["entities_id"] = $entity;
                             $id_periph = $p->add($input);
                         }
                     }
                     if ($id_periph) {
                         $already_processed[] = $id_periph;
                         $conn = new Computer_Item();
                         if ($connID = $conn->add(array('computers_id' => $computers_id, 'itemtype' => 'Peripheral', 'items_id' => $id_periph, '_no_history' => !$dohistory, 'is_dynamic' => 1))) {
                             //Update column "is_deleted" set value to 0 and set status to default
                             $input = array();
                             $input["id"] = $id_periph;
                             $input["is_deleted"] = 0;
                             $input["entities_id"] = $entity;
                             if ($cfg_ocs["states_id_default"] > 0) {
                                 $input["states_id"] = $cfg_ocs["states_id_default"];
                             }
                             $p->update($input);
                         }
                     }
                 } else {
                     $already_processed[] = $id;
                 }
             }
         }
         //Look for all monitors, not locked, not linked to the computer anymore
         $query = "SELECT `id`\n                   FROM `glpi_computers_items`\n                   WHERE `itemtype`='Peripheral'\n                      AND `computers_id`='{$computers_id}'\n                      AND `is_dynamic`='1'\n                      AND `is_deleted`='0'";
         if (!empty($already_processed)) {
             $query .= "AND `items_id` NOT IN (" . implode(',', $already_processed) . ")";
         }
         foreach ($DB->request($query) as $data) {
             //Delete all connexions
             $conn->delete(array('id' => $data['id'], '_ocsservers_id' => $ocsservers_id), true);
         }
     }
 }
 /**
  * @param $plugin_ocsinventoryng_ocsservers_id
  * @param $check
  * @param $start
  * @return bool|void
  */
 static function showSnmpDeviceToUpdate($plugin_ocsinventoryng_ocsservers_id, $check, $start)
 {
     global $DB, $CFG_GLPI;
     PluginOcsinventoryngOcsServer::checkOCSconnection($plugin_ocsinventoryng_ocsservers_id);
     if (!Session::haveRight("plugin_ocsinventoryng", UPDATE)) {
         return false;
     }
     // Get linked computer ids in GLPI
     $already_linked_query = "SELECT `glpi_plugin_ocsinventoryng_snmpocslinks`.`ocs_id` AS ocsid\n                               FROM `glpi_plugin_ocsinventoryng_snmpocslinks`\n                               WHERE `glpi_plugin_ocsinventoryng_snmpocslinks`.`plugin_ocsinventoryng_ocsservers_id`\n                                            = '{$plugin_ocsinventoryng_ocsservers_id}'";
     $already_linked_result = $DB->query($already_linked_query);
     if ($DB->numrows($already_linked_result) == 0) {
         echo "<div class='center b'>" . __('No new SNMP device to be updated', 'ocsinventoryng') . "</div>";
         return;
     }
     $already_linked_ids = array();
     while ($data = $DB->fetch_assoc($already_linked_result)) {
         $already_linked_ids[] = $data['ocsid'];
     }
     // Fetch linked items from ocs
     $ocsClient = PluginOcsinventoryngOcsServer::getDBocs($plugin_ocsinventoryng_ocsservers_id);
     $ocsResult = $ocsClient->getSnmp(array('ORDER' => 'LASTDATE', 'FILTER' => array('IDS' => $already_linked_ids)));
     if (isset($ocsResult['SNMP'])) {
         if (count($ocsResult['SNMP']) > 0) {
             // Get all ids of the returned items
             $ocs_snmp_ids = array();
             $hardware = array();
             $snmps = array_slice($ocsResult['SNMP'], $start, $_SESSION['glpilist_limit']);
             foreach ($snmps as $snmp) {
                 $LASTDATE = $snmp['META']['LASTDATE'];
                 $ocs_snmp_inv[$snmp['META']['ID']] = $LASTDATE;
                 $NAME = $snmp['META']['NAME'];
                 $ocs_snmp_name[$snmp['META']['ID']] = $NAME;
                 $ID = $snmp['META']['ID'];
                 $ocs_snmp_ids[] = $ID;
                 if (isset($snmp['PRINTER'])) {
                     $TYPE = "printer";
                 } else {
                     $TYPE = "";
                 }
                 $ocs_snmp_type[$snmp['META']['ID']] = $TYPE;
             }
             // query snmp links
             $query = "SELECT * FROM `glpi_plugin_ocsinventoryng_snmpocslinks`\n                WHERE `glpi_plugin_ocsinventoryng_snmpocslinks`.`ocs_id` IN (" . implode(',', $ocs_snmp_ids) . ")";
             $result = $DB->query($query);
             // Get all links between glpi and OCS
             $already_linked = array();
             if ($DB->numrows($result) > 0) {
                 while ($data = $DB->fetch_assoc($result)) {
                     $data = Toolbox::clean_cross_side_scripting_deep(Toolbox::addslashes_deep($data));
                     $format = 'Y-m-d H:i:s';
                     //                  $last_glpi_update = DateTime::createFromFormat($format, $data['last_update']);
                     //                  $last_ocs_inventory = DateTime::createFromFormat($format, $ocs_snmp_inv[$data['ocs_id']]);
                     //TODOSNMP comment for test
                     //if ($last_ocs_inventory > $last_glpi_update) {
                     $already_linked[$data['id']] = $data;
                     //}
                 }
             }
             echo "<div class='center'>";
             echo "<h2>" . __('Snmp device updated in OCSNG', 'ocsinventoryng') . "</h2>";
             $target = $CFG_GLPI['root_doc'] . '/plugins/ocsinventoryng/front/ocsngsnmp.sync.php';
             if (($numrows = $ocsResult['TOTAL_COUNT']) > 0) {
                 $parameters = "check={$check}";
                 Html::printPager($start, $numrows, $target, $parameters);
                 echo "<form method='post' id='ocsng_form' name='ocsng_form' action='" . $target . "'>";
                 PluginOcsinventoryngOcsServer::checkBox($target);
                 echo "<table class='tab_cadre_fixe'>";
                 echo "<tr class='tab_bg_1'><td colspan='6' class='center'>";
                 echo "<input class='submit' type='submit' name='update_ok' value=\"" . _sx('button', 'Synchronize', 'ocsinventoryng') . "\">";
                 echo "&nbsp;<input class='submit' type='submit' name='delete' value=\"" . _sx('button', 'Delete link', 'ocsinventoryng') . "\">";
                 echo "</td></tr>\n";
                 echo "<tr>";
                 echo "<th>" . __('GLPI Object', 'ocsinventoryng') . "</th>";
                 echo "<th>" . __('Item type') . "</th>";
                 echo "<th>" . __('OCS SNMP device', 'ocsinventoryng') . "</th>";
                 echo "<th>" . __('Import date in GLPI', 'ocsinventoryng') . "</th>";
                 echo "<th>" . __('Last OCSNG SNMP inventory date', 'ocsinventoryng') . "</th>";
                 echo "<th>&nbsp;</th></tr>\n";
                 foreach ($already_linked as $ID => $tab) {
                     echo "<tr class='tab_bg_2 center'>";
                     $item = new $tab["itemtype"]();
                     $item->getFromDB($tab["items_id"]);
                     echo "<td>" . $item->getLink() . "</td>\n";
                     echo "<td>" . $item->getTypeName() . "</td>\n";
                     echo "<td>" . $ocs_snmp_name[$tab["ocs_id"]] . "</td>\n";
                     echo "<td>" . Html::convDateTime($tab["last_update"]) . "</td>\n";
                     echo "<td>" . Html::convDateTime($ocs_snmp_inv[$tab["ocs_id"]]) . "</td>\n";
                     echo "<td><input type='checkbox' name='toupdate[" . $tab["id"] . "]' " . ($check == "all" ? "checked" : "") . ">";
                     echo "</td></tr>\n";
                 }
                 echo "<tr class='tab_bg_1'><td colspan='6' class='center'>";
                 echo "<input class='submit' type='submit' name='update_ok' value=\"" . _sx('button', 'Synchronize', 'ocsinventoryng') . "\">";
                 echo "&nbsp;<input class='submit' type='submit' name='delete' value=\"" . _sx('button', 'Delete link', 'ocsinventoryng') . "\">";
                 echo "<input type=hidden name='plugin_ocsinventoryng_ocsservers_id' " . "value='{$plugin_ocsinventoryng_ocsservers_id}'>";
                 echo "</td></tr>";
                 echo "<tr class='tab_bg_1'><td colspan='6' class='center'>";
                 PluginOcsinventoryngOcsServer::checkBox($target);
                 echo "</table>\n";
                 Html::closeForm();
                 Html::printPager($start, $numrows, $target, $parameters);
             } else {
                 echo "<br><span class='b'>" . __('Update SNMP device', 'ocsinventoryng') . "</span>";
             }
             echo "</div>";
         } else {
             echo "<div class='center b'>" . __('No new SNMP device to be updated', 'ocsinventoryng') . "</div>";
         }
     } else {
         echo "<div class='center b'>" . __('No new SNMP device to be updated', 'ocsinventoryng') . "</div>";
     }
 }
 /**
  * Clean XML, ie convert to be insert without problem into MySQL DB
  *
  * @param $xml SimpleXMLElement object
  * @return SimpleXMLElement object
  */
 function cleanXML($xml)
 {
     $nodes = array();
     foreach ($xml->children() as $key => $value) {
         if (!isset($nodes[$key])) {
             $nodes[$key] = 0;
         }
         $nodes[$key]++;
     }
     foreach ($nodes as $key => $nb) {
         if ($nb < 2) {
             unset($nodes[$key]);
         }
     }
     if (count($xml) > 0) {
         $i = 0;
         foreach ($xml->children() as $key => $value) {
             if (count($value->children()) > 0) {
                 $this->cleanXML($value);
             } else {
                 if (isset($nodes[$key])) {
                     $xml->{$key}->{$i} = Toolbox::clean_cross_side_scripting_deep(Toolbox::addslashes_deep($value));
                     $i++;
                 } else {
                     $xml->{$key} = Toolbox::clean_cross_side_scripting_deep(Toolbox::addslashes_deep($value));
                 }
             }
         }
     }
     return $xml;
 }
LICENSE

This file is part of GLPI.

GLPI is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

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

You should have received a copy of the GNU General Public License
along with GLPI. If not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------
*/
/** @file
* @brief
*/
$AJAX_INCLUDE = 1;
include '../inc/includes.php';
header("Content-Type: text/html; charset=UTF-8");
Html::header_nocache();
Session::checkLoginUser();
if (isset($_POST['name'])) {
    echo "<textarea " . (isset($_POST['rows']) ? " rows='" . $_POST['rows'] . "' " : "") . " " . (isset($_POST['cols']) ? " cols='" . $_POST['cols'] . "' " : "") . "  name='" . $_POST['name'] . "'>";
    echo Html::cleanPostForTextArea(Toolbox::clean_cross_side_scripting_deep(rawurldecode($_POST["data"])));
    echo "</textarea>";
}
 static function updateDetailForPerfdata($perfdata, $perfdatas_id)
 {
     $a_lines = array();
     $a_perfdata = PluginMonitoringPerfdata::splitPerfdata($perfdata);
     $i = 1;
     foreach ($a_perfdata as $data) {
         $data = trim($data, ", ");
         $a_a_perfdata = explode("=", $data);
         $a_a_perfdata[0] = trim($a_a_perfdata[0], "'");
         if (!isset($a_a_perfdata[1])) {
             return;
         }
         //$a_a_perfdata[1] = trim($a_a_perfdata[1], ";");
         $a_lines[$i] = array('name' => $a_a_perfdata[0]);
         $a_perfdata_final = explode(";", $a_a_perfdata[1]);
         $num = 1;
         foreach ($a_perfdata_final as $nb_val => $val) {
             if ($val == '') {
                 if ($nb_val < count($a_perfdata_final) - 1) {
                     $a_lines[$i]['values'][$num] = '';
                 }
             } else {
                 $a_lines[$i]['values'][$num] = '';
             }
             $num++;
         }
         $i++;
     }
     // Add/update perfdatadetails in DB
     $pmPerfdataDetail = new PluginMonitoringPerfdataDetail();
     $a_perfdatadetails = $pmPerfdataDetail->find("`plugin_monitoring_perfdatas_id`='" . $perfdatas_id . "'", "position");
     foreach ($a_perfdatadetails as $data) {
         $find = 0;
         foreach ($a_lines as $key => $a_line) {
             if ($a_line['name'] == $data['name'] && $data['position'] == $key && !$find) {
                 $find = 1;
                 $countfind = count($a_line['values']);
                 $input = array();
                 $input['id'] = $data['id'];
                 $input['dsname_num'] = $countfind;
                 for ($i = 1; $i <= $countfind; $i++) {
                     if ($data['dsname' . $i] == '') {
                         $input['dsname' . $i] = 'value' . $data['position'] . '.' . $i;
                     }
                 }
                 for ($i = $countfind + 1; $i < 9; $i++) {
                     $input['dsname' . $i] = '';
                 }
                 $pmPerfdataDetail->update($input);
                 unset($a_lines[$key]);
             }
         }
         if (!$find) {
             $pmPerfdataDetail->delete($data);
         }
     }
     foreach ($a_lines as $position => $data) {
         $input = array();
         $input['name'] = Toolbox::clean_cross_side_scripting_deep(Toolbox::addslashes_deep($data['name']));
         $input['plugin_monitoring_perfdatas_id'] = $perfdatas_id;
         $input['position'] = $position;
         $input['dsname_num'] = count($data['values']);
         for ($i = 1; $i <= $input['dsname_num']; $i++) {
             $input['dsname' . $i] = 'value' . $position . '.' . $i;
         }
         $pmPerfdataDetail->add($input);
     }
 }
Ejemplo n.º 21
0
 function prepareInputForAdd($input)
 {
     global $CFG_GLPI;
     // save value before clean;
     $title = ltrim($input['name']);
     // Standard clean datas
     $input = parent::prepareInputForAdd($input);
     // Do not check mandatory on auto import (mailgates)
     if (!isset($input['_auto_import'])) {
         if (isset($input['_tickettemplates_id']) && $input['_tickettemplates_id']) {
             $tt = new TicketTemplate();
             if ($tt->getFromDBWithDatas($input['_tickettemplates_id'])) {
                 if (count($tt->mandatory)) {
                     $mandatory_missing = array();
                     $fieldsname = $tt->getAllowedFieldsNames(true);
                     foreach ($tt->mandatory as $key => $val) {
                         // for title if mandatory (restore initial value)
                         if ($key == 'name') {
                             $input['name'] = $title;
                         }
                         // Check only defined values : Not defined not in form
                         if (isset($input[$key])) {
                             // If content is also predefined need to be different from predefined value
                             if ($key == 'content' && isset($tt->predefined['content'])) {
                                 // Clean new lines to be fix encoding
                                 if (strcmp(preg_replace("/\r?\n/", "", Html::cleanPostForTextArea($input[$key])), preg_replace("/\r?\n/", "", $tt->predefined['content'])) == 0) {
                                     $mandatory_missing[$key] = $fieldsname[$val];
                                 }
                             }
                             if (empty($input[$key]) || $input[$key] == 'NULL') {
                                 $mandatory_missing[$key] = $fieldsname[$val];
                             }
                         }
                         if ($key == '_add_validation' && !empty($input['users_id_validate']) && isset($input['users_id_validate'][0]) && $input['users_id_validate'][0] > 0) {
                             unset($mandatory_missing['_add_validation']);
                         }
                         // For due_date : check also slas_id
                         if ($key == 'due_date' && isset($input['slas_id']) && $input['slas_id'] > 0 && isset($mandatory_missing['due_date'])) {
                             unset($mandatory_missing['due_date']);
                         }
                     }
                     if (count($mandatory_missing)) {
                         //TRANS: %s are the fields concerned
                         $message = sprintf(__('Mandatory fields are not filled. Please correct: %s'), implode(", ", $mandatory_missing));
                         Session::addMessageAfterRedirect($message, false, ERROR);
                         return false;
                     }
                 }
             }
         }
     }
     if (!isset($input["requesttypes_id"])) {
         $input["requesttypes_id"] = RequestType::getDefault('helpdesk');
     }
     if (!isset($input['global_validation'])) {
         $input['global_validation'] = CommonITILValidation::NONE;
     }
     // Set additional default dropdown
     $dropdown_fields = array('items_id', 'users_locations');
     foreach ($dropdown_fields as $field) {
         if (!isset($input[$field])) {
             $input[$field] = 0;
         }
     }
     if (!isset($input['itemtype']) || !($input['items_id'] > 0)) {
         $input['itemtype'] = '';
     }
     // Get item
     $item = NULL;
     if ($input["items_id"] > 0 && !empty($input["itemtype"])) {
         if ($item = getItemForItemtype($input["itemtype"])) {
             $item->getFromDB($input["items_id"]);
         }
     }
     // Business Rules do not override manual SLA
     $manual_slas_id = 0;
     if (isset($input['slas_id']) && $input['slas_id'] > 0) {
         $manual_slas_id = $input['slas_id'];
     }
     // Process Business Rules
     $rules = new RuleTicketCollection($input['entities_id']);
     // Set unset variables with are needed
     $user = new User();
     if (isset($input["_users_id_requester"]) && $user->getFromDB($input["_users_id_requester"])) {
         $input['users_locations'] = $user->fields['locations_id'];
         $tmprequester = $input["_users_id_requester"];
     } else {
         $tmprequester = 0;
     }
     // Clean new lines before passing to rules
     if (isset($input["content"])) {
         $input["content"] = preg_replace('/\\\\r\\\\n/', "\n", $input['content']);
         $input["content"] = preg_replace('/\\\\n/', "\n", $input['content']);
         $input["content"] = Toolbox::clean_cross_side_scripting_deep(Html::clean($input["content"]));
     }
     $input = $rules->processAllRules(Toolbox::stripslashes_deep($input), Toolbox::stripslashes_deep($input), array('recursive' => true), array('condition' => RuleTicket::ONADD));
     // Recompute default values based on values computed by rules
     $input = $this->computeDefaultValuesForAdd($input);
     if (isset($input['_users_id_requester']) && $input['_users_id_requester'] != $tmprequester) {
         // if requester set by rule, clear address from mailcollector
         unset($input['_users_id_requester_notif']);
     }
     // Restore slas_id
     if ($manual_slas_id > 0) {
         $input['slas_id'] = $manual_slas_id;
     }
     // Manage auto assign
     $auto_assign_mode = Entity::getUsedConfig('auto_assign_mode', $input['entities_id']);
     switch ($auto_assign_mode) {
         case Entity::CONFIG_NEVER:
             break;
         case Entity::AUTO_ASSIGN_HARDWARE_CATEGORY:
             if ($item != NULL) {
                 // Auto assign tech from item
                 if ((!isset($input['_users_id_assign']) || $input['_users_id_assign'] == 0) && $item->isField('users_id_tech')) {
                     $input['_users_id_assign'] = $item->getField('users_id_tech');
                 }
                 // Auto assign group from item
                 if ((!isset($input['_groups_id_assign']) || $input['_groups_id_assign'] == 0) && $item->isField('groups_id_tech')) {
                     $input['_groups_id_assign'] = $item->getField('groups_id_tech');
                 }
             }
             // Auto assign tech/group from Category
             if ($input['itilcategories_id'] > 0 && (!isset($input['_users_id_assign']) || !$input['_users_id_assign'] || (!isset($input['_groups_id_assign']) || !$input['_groups_id_assign']))) {
                 $cat = new ITILCategory();
                 $cat->getFromDB($input['itilcategories_id']);
                 if ((!isset($input['_users_id_assign']) || !$input['_users_id_assign']) && $cat->isField('users_id')) {
                     $input['_users_id_assign'] = $cat->getField('users_id');
                 }
                 if ((!isset($input['_groups_id_assign']) || !$input['_groups_id_assign']) && $cat->isField('groups_id')) {
                     $input['_groups_id_assign'] = $cat->getField('groups_id');
                 }
             }
             break;
         case Entity::AUTO_ASSIGN_CATEGORY_HARDWARE:
             // Auto assign tech/group from Category
             if ($input['itilcategories_id'] > 0 && (!isset($input['_users_id_assign']) || !$input['_users_id_assign'] || (!isset($input['_groups_id_assign']) || !$input['_groups_id_assign']))) {
                 $cat = new ITILCategory();
                 $cat->getFromDB($input['itilcategories_id']);
                 if ((!isset($input['_users_id_assign']) || !$input['_users_id_assign']) && $cat->isField('users_id')) {
                     $input['_users_id_assign'] = $cat->getField('users_id');
                 }
                 if ((!isset($input['_groups_id_assign']) || !$input['_groups_id_assign']) && $cat->isField('groups_id')) {
                     $input['_groups_id_assign'] = $cat->getField('groups_id');
                 }
             }
             if ($item != NULL) {
                 // Auto assign tech from item
                 if ((!isset($input['_users_id_assign']) || $input['_users_id_assign'] == 0) && $item->isField('users_id_tech')) {
                     $input['_users_id_assign'] = $item->getField('users_id_tech');
                 }
                 // Auto assign group from item
                 if ((!isset($input['_groups_id_assign']) || $input['_groups_id_assign'] == 0) && $item->isField('groups_id_tech')) {
                     $input['_groups_id_assign'] = $item->getField('groups_id_tech');
                 }
             }
             break;
     }
     // Replay setting auto assign if set in rules engine or by auto_assign_mode
     if ((isset($input["_users_id_assign"]) && $input["_users_id_assign"] > 0 || isset($input["_groups_id_assign"]) && $input["_groups_id_assign"] > 0 || isset($input["_suppliers_id_assign"]) && $input["_suppliers_id_assign"] > 0) && in_array($input['status'], $this->getNewStatusArray())) {
         $input["status"] = self::ASSIGNED;
     }
     //// Manage SLA assignment
     // Manual SLA defined : reset due date
     // No manual SLA and due date defined : reset auto SLA
     if ($manual_slas_id == 0 && isset($input["due_date"]) && $input['due_date'] != 'NULL') {
         // Valid due date
         if ($input['due_date'] >= $input['date']) {
             if (isset($input["slas_id"])) {
                 unset($input["slas_id"]);
             }
         } else {
             // Unset due date
             unset($input["due_date"]);
         }
     }
     if (isset($input["slas_id"]) && $input["slas_id"] > 0) {
         // Get datas to initialize SLA and set it
         $sla_data = $this->getDatasToAddSLA($input["slas_id"], $input['entities_id'], $input['date']);
         if (count($sla_data)) {
             foreach ($sla_data as $key => $val) {
                 $input[$key] = $val;
             }
         }
     }
     // auto set type if not set
     if (!isset($input["type"])) {
         $input['type'] = Entity::getUsedConfig('tickettype', $input['entities_id'], '', Ticket::INCIDENT_TYPE);
     }
     return $input;
 }
/**
 * Update from 0.84 to 0.84.1
 *
 * @return bool for success (will die for most error)
**/
function update084to0841()
{
    global $DB, $migration;
    $updateresult = true;
    $ADDTODISPLAYPREF = array();
    //TRANS: %s is the number of new version
    $migration->displayTitle(sprintf(__('Update to %s'), '0.84.1'));
    $migration->setVersion('0.84.1');
    $backup_tables = false;
    $newtables = array();
    foreach ($newtables as $new_table) {
        // rename new tables if exists ?
        if (TableExists($new_table)) {
            $migration->dropTable("backup_{$new_table}");
            $migration->displayWarning("{$new_table} table already exists. " . "A backup have been done to backup_{$new_table}.");
            $backup_tables = true;
            $query = $migration->renameTable("{$new_table}", "backup_{$new_table}");
        }
    }
    if ($backup_tables) {
        $migration->displayWarning("You can delete backup tables if you have no need of them.", true);
    }
    // Convert html fields from numeric encoding to raw encoding
    $fields_to_clean = array('glpi_knowbaseitems' => 'answer', 'glpi_tickets' => 'solution', 'glpi_problems' => 'solution', 'glpi_reminders' => 'text', 'glpi_solutiontemplates' => 'content', 'glpi_notificationtemplatetranslations' => 'content_text');
    foreach ($fields_to_clean as $table => $field) {
        foreach ($DB->request($table) as $data) {
            $text = Toolbox::unclean_html_cross_side_scripting_deep($data[$field]);
            $text = html_entity_decode($text, ENT_NOQUOTES, 'UTF-8');
            $text = addslashes($text);
            $text = Toolbox::clean_cross_side_scripting_deep($text);
            $query = "UPDATE `{$table}`\n                   SET `{$field}` = '{$text}'\n                   WHERE `id` = '" . $data['id'] . "';";
            $DB->queryOrDie($query, "0.84.1 fix encoding of html field : {$table}.{$field}");
        }
    }
    // Add date_mod to document_item
    $migration->addField('glpi_documents_items', 'date_mod', 'datetime');
    $migration->migrationOneTable('glpi_documents_items');
    $query_doc_i = "UPDATE `glpi_documents_items` as `doc_i`\n                   INNER JOIN `glpi_documents` as `doc`\n                     ON  `doc`.`id` = `doc_i`.`documents_id`\n                   SET `doc_i`.`date_mod` = `doc`.`date_mod`";
    $DB->queryOrDie($query_doc_i, "0.84.1 update date_mod in glpi_documents_items");
    // correct entities_id in documents_items
    $query_doc_i = "UPDATE `glpi_documents_items` as `doc_i`\n                   INNER JOIN `glpi_documents` as `doc`\n                     ON  `doc`.`id` = `doc_i`.`documents_id`\n                   SET `doc_i`.`entities_id` = `doc`.`entities_id`,\n                       `doc_i`.`is_recursive` = `doc`.`is_recursive`";
    $DB->queryOrDie($query_doc_i, "0.84.1 change entities_id in documents_items");
    // add delete_problem
    $migration->addField('glpi_profiles', 'delete_problem', 'char', array('after' => 'edit_all_problem', 'update' => 'edit_all_problem'));
    // ************ Keep it at the end **************
    //TRANS: %s is the table or item to migrate
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_displaypreferences'));
    foreach ($ADDTODISPLAYPREF as $type => $tab) {
        $query = "SELECT DISTINCT `users_id`\n                FROM `glpi_displaypreferences`\n                WHERE `itemtype` = '{$type}'";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                while ($data = $DB->fetch_assoc($result)) {
                    $query = "SELECT MAX(`rank`)\n                         FROM `glpi_displaypreferences`\n                         WHERE `users_id` = '" . $data['users_id'] . "'\n                               AND `itemtype` = '{$type}'";
                    $result = $DB->query($query);
                    $rank = $DB->result($result, 0, 0);
                    $rank++;
                    foreach ($tab as $newval) {
                        $query = "SELECT *\n                            FROM `glpi_displaypreferences`\n                            WHERE `users_id` = '" . $data['users_id'] . "'\n                                  AND `num` = '{$newval}'\n                                  AND `itemtype` = '{$type}'";
                        if ($result2 = $DB->query($query)) {
                            if ($DB->numrows($result2) == 0) {
                                $query = "INSERT INTO `glpi_displaypreferences`\n                                         (`itemtype` ,`num` ,`rank` ,`users_id`)\n                                  VALUES ('{$type}', '{$newval}', '" . $rank++ . "',\n                                          '" . $data['users_id'] . "')";
                                $DB->query($query);
                            }
                        }
                    }
                }
            } else {
                // Add for default user
                $rank = 1;
                foreach ($tab as $newval) {
                    $query = "INSERT INTO `glpi_displaypreferences`\n                                (`itemtype` ,`num` ,`rank` ,`users_id`)\n                         VALUES ('{$type}', '{$newval}', '" . $rank++ . "', '0')";
                    $DB->query($query);
                }
            }
        }
    }
    // must always be at the end
    $migration->executeMigration();
    return $updateresult;
}
 static function cleanArray($data)
 {
     foreach ($data as $key => $value) {
         //if (is_array($value)) {
         if ((array) $value === $value) {
             if (count($value) == 0) {
                 $value = '';
             } else {
                 $value = PluginFusioninventoryFormatconvert::cleanArray($value);
             }
         } else {
             if (strpos($value, "\\'")) {
                 $value = str_replace("\\'", "'", $value);
             }
             if (preg_match("/[^a-zA-Z0-9 \\-_\\(\\)]+/", $value)) {
                 $value = Toolbox::addslashes_deep($value);
             }
             $value = Toolbox::clean_cross_side_scripting_deep($value);
         }
         $data[$key] = $value;
     }
     return array_change_key_case($data, CASE_UPPER);
 }
Ejemplo n.º 24
0
 /** function textCleaner - Strip out unwanted/unprintable characters from the subject.
  *
  * @param $text text to clean
  *
  * @return clean text
  **/
 function textCleaner($text)
 {
     $text = str_replace("=20", "\n", $text);
     $text = Toolbox::clean_cross_side_scripting_deep($text);
     return $text;
 }
Ejemplo n.º 25
0
 /**
  * Show OcsLink of an item
  *
  * @param $item                   CommonDBTM object
  * @return nothing
  * @internal param int|string $withtemplate integer  withtemplate param (default '')
  */
 static function showForItem(CommonDBTM $item)
 {
     global $DB;
     $target = Toolbox::getItemTypeFormURL(__CLASS__);
     if (in_array($item->getType(), array('Computer'))) {
         $items_id = $item->getField('id');
         if (!empty($items_id) && $item->fields["is_dynamic"] && Session::haveRight("plugin_ocsinventoryng_view", READ)) {
             $query = "SELECT *\n                      FROM `glpi_plugin_ocsinventoryng_ocslinks`\n                      WHERE `computers_id` = '{$items_id}' " . getEntitiesRestrictRequest("AND", "glpi_plugin_ocsinventoryng_ocslinks");
             $result = $DB->query($query);
             if ($DB->numrows($result) > 0) {
                 $data = $DB->fetch_assoc($result);
                 $data = Toolbox::clean_cross_side_scripting_deep(Toolbox::addslashes_deep($data));
                 if (count($data)) {
                     echo "<div class='center'>";
                     echo "<form method='post' action=\"{$target}\">";
                     echo "<input type='hidden' name='id' value='{$items_id}'>";
                     echo "<table class='tab_cadre_fixe'>";
                     echo "<tr><th colspan = '4'>" . __('OCSNG link', 'ocsinventoryng') . "</th>";
                     echo "<tr class='tab_bg_1'>";
                     echo "<td class='left'>";
                     _e('OCSNG DEVICE ID', 'ocsinventoryng');
                     echo "</td>";
                     echo "<td class='left'>";
                     echo $data['ocs_deviceid'];
                     echo "</td>";
                     echo "<td class='left'>";
                     _e('OCSNG TAG', 'ocsinventoryng');
                     echo "</td>";
                     echo "<td class='left'>";
                     echo $data['tag'];
                     echo "</td>";
                     echo "<tr class='tab_bg_1'>";
                     echo "<td class='left'>" . __('Automatic update OCSNG', 'ocsinventoryng') . "</td>";
                     echo "<td class='left'>";
                     Dropdown::showYesNo("use_auto_update", $data["use_auto_update"]);
                     echo "</td>";
                     echo "<td class='left'>";
                     _e('Uptime', 'ocsinventoryng');
                     echo "</td>";
                     echo "<td class='left'>";
                     echo $data['uptime'];
                     echo "</td>";
                     echo "</tr>";
                     if (Session::haveRight("plugin_ocsinventoryng_sync", UPDATE)) {
                         echo "<tr class='tab_bg_1'>";
                         echo "<td class='center'>";
                         echo "<input type='hidden' name='link_id' value='" . $data["id"] . "'>";
                         echo "<input class=submit type='submit' name='update' value=\"" . _sx('button', 'Save') . "\">";
                         echo "</td>";
                         echo "<td class='center'>";
                         echo "<input type='hidden' name='resynch_id' value='" . $data["id"] . "'>";
                         echo "<input class=submit type='submit' name='force_ocs_resynch' value=\"" . _sx('button', 'Force synchronization', 'ocsinventoryng') . "\">";
                         echo "</td>";
                         echo "<td class='center'>";
                         echo "<input type='hidden' name='items_id' value='" . $items_id . "'>";
                         echo "<input class=submit type='submit' name='delete_link' value=\"" . _sx('button', 'Delete link', 'ocsinventoryng') . "\">";
                         echo "</td>";
                         echo "<td>";
                         echo "</td>";
                         echo "</tr>";
                     }
                     echo "</table>\n";
                     Html::closeForm();
                     echo "</div>";
                     if ($_SESSION['glpi_use_mode'] == Session::DEBUG_MODE) {
                         $ocsClient = PluginOcsinventoryngOcsServer::getDBocs($data["plugin_ocsinventoryng_ocsservers_id"]);
                         $options = array('DISPLAY' => array('CHECKSUM' => PluginOcsinventoryngOcsClient::CHECKSUM_HARDWARE, 'PLUGINS' => PluginOcsinventoryngOcsClient::PLUGINS_NONE), 'COMPLETE' => 0);
                         $computer = array();
                         $checksum_client = 0;
                         $computer = $ocsClient->getComputer($data["ocsid"], $options);
                         echo "<br><table class='tab_cadre_fixe'>";
                         echo "<tr>";
                         echo "<th colspan='2'>" . __('DEBUG') . " " . __('OCSNG', "ocsinventoryng") . "</th>";
                         echo "</tr>";
                         if (count($computer) > 0) {
                             foreach ($computer as $key => $val) {
                                 echo "<tr class='tab_bg_1'>";
                                 echo "<td>";
                                 print_r($key);
                                 echo "</td>";
                                 echo "<td>";
                                 foreach ($val as $name => $value) {
                                     if (is_array($value)) {
                                         echo "<table class='tab_cadre' width='100%' border='0'>";
                                         foreach ($value as $k => $v) {
                                             echo "<tr class='tab_bg_1'>";
                                             echo "<td>";
                                             printf(__('%1$s: %2$s'), $k, $v);
                                             echo "</td>";
                                             echo "</tr>";
                                         }
                                         echo "</table>";
                                     } else {
                                         printf(__('%1$s: %2$s'), $name, $value);
                                     }
                                     if ($name == "CHECKSUM") {
                                         $checksum_client = intval($value);
                                     }
                                     echo "</br>";
                                 }
                                 echo "</td>";
                                 echo "</tr>";
                             }
                         } else {
                             echo "<tr class='tab_bg_1'>";
                             echo "<td colspan='2' class='red'>";
                             _e('No computer found into OCSNG Database', 'ocsinventoryng');
                             echo "</td>";
                             echo "</tr>";
                         }
                         $server = new PluginOcsinventoryngOcsServer();
                         if ($server->getFromDB($data["plugin_ocsinventoryng_ocsservers_id"]) && $checksum_client > 0) {
                             echo "<tr class='tab_bg_1'>";
                             echo "<td>";
                             _e('Checksum test', 'ocsinventoryng');
                             echo "</td>";
                             echo "<td>";
                             $format = '(%1$2d = %1$04b) = (%2$2d = %2$04b)' . ' %3$s (%4$2d = %4$04b)' . "\n";
                             $checksum_server = intval($server->fields["checksum"]);
                             $result = $checksum_server & $checksum_client;
                             printf($format, $result, $checksum_server, '&', $checksum_client);
                             echo "</td>";
                             echo "</tr>";
                         }
                         echo "</table>";
                     }
                 } else {
                     echo "<div class='center'>";
                     echo "<table class='tab_cadre_fixe'>";
                     echo "<tr><th colspan = '2'>" . __('OCSNG link', 'ocsinventoryng') . "</th>";
                     echo "<tr class='tab_bg_1'>";
                     echo "<td colspan='2' >";
                     _e('No computer found into OCSNG Database', 'ocsinventoryng');
                     echo "</td>";
                     echo "</tr>";
                     echo "</table>";
                     echo "</div>";
                 }
             } else {
                 echo "<div class='center'>";
                 echo "<table class='tab_cadre_fixe'>";
                 echo "<tr><th colspan = '2'>" . __('OCSNG link', 'ocsinventoryng') . "</th>";
                 echo "<tr class='tab_bg_1'>";
                 echo "<td colspan='2' '>";
                 _e('No computer found into OCSNG Database', 'ocsinventoryng');
                 echo "</td>";
                 echo "</tr>";
                 echo "</table>";
                 echo "</div>";
             }
         } else {
             echo "<div class='center'>";
             echo "<table class='tab_cadre_fixe'>";
             echo "<tr><th colspan = '2'>" . __('OCSNG link', 'ocsinventoryng') . "</th>";
             echo "<tr class='tab_bg_1'>";
             echo "<td colspan='2' '>";
             _e('No computer found into OCSNG Database', 'ocsinventoryng');
             echo "</td>";
             echo "</tr>";
             echo "</table>";
             echo "</div>";
         }
     }
 }