static function getPeriodTime(CommonGLPI $ticket, $start, $end) { $totaltime = 0; if ($ticket->fields['slas_id'] != 0) { // Have SLA $sla = new SLA(); $sla->getFromDB($ticket->fields['slas_id']); $totaltime = $sla->getActiveTimeBetween($start, $end); } else { $calendars_id = Entity::getUsedConfig('calendars_id', $ticket->fields['entities_id']); if ($calendars_id != 0) { // Ticket entity have calendar $calendar = new Calendar(); $calendar->getFromDB($calendars_id); $totaltime = $calendar->getActiveTimeBetween($start, $end); } else { // No calendar $totaltime = strtotime($end) - strtotime($start); } } return $totaltime; }
function generateTimeperiodsCfg($file = 0, $tag = '') { global $DB; PluginMonitoringToolbox::logIfExtradebug('pm-shinken', "Starting generateTimeperiodsCfg ...\n"); $calendar = new Calendar(); $calendarSegment = new CalendarSegment(); $calendar_Holiday = new Calendar_Holiday(); $holiday = new Holiday(); $hostconfig = new PluginMonitoringHostconfig(); $pmEntity = new PluginMonitoringEntity(); // Get list of entities $a_entities_allowed = $pmEntity->getEntitiesByTag($tag); $a_entities_list = array(); foreach ($a_entities_allowed as $entity) { $a_entities_list = getSonsOf("glpi_entities", $entity); } $where = ''; if (!isset($a_entities_allowed['-1'])) { $where = getEntitiesRestrictRequest("WHERE", "glpi_entities", '', $a_entities_list); } foreach ($a_entities_list as $entities_id) { $jetlag = $hostconfig->getValueAncestor('jetlag', $entities_id); $a_entities_list[$entities_id] = $jetlag; } // Get all calendars of components $cals_entities = array(); $query = "SELECT `entities_id`, `calendars_id`\n FROM `glpi_plugin_monitoring_services`\n LEFT JOIN `glpi_plugin_monitoring_components`\n ON `plugin_monitoring_components_id` = `glpi_plugin_monitoring_components`.`id` "; if ($where == '') { $query .= "WHERE `glpi_plugin_monitoring_components`.`id` IS NOT NULL"; } else { $query .= $where . " AND `glpi_plugin_monitoring_components`.`id` IS NOT NULL"; } $result = $DB->query($query); while ($data = $DB->fetch_array($result)) { if (!isset($cals_entities[$data['entities_id']])) { $cals_entities[$data['entities_id']] = array(); } $cals_entities[$data['entities_id']][$data['calendars_id']] = $data['calendars_id']; } // get all calendars of servciescatalog $query = "SELECT `entities_id`, `calendars_id`\n FROM `glpi_plugin_monitoring_servicescatalogs` " . $where; $result = $DB->query($query); while ($data = $DB->fetch_array($result)) { if (!isset($cals_entities[$data['entities_id']])) { $cals_entities[$data['entities_id']] = array(); } $cals_entities[$data['entities_id']][$data['calendars_id']] = $data['calendars_id']; } // Get all calendars of contacts TODO $calendars_added = array(); $a_timeperiods = array(); $i = 0; foreach ($cals_entities as $entities_id => $calendars) { foreach ($calendars as $calendars_id) { $jetlag = $a_entities_list[$entities_id]; if (!isset($calendars_added[$calendars_id . "-" . $jetlag])) { $calendars_added[$calendars_id . "-" . $jetlag] = 1; $calendar->getFromDB($calendars_id); $tmp = array(); $tmp['timeperiod_name'] = $calendar->fields['name']; $tmp['alias'] = $calendar->fields['name']; $a_listsegment = $calendarSegment->find("`calendars_id`='" . $calendar->fields['id'] . "'"); $a_cal = array(); foreach ($a_listsegment as $datasegment) { $begin = preg_replace("/:00\$/", "", $datasegment['begin']); $end = preg_replace("/:00\$/", "", $datasegment['end']); $day = ""; switch ($datasegment['day']) { case "0": $day = "sunday"; break; case "1": $day = "monday"; break; case "2": $day = "tuesday"; break; case "3": $day = "wednesday"; break; case "4": $day = "thursday"; break; case "5": $day = "friday"; break; case "6": $day = "saturday"; break; } $a_cal[$day][] = $begin . "-" . $end; } foreach ($a_cal as $day => $a_times) { $tmp[$day] = implode(',', $a_times); } $a_cholidays = $calendar_Holiday->find("`calendars_id`='" . $calendar->fields['id'] . "'"); foreach ($a_cholidays as $a_choliday) { $holiday->getFromDB($a_choliday['holidays_id']); if ($holiday->fields['is_perpetual'] == 1 && $holiday->fields['begin_date'] == $holiday->fields['end_date']) { $datetime = strtotime($holiday->fields['begin_date']); $tmp[strtolower(date('F', $datetime)) . ' ' . date('j', $datetime)] = '00:00-00:00'; } } if ($jetlag == 0) { $tmp['timeperiod_name'] = $tmp['timeperiod_name']; $tmp['alias'] = $tmp['alias']; } else { $tmp['timeperiod_name'] = $tmp['timeperiod_name'] . "-" . $jetlag; $tmp['alias'] = $tmp['alias'] . "-" . $jetlag; } $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'); $saturday = ''; $reportHours = 0; $beforeday = 'saturday'; foreach ($days as $numday => $day) { if (isset($tmp[$day])) { $splitDay = explode(',', $tmp[$day]); $toAdd = ''; if ($reportHours > 0) { $toAdd = '00:00-' . sprintf("%02s", $reportHours) . ':00'; $reportHours = 0; } foreach ($splitDay as $num => $hourMinute) { $previous_begin = 0; $beginEnd = explode('-', $hourMinute); // ** Begin ** $split = explode(':', $beginEnd[0]); $split[0] += $jetlag; if ($split[0] > 24) { //$reportHours = $split[0] - 24; unset($splitDay[$num]); } else { if ($split[0] < 0) { $reportHours = $split[0]; $previous_begin = 24 + $split[0]; $split[0] = '00'; } $beginEnd[0] = sprintf("%02s", $split[0]) . ':' . $split[1]; // ** End ** $split = explode(':', $beginEnd[1]); $split[0] += $jetlag; if ($split[0] < 0) { if ($numday - 1 == -1) { $saturday .= "," . sprintf("%02s", $previous_begin) . ":00-" . sprintf("%02s", 24 + $split[0]) . ":00"; } else { $tmp[$days[$numday - 1]] .= "," . sprintf("%02s", $previous_begin) . ":00-" . sprintf("%02s", 24 + $split[0]) . ":00"; } unset($splitDay[$num]); } else { if ($split[0] > 24) { $reportHours = $split[0] - 24; $split[0] = 24; } $beginEnd[1] = sprintf("%02s", $split[0]) . ':' . $split[1]; $hourMinute = implode('-', $beginEnd); $splitDay[$num] = $hourMinute; } } } if ($reportHours < 0) { // if (!isset($tmp[$beforeday])) { // $tmp[$beforeday] = array(); // } // $splitBeforeDay = explode(',', $tmp[$beforeday]); // $splitBeforeDay[] = sprintf("%02s", (24 + $reportHours)).':00-24:00'; // $tmp[$beforeday] = implode(',', $splitBeforeDay); $reportHours = 0; } if (!empty($toAdd)) { array_unshift($splitDay, $toAdd); } $tmp[$day] = implode(',', $splitDay); } else { if ($reportHours > 0) { //$tmp[$day] = '00:00-'.$reportHours.':00'; $reportHours = 0; } } $beforeday = $day; } // Manage for report hours from saturday to sunday if ($reportHours > 0) { $splitDay = explode(',', $tmp['sunday']); array_unshift($splitDay, '00:00-' . sprintf("%02s", $reportHours) . ':00'); $tmp['sunday'] = implode(',', $splitDay); } if ($saturday != '') { if (isset($tmp['saturday'])) { $tmp['saturday'] .= $saturday; } else { $tmp['saturday'] = $saturday; } } // concatain if need foreach ($days as $day) { if (isset($tmp[$day])) { $splitDay = explode(',', $tmp[$day]); $beforeHour = ''; $beforeNum = 0; foreach ($splitDay as $num => $data) { if (substr($data, 0, 2) == $beforeHour) { $splitDay[$beforeNum] = substr($splitDay[$beforeNum], 0, 6) . substr($data, 6, 5); $beforeHour = substr($data, 6, 2); unset($splitDay[$num]); } else { $beforeHour = substr($data, 6, 2); $beforeNum = $num; } } $tmp[$day] = implode(',', $splitDay); } } $a_timeperiods[$i] = $tmp; $i++; } } } PluginMonitoringToolbox::logIfExtradebug('pm-shinken', "End generateTimeperiodsCfg\n"); if ($file == "1") { $config = "# Generated by plugin monitoring for GLPI\n# on " . date("Y-m-d H:i:s") . "\n\n"; foreach ($a_timeperiods as $data) { $config .= $this->writeFile("timeperiod", $data); } return array('timeperiods.cfg', $config); } else { return $a_timeperiods; } }
/** * * @param $items_id integer ID * @param $options array * *@return bool true if form is ok * **/ function showForm($items_id, $itemtype, $options = array()) { global $DB, $CFG_GLPI; $pmCommand = new PluginMonitoringCommand(); $pmCheck = new PluginMonitoringCheck(); $calendar = new Calendar(); $pmRealm = new PluginMonitoringRealm(); $entities_id = 0; if ($itemtype == "Entity") { $entities_id = $items_id; } else { $item = new $itemtype(); $item->getFromDB($items_id); $entities_id = $item->fields['entities_id']; } $query = "SELECT * FROM `" . $this->getTable() . "`\n WHERE `items_id`='" . $items_id . "'\n AND `itemtype`='" . $itemtype . "'\n LIMIT 1"; $result = $DB->query($query); if ($DB->numrows($result) == '0') { $this->getEmpty(); if ($entities_id != '0' or $itemtype != 'Entity') { $this->fields['plugin_monitoring_commands_id'] = -1; $this->fields['plugin_monitoring_checks_id'] = -1; $this->fields['calendars_id'] = -1; $this->fields['plugin_monitoring_realms_id'] = -1; } } else { $data = $DB->fetch_assoc($result); $this->getFromDB($data['id']); } echo "<form name='form' method='post' \n action='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/hostconfig.form.php'>"; echo "<table class='tab_cadre_fixe'"; echo "<tr class='tab_bg_1'>"; echo "<th colspan='4'>"; echo __('Hosts configuration', 'monitoring'); echo "</th>"; echo "</tr>"; echo "<tr class='tab_bg_1'>"; echo "<td>"; echo __('Command', 'monitoring') . " :"; echo "</td>"; echo "<td>"; $input = array(); if ($entities_id != '0' or $itemtype != 'Entity') { $input["-1"] = __('Inheritance of the parent entity'); } $query = "SELECT * FROM `" . getTableForItemType("PluginMonitoringCommand") . "`\n ORDER BY `name`"; $result = $DB->query($query); while ($data = $DB->fetch_array($result)) { $input[$data['id']] = $data['name']; } Dropdown::showFromArray('plugin_monitoring_commands_id', $input, array('value' => $this->fields['plugin_monitoring_commands_id'])); echo "</td>"; echo "<td>" . __('Check definition', 'monitoring') . " :</td>"; echo "<td>"; $input = array(); if ($entities_id != '0' or $itemtype != 'Entity') { $input["-1"] = __('Inheritance of the parent entity'); } $query = "SELECT * FROM `" . getTableForItemType("PluginMonitoringCheck") . "`\n ORDER BY `name`"; $result = $DB->query($query); while ($data = $DB->fetch_array($result)) { $input[$data['id']] = $data['name']; } Dropdown::showFromArray('plugin_monitoring_checks_id', $input, array('value' => $this->fields['plugin_monitoring_checks_id'])); echo "</td>"; echo "</tr>"; // Inheritance if ($this->fields['plugin_monitoring_commands_id'] == '-1' or $this->fields['plugin_monitoring_checks_id'] == '-1') { echo "<tr class='tab_bg_1'>"; if ($this->fields['plugin_monitoring_commands_id'] == '-1') { echo "<td colspan='2' class='green center'>"; echo __('Inheritance of the parent entity') . " : "; $pmCommand->getFromDB($this->getValueAncestor("plugin_monitoring_commands_id", $entities_id)); echo $pmCommand->fields['name']; echo "</td>"; } else { echo "<td colspan='2'>"; echo "</td>"; } if ($this->fields['plugin_monitoring_checks_id'] == '-1') { echo "<td colspan='2' class='green center'>"; echo __('Inheritance of the parent entity') . " : "; $pmCheck->getFromDB($this->getValueAncestor("plugin_monitoring_checks_id", $entities_id)); echo $pmCheck->fields['name']; echo "</td>"; } else { echo "<td colspan='2'>"; echo "</td>"; } echo "</tr>"; } echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Reaml', 'monitoring') . " :</td>"; echo "<td>"; $input = array(); if ($entities_id != '0' or $itemtype != 'Entity') { $input["-1"] = __('Inheritance of the parent entity'); } $query = "SELECT * FROM `" . getTableForItemType("PluginMonitoringRealm") . "`\n ORDER BY `name`"; $result = $DB->query($query); while ($data = $DB->fetch_array($result)) { $input[$data['id']] = $data['name']; } Dropdown::showFromArray('plugin_monitoring_realms_id', $input, array('value' => $this->fields['plugin_monitoring_realms_id'])); echo "</td>"; echo "<td>" . __('Check period', 'monitoring') . " :</td>"; echo "<td>"; if (Session::isMultiEntitiesMode()) { $input = array(); if ($entities_id != '0' or $itemtype != 'Entity') { $input["-1"] = __('Inheritance of the parent entity'); } $entities_ancestors = getAncestorsOf("glpi_entities", $entities_id); if (!isset($entities_ancestors[$entities_id])) { $entities_ancestors[$entities_id] = $entities_id; } $query = "SELECT * FROM `" . getTableForItemType("Calendar") . "`\n WHERE `entities_id` IN ('" . implode(",", $entities_ancestors) . "') AND `is_recursive`='1'\n ORDER BY `name`"; $result = $DB->query($query); while ($data = $DB->fetch_array($result)) { $input[$data['id']] = $data['name']; } Dropdown::showFromArray('calendars_id', $input, array('value' => $this->fields['calendars_id'])); } else { Dropdown::show("Calendar", array('value' => $this->fields['calendars_id'])); } echo "</td>"; echo "</tr>"; // Inheritance if ($this->fields['calendars_id'] == '-1' or $this->fields['plugin_monitoring_realms_id'] == '-1') { echo "<tr class='tab_bg_1'>"; if ($this->fields['plugin_monitoring_realms_id'] == '-1') { echo "<td colspan='2' class='green center'>"; echo __('Inheritance of the parent entity') . " : "; $pmRealm->getFromDB($this->getValueAncestor("plugin_monitoring_realms_id", $entities_id)); echo $pmRealm->fields['name']; echo "</td>"; } else { echo "<td colspan='2'>"; echo "</td>"; } if ($this->fields['calendars_id'] == '-1') { echo "<td colspan='2' class='green center'>"; echo __('Inheritance of the parent entity') . " : "; $calendar->getFromDB($this->getValueAncestor("calendars_id", $entities_id)); echo $calendar->fields['name']; echo "</td>"; } else { echo "<td colspan='2'>"; echo "</td>"; } echo "</tr>"; } if ($itemtype == 'Entity' and $items_id == '0') { echo "<tr class='tab_bg_1'>"; echo "<td>"; echo __('Shinken Server', 'monitoring') . " :"; echo "</td>"; echo "<td>"; Dropdown::show("Computer", array('name' => 'computers_id', 'value' => $this->fields['computers_id'])); echo "</td>"; echo "<td colspan='2'></td>"; echo "</tr>"; } echo "<tr class='tab_bg_1'>"; echo "<td colspan='4' align='center'>"; if (isset($this->fields['id']) and $this->fields['id'] != '') { echo "<input type='hidden' name='id' value='" . $this->fields['id'] . "'/>"; } echo "<input type='hidden' name='itemtype' value='" . $itemtype . "'/>"; echo "<input type='hidden' name='items_id' value='" . $items_id . "'/>"; echo "<input type='submit' name='update' value=\"" . __('Save') . "\" class='submit'>"; echo "</td>"; echo "</tr>"; echo "</table>"; Html::closeForm(); return true; }
/** * Compute take into account stat of the current ticket **/ function computeTakeIntoAccountDelayStat() { if (isset($this->fields['id']) && !empty($this->fields['date'])) { $calendars_id = $this->getCalendar(); $calendar = new Calendar(); // Using calendar if ($calendars_id > 0 && $calendar->getFromDB($calendars_id)) { return max(1, $calendar->getActiveTimeBetween($this->fields['date'], $_SESSION["glpi_currenttime"])); } // Not calendar defined return max(1, strtotime($_SESSION["glpi_currenttime"]) - strtotime($this->fields['date'])); } return 0; }
/** * Compute close delay stat of the current ticket **/ function computeCloseDelayStat() { if (isset($this->fields['id']) && !empty($this->fields['date']) && !empty($this->fields['closedate'])) { $calendars_id = Entity::getUsedConfig('calendars_id', $this->fields['entities_id']); $calendar = new Calendar(); // Using calendar if ($calendars_id > 0 && $calendar->getFromDB($calendars_id)) { return max(0, $calendar->getActiveTimeBetween($this->fields['date'], $this->fields['closedate']) - $this->fields["waiting_duration"]); } // Not calendar defined return max(0, strtotime($this->fields['closedate']) - strtotime($this->fields['date']) - $this->fields["waiting_duration"]); } return 0; }
function showForm($items_id, $options=array(), $services_id='') { $pMonitoringCommand = new PluginMonitoringCommand(); $pMonitoringServicedef = new PluginMonitoringServicedef(); if (isset($_GET['withtemplate']) AND ($_GET['withtemplate'] == '1')) { $options['withtemplate'] = 1; } else { $options['withtemplate'] = 0; } if ($services_id!='') { $this->getEmpty(); } else { $this->getFromDB($items_id); } $this->showTabs($options); $this->showFormHeader($options); if (!isset($this->fields['plugin_monitoring_servicedefs_id']) OR empty($this->fields['plugin_monitoring_servicedefs_id'])) { $pMonitoringServicedef->getEmpty(); } else { $pMonitoringServicedef->getFromDB($this->fields['plugin_monitoring_servicedefs_id']); } $template = false; echo "<tr>"; echo "<td>"; if ($services_id!='') { echo "<input type='hidden' name='plugin_monitoring_services_id' value='".$services_id."' />"; } echo __('Name')." :"; echo "</td>"; echo "<td>"; $objectName = autoName($this->fields["name"], "name", ($template === "newcomp"), $this->getType()); Html::autocompletionTextField($this, 'name', array('value' => $objectName)); echo "</td>"; echo "<td>"; echo __('Template')." :"; echo "</td>"; echo "<td>"; if ($items_id != '0') { echo "<input type='hidden' name='update' value='update'>\n"; } echo "<input type='hidden' name='plugin_monitoring_servicedefs_id_s' value='".$this->fields['plugin_monitoring_servicedefs_id']."'>\n"; if ($pMonitoringServicedef->fields['is_template'] == '0') { $this->fields['plugin_monitoring_servicedefs_id'] = 0; } Dropdown::show("PluginMonitoringServicetemplate", array( 'name' => 'plugin_monitoring_servicetemplates_id', 'value' => $this->fields['plugin_monitoring_servicetemplates_id'], 'auto_submit' => true )); echo "</td>"; echo "<td>"; if ($this->fields["items_id"] == '') { } else { echo "<input type='hidden' name='items_id' value='".$this->fields["items_id"]."'>\n"; echo "<input type='hidden' name='itemtype' value='".$this->fields["itemtype"]."'>\n"; } echo "</td>"; echo "</tr>"; echo "<tr>"; echo "<th colspan='4'> </th>"; echo "</tr>"; echo "<tr>"; // * itemtype link if ($this->fields['itemtype'] != '') { $itemtype = $this->fields['itemtype']; $item = new $itemtype(); $item->getFromDB($this->fields['items_id']); echo "<td>"; echo __('Item Type')." <i>".$item->getTypeName()."</i>"; echo " :</td>"; echo "<td>"; echo $item->getLink(1); echo "</td>"; } else { echo "<td colspan='2' align='center'>"; echo __('No type associated', 'monitoring'); echo "</td>"; } // * command echo "<td>"; echo __('Command', 'monitoring')." :"; echo "</td>"; echo "<td align='center'>"; if ($this->fields['plugin_monitoring_servicetemplates_id'] > 0) { $pMonitoringServicetemplate = new PluginMonitoringServicetemplate(); $pMonitoringServicetemplate->getFromDB($this->fields['plugin_monitoring_servicetemplates_id']); $pMonitoringCommand->getFromDB($pMonitoringServicetemplate->fields['plugin_monitoring_commands_id']); echo $pMonitoringCommand->getLink(1); } else { $pMonitoringCommand->getFromDB($pMonitoringServicedef->fields['plugin_monitoring_commands_id']); Dropdown::show("PluginMonitoringCommand", array( 'name' =>'plugin_monitoring_commands_id', 'value'=>$pMonitoringServicedef->fields['plugin_monitoring_commands_id'] )); } echo "</td>"; echo "</tr>"; echo "<tr>"; // * checks echo "<td>".__('Check definition', 'monitoring')." :</td>"; echo "<td align='center'>"; if ($this->fields['plugin_monitoring_servicetemplates_id'] > 0) { $pMonitoringCheck = new PluginMonitoringCheck(); $pMonitoringCheck->getFromDB($pMonitoringServicetemplate->fields['plugin_monitoring_checks_id']); echo $pMonitoringCheck->getLink(1); } else { Dropdown::show("PluginMonitoringCheck", array('name'=>'plugin_monitoring_checks_id', 'value'=>$pMonitoringServicedef->fields['plugin_monitoring_checks_id'])); } echo "</td>"; // * active check echo "<td>"; echo __('Active check', 'monitoring')." :"; echo "</td>"; echo "<td align='center'>"; if ($this->fields['plugin_monitoring_servicetemplates_id'] > 0) { echo Dropdown::getYesNo($pMonitoringServicetemplate->fields['active_checks_enabled']); } else { Dropdown::showYesNo("active_checks_enabled", $pMonitoringServicedef->fields['active_checks_enabled']); } echo "</td>"; echo "</tr>"; echo "<tr>"; // * passive check echo "<td>"; echo __('Passive check', 'monitoring')." :"; echo "</td>"; echo "<td align='center'>"; if ($this->fields['plugin_monitoring_servicetemplates_id'] > 0) { echo Dropdown::getYesNo($pMonitoringServicetemplate->fields['passive_checks_enabled']); } else { Dropdown::showYesNo("passive_checks_enabled", $pMonitoringServicedef->fields['passive_checks_enabled']); } echo "</td>"; // * calendar echo "<td>".__('Check period', 'monitoring')." :</td>"; echo "<td align='center'>"; if ($this->fields['plugin_monitoring_servicetemplates_id'] > 0) { $calendar = new Calendar(); $calendar->getFromDB($pMonitoringServicetemplate->fields['calendars_id']); echo $calendar->getLink(1); } else { dropdown::show("Calendar", array('name'=>'calendars_id', 'value'=>$pMonitoringServicedef->fields['calendars_id'])); } echo "</td>"; echo "</tr>"; if (!($this->fields['plugin_monitoring_servicetemplates_id'] > 0 AND $pMonitoringServicetemplate->fields['remotesystem'] == '')) { echo "<tr>"; echo "<th colspan='4'>".__('Remote check', 'monitoring')."</th>"; echo "</tr>"; echo "<tr>"; // * remotesystem echo "<td>"; echo __('Utility used for remote check', 'monitoring')." :"; echo "</td>"; echo "<td>"; $input = array(); $input[''] = '------'; $input['byssh'] = 'byssh'; $input['nrpe'] = 'nrpe'; $input['nsca'] = 'nsca'; if ($this->fields['plugin_monitoring_servicetemplates_id'] > 0) { echo $input[$pMonitoringServicetemplate->fields['remotesystem']]; } else { Dropdown::showFromArray("remotesystem", $input, array('value'=>$pMonitoringServicedef->fields['remotesystem'])); } echo "</td>"; // * is_argument echo "<td>"; echo __('Use arguments (NRPE only)', 'monitoring')." :"; echo "</td>"; echo "<td>"; if ($this->fields['plugin_monitoring_servicetemplates_id'] > 0) { echo Dropdown::getYesNo($pMonitoringServicetemplate->fields['is_arguments']); } else { Dropdown::showYesNo("is_arguments", $pMonitoringServicedef->fields['is_arguments']); } echo "</td>"; echo "</tr>"; echo "<tr>"; // alias command echo "<td>"; echo __('Alias command if required (NRPE only)', 'monitoring')." :"; echo "</td>"; echo "<td>"; if ($this->fields['plugin_monitoring_servicetemplates_id'] > 0) { echo "<input type='text' name='alias_commandservice' value='".$this->fields['alias_command']."' />"; } else { echo "<input type='text' name='alias_command' value='".$pMonitoringServicedef->fields['alias_command']."' />"; } echo "</td>"; echo "<td>"; echo __('Template (for graphs generation)', 'monitoring')." :GHJKL"; echo "</td>"; echo "<td>"; if ($this->fields['plugin_monitoring_servicetemplates_id'] > 0) { $pMonitoringCommand->getEmpty(); $pMonitoringCommand->getFromDB($pMonitoringServicetemplate->fields['aliasperfdata_commands_id']); echo $pMonitoringCommand->getLink(1); } else { $pMonitoringCommand->getFromDB($pMonitoringServicedef->fields['aliasperfdata_commands_id']); Dropdown::show("PluginMonitoringCommand", array( 'name' =>'aliasperfdata_commands_id', 'value'=>$pMonitoringServicedef->fields['aliasperfdata_commands_id'] )); } echo "</td>"; echo "</tr>"; } // * Manage arguments $array = array(); $a_displayarg = array(); if (isset($pMonitoringCommand->fields['command_line'])) { preg_match_all("/\\$(ARG\d+)\\$/", $pMonitoringCommand->fields['command_line'], $array); $a_arguments = importArrayFromDB($this->fields['arguments']); foreach ($array[0] as $arg) { if (strstr($arg, "ARG")) { $arg = str_replace('$', '', $arg); if (!isset($a_arguments[$arg])) { $a_arguments[$arg] = ''; } $a_displayarg[$arg] = $a_arguments[$arg]; } } } if (count($a_displayarg) > 0) { $a_argtext = importArrayFromDB($pMonitoringCommand->fields['arguments']); echo "<tr>"; echo "<th colspan='4'>".__('Argument ([text:text] is used to get values dynamically)', 'monitoring')." </th>"; echo "</tr>"; foreach ($a_displayarg as $key=>$value) { echo "<tr>"; echo "<th>".$key."</th>"; echo "<td colspan='2'>"; if (isset($a_argtext[$key])) { echo nl2br($a_argtext[$key])." :"; } else { echo __('Argument', 'monitoring')." :"; } if ($value == '') { $matches = array(); preg_match('/(\[\w+\:\w+\])/', nl2br($a_argtext[$key]), $matches); if (isset($matches[0])) { $value = $matches[0]; } } echo "</td>"; echo "<td>"; echo "<input type='text' name='arg[".$key."]' value='".$value."'/><br/>"; echo "</td>"; echo "</tr>"; } } $this->showFormButtons($options); return true; }
/** * Get active time between to date time for the active calendar * * @param $start datetime begin * @param $end datetime end * * @return timestamp of delay **/ function getActiveTimeBetween($start, $end) { if ($end < $start) { return 0; } if (isset($this->fields['id'])) { $cal = new Calendar(); $work_in_days = $this->fields['definition_time'] == 'day'; // Based on a calendar if ($this->fields['calendars_id'] > 0) { if ($cal->getFromDB($this->fields['calendars_id'])) { return $cal->getActiveTimeBetween($start, $end, $work_in_days); } } else { // No calendar $timestart = strtotime($start); $timeend = strtotime($end); return $timeend - $timestart; } } return 0; }
function showTimeline(Ticket $ticket, $params = array()) { global $DB, $CFG_GLPI; /* Create and populate the pData object */ $MyData = new pData(); /* Create the pChart object */ $myPicture = new pImage(820, 29, $MyData); /* Create the pIndicator object */ $Indicator = new pIndicator($myPicture); $myPicture->setFontProperties(array("FontName" => GLPI_ROOT . "/plugins/timelineticket/lib/pChart2.1.4/fonts/pf_arma_five.ttf", "FontSize" => 6)); /* Define the indicator sections */ $IndicatorSections = array(); $a_states = array(Ticket::INCOMING, Ticket::ASSIGNED, Ticket::PLANNED, Ticket::WAITING, Ticket::SOLVED, Ticket::CLOSED); $a_status_color = array(); $a_status_color[Ticket::INCOMING] = array('R' => 197, 'G' => 204, 'B' => 79); $a_status_color[Ticket::ASSIGNED] = array('R' => 38, 'G' => 174, 'B' => 38); $a_status_color[Ticket::PLANNED] = array('R' => 255, 'G' => 102, 'B' => 0); $a_status_color[Ticket::WAITING] = array('R' => 229, 'G' => 184, 'B' => 0); $a_status_color[Ticket::SOLVED] = array('R' => 83, 'G' => 141, 'B' => 184); $a_status_color[Ticket::CLOSED] = array('R' => 51, 'G' => 51, 'B' => 51); $delaystatus = array(); foreach ($a_states as $status) { $IndicatorSections[$status] = ''; $delaystatus[$status] = 0; } $a_status = $this->find("`tickets_id`='" . $ticket->getField('id') . "'", "`date`"); $begin = 0; if ($params['totaltime'] > 0) { foreach ($a_status as $data) { foreach ($a_states as $statusSection) { $R = 235; $G = 235; $B = 235; $caption = ''; if ($statusSection == $data['old_status']) { $R = $a_status_color[$statusSection]['R']; $G = $a_status_color[$statusSection]['G']; $B = $a_status_color[$statusSection]['B']; //$caption = $status; $delaystatus[$statusSection] += round($data['delay'] * 100 / $params['totaltime'], 2); } $IndicatorSections[$statusSection][] = array("Start" => $begin, "End" => $begin + $data['delay'], "Caption" => $caption, "R" => $R, "G" => $G, "B" => $B); } $begin += $data['delay']; } if ($ticket->fields['status'] != Ticket::CLOSED) { foreach ($a_states as $statusSection) { $R = 235; $G = 235; $B = 235; $caption = ' '; if ($statusSection == $ticket->fields['status']) { $R = $a_status_color[$statusSection]['R']; $G = $a_status_color[$statusSection]['G']; $B = $a_status_color[$statusSection]['B']; //$caption = $status; $delaystatus[$statusSection] += round(($params['totaltime'] - $begin) * 100 / $params['totaltime'], 2); } $IndicatorSections[$statusSection][] = array("Start" => $begin, "End" => $begin + ($params['totaltime'] - $begin), "Caption" => $caption, "R" => $R, "G" => $G, "B" => $B); } } } if (count($a_status) > 1) { foreach ($a_states as $status) { echo "<tr class='tab_bg_2'>"; echo "<td width='100'>"; echo Ticket::getStatus($status); echo "<br/>(" . $delaystatus[$status] . "%)"; echo "</td>"; echo "<td>"; if ($ticket->fields['status'] != Ticket::CLOSED) { $IndicatorSettings = array("Values" => array(100, 201), "CaptionPosition" => INDICATOR_CAPTION_BOTTOM, "CaptionLayout" => INDICATOR_CAPTION_DEFAULT, "CaptionR" => 0, "CaptionG" => 0, "CaptionB" => 0, "DrawLeftHead" => FALSE, "ValueDisplay" => false, "IndicatorSections" => $IndicatorSections[$status], "SectionsMargin" => 0); $Indicator->draw(2, 2, 805, 25, $IndicatorSettings); } else { $IndicatorSettings = array("Values" => array(100, 201), "CaptionPosition" => INDICATOR_CAPTION_BOTTOM, "CaptionLayout" => INDICATOR_CAPTION_DEFAULT, "CaptionR" => 0, "CaptionG" => 0, "CaptionB" => 0, "DrawLeftHead" => FALSE, "DrawRightHead" => FALSE, "ValueDisplay" => false, "IndicatorSections" => $IndicatorSections[$status], "SectionsMargin" => 0); $Indicator->draw(2, 2, 814, 25, $IndicatorSettings); } $filename = $uid = Session::getLoginUserID(false) . "_test" . $status; $myPicture->render(GLPI_GRAPH_DIR . "/" . $filename . ".png"); echo "<img src='" . $CFG_GLPI['root_doc'] . "/front/graph.send.php?file=" . $filename . ".png'><br/>"; echo "</td>"; echo "</tr>"; } } // Display ticket have Due date if ($ticket->fields['due_date'] && strtotime(date('Y-m-d H:i:s') - strtotime($ticket->fields['due_date'])) > 0) { $calendar = new Calendar(); $calendars_id = Entity::getUsedConfig('calendars_id', $ticket->fields['entities_id']); if ($calendars_id > 0 && $calendar->getFromDB($calendars_id)) { $duedate = $calendar->getActiveTimeBetween($ticket->fields['date'], $ticket->fields['due_date']); if ($ticket->fields['closedate']) { $dateend = $calendar->getActiveTimeBetween($ticket->fields['due_date'], $ticket->fields['closedate']); } else { $dateend = $calendar->getActiveTimeBetween($ticket->fields['due_date'], date('Y-m-d H:i:s')); } } else { // cas 24/24 - 7/7 $duedate = strtotime($ticket->fields['due_date']) - strtotime($ticket->fields['date']); if ($ticket->fields['closedate']) { $dateend = strtotime($ticket->fields['closedate']) - strtotime($ticket->fields['due_date']); } else { $dateend = strtotime(date('Y-m-d H:i:s')) - strtotime($ticket->fields['due_date']); } } echo "<tr class='tab_bg_2'>"; echo "<td width='100' class='tab_bg_2_2'>"; _e('Late'); echo "<br/>(" . round($dateend * 100 / $params['totaltime'], 2) . "%)"; echo "</td>"; echo "<td>"; $calendar = new Calendar(); $calendars_id = Entity::getUsedConfig('calendars_id', $ticket->fields['entities_id']); if ($ticket->fields['status'] != Ticket::CLOSED) { $IndicatorSettings = array("Values" => array(100, 201), "CaptionPosition" => INDICATOR_CAPTION_BOTTOM, "CaptionLayout" => INDICATOR_CAPTION_DEFAULT, "CaptionR" => 0, "CaptionG" => 0, "CaptionB" => 0, "DrawLeftHead" => FALSE, "ValueDisplay" => false, "IndicatorSections" => array(array("Start" => 0, "End" => $duedate, "Caption" => "", "R" => 235, "G" => 235, "B" => 235), array("Start" => $duedate, "End" => $dateend + $duedate, "Caption" => "", "R" => 255, "G" => 0, "B" => 0)), "SectionsMargin" => 0); $Indicator->draw(2, 2, 805, 25, $IndicatorSettings); } else { $IndicatorSettings = array("Values" => array(100, 201), "CaptionPosition" => INDICATOR_CAPTION_BOTTOM, "CaptionLayout" => INDICATOR_CAPTION_DEFAULT, "CaptionR" => 0, "CaptionG" => 0, "CaptionB" => 0, "DrawLeftHead" => FALSE, "DrawRightHead" => FALSE, "ValueDisplay" => false, "IndicatorSections" => array(array("Start" => 0, "End" => $duedate, "Caption" => "", "R" => 235, "G" => 235, "B" => 235), array("Start" => $duedate, "End" => $dateend + $duedate, "Caption" => "", "R" => 255, "G" => 0, "B" => 0)), "SectionsMargin" => 0); $Indicator->draw(2, 2, 814, 25, $IndicatorSettings); } $filename = $uid = Session::getLoginUserID(false) . "_testduedate"; $myPicture->render(GLPI_GRAPH_DIR . "/" . $filename . ".png"); echo "<img src='" . $CFG_GLPI['root_doc'] . "/front/graph.send.php?file=" . $filename . ".png'><br/>"; echo "</td>"; echo "</tr>"; } }
static function showHelpdeskOptions(Entity $entity) { global $LANG, $CFG_GLPI; $ID = $entity->getField('id'); if (!$entity->can($ID, 'r') || !haveRight('entity_helpdesk', 'r')) { return false; } $canedit = haveRight('entity_helpdesk', 'w') && haveAccessToEntity($ID); // Get data $entdata = new EntityData(); if (!$entdata->getFromDB($ID)) { $entdata->getEmpty(); } echo "<div class='spaced'>"; if ($canedit) { echo "<form method='post' name=form action='" . getItemTypeFormURL(__CLASS__) . "'>"; } echo "<table class='tab_cadre_fixe'>"; echo "<tr class='tab_bg_1'><td colspan='2'>" . $LANG['buttons'][15] . " : </td>"; echo "<td colspan='2'>"; $options = array('value' => $entdata->fields["calendars_id"], 'emptylabel' => $LANG['common'][102]); if ($ID == 0) { $options['emptylabel'] = $LANG['sla'][10]; } Dropdown::show('Calendar', $options); if ($entdata->fields["calendars_id"] == 0) { $calendar = new Calendar(); if ($calendar->getFromDB(self::getUsedConfig('calendars_id', $ID))) { echo " - " . $calendar->getLink(); } } echo "</td></tr>"; echo "<tr class='tab_bg_1'><td colspan='2'>" . $LANG['entity'][28] . " : </td>"; echo "<td colspan='2'>"; $toadd = array(); if ($ID != 0) { $toadd = array(0 => $LANG['common'][102]); } Ticket::dropdownType('tickettype', $entdata->fields["tickettype"], $toadd); if ($entdata->fields["calendars_id"] == 0) { $calendar = new Calendar(); if ($calendar->getFromDB(self::getUsedConfig('calendars_id', $ID))) { echo " - " . $calendar->getLink(); } } echo "</td></tr>"; echo "<tr class='tab_bg_1'><td colspan='2'>" . $LANG['setup'][52] . " : </td>"; echo "<td colspan='2'>"; $autoassign = array(-1 => $LANG['setup'][731], NO_AUTO_ASSIGN => $LANG['choice'][0], AUTO_ASSIGN_HARDWARE_CATEGORY => $LANG['setup'][51], AUTO_ASSIGN_CATEGORY_HARDWARE => $LANG['setup'][50]); Dropdown::showFromArray('auto_assign_mode', $autoassign, array('value' => $entdata->fields["auto_assign_mode"])); echo "</td></tr>"; echo "<tr><th colspan='4'>" . $LANG['entity'][17] . "</th></tr>"; echo "<tr class='tab_bg_1'><td colspan='2'>" . $LANG['entity'][18] . " : </td>"; echo "<td colspan='2'>"; Dropdown::showInteger('autoclose_delay', $entdata->fields['autoclose_delay'], 0, 99, 1, array(-1 => $LANG['setup'][731], -10 => $LANG['setup'][307])); /* Alert::dropdownIntegerNever('autoclose_delay', $entdata->fields['autoclose_delay'], array('max' => 99, 'inherit_global' => 1, 'never_value' => -10,)); */ echo " " . $LANG['stats'][31] . "</td></tr>"; echo "<tr><th colspan='4'>" . $LANG['entity'][19] . "</th></tr>"; echo "<tr class='tab_bg_1'><td colspan='2'>" . $LANG['entity'][19] . " : </td>"; echo "<td colspan='2'>"; /// no inquest case = rate 0 $typeinquest = array(0 => $LANG['common'][102], 1 => $LANG['satisfaction'][9], 2 => $LANG['satisfaction'][10]); // No inherit from parent for root entity if ($entdata->fields['entities_id'] == 0) { unset($typeinquest[0]); if ($entdata->fields['inquest_config'] == 0) { $entdata->fields['inquest_config'] = 1; } } $rand = Dropdown::showFromArray('inquest_config', $typeinquest, $options = array('value' => $entdata->fields['inquest_config'])); echo "</td></tr>\n"; // Do not display for root entity in inherit case if ($entdata->fields['inquest_config'] == 0 && $entdata->fields['entities_id'] != 0) { $inquestconfig = self::getUsedConfig('inquest_config', $entdata->fields['entities_id']); $inquestrate = self::getUsedConfig('inquest_config', $entdata->fields['entities_id'], 'inquest_rate'); echo "<tr><td colspan='4' class='green center'>" . $LANG['common'][102] . " : "; if ($inquestrate == 0) { echo $LANG['crontask'][31]; } else { echo $typeinquest[$inquestconfig]; echo " - " . self::getUsedConfig('inquest_config', $entdata->fields['entities_id'], 'inquest_delay'); echo " " . $LANG['stats'][31] . " - "; echo $inquestrate . "%"; if ($inquestconfig == 2) { echo " - " . self::getUsedConfig('inquest_config', $entdata->fields['entities_id'], 'inquest_URL'); } } echo "</td></tr>\n"; } echo "<tr class='tab_bg_1'><td colspan='4'>"; $_REQUEST = array('inquest_config' => $entdata->fields['inquest_config'], 'entities_id' => $ID); $params = array('inquest_config' => '__VALUE__', 'entities_id' => $ID); echo "<div id='inquestconfig'>"; include GLPI_ROOT . '/ajax/ticketsatisfaction.php'; echo "</div>\n"; echo "</td></tr>"; if ($canedit) { echo "<tr>"; echo "<td class='tab_bg_2 center' colspan='4'>"; echo "<input type='hidden' name='entities_id' value='{$ID}'>"; if ($entdata->fields["id"]) { echo "<input type='hidden' name='id' value='" . $entdata->fields["id"] . "'>"; echo "<input type='submit' name='update' value=\"" . $LANG['buttons'][7] . "\"\n class='submit'>"; } else { echo "<input type='submit' name='add' value=\"" . $LANG['buttons'][7] . "\" class='submit'>"; } echo "</td></tr>"; echo "</table></form>"; } else { echo "</table>"; } echo "</div>"; ajaxUpdateItemOnSelectEvent("dropdown_inquest_config{$rand}", "inquestconfig", $CFG_GLPI["root_doc"] . "/ajax/ticketsatisfaction.php", $params); }
/** * Get active time between to date time for the active calendar * * @param $start datetime begin * @param $end datetime end * * @return timestamp of delay **/ function getActiveTimeBetween($start, $end) { if ($end < $start) { return 0; } if (isset($this->fields['id'])) { $slalevel = new SlaLevel(); $cal = new Calendar(); $work_in_days = $this->fields['resolution_time'] >= DAY_TIMESTAMP; // Based on a calendar if ($this->fields['calendars_id'] > 0) { if ($cal->getFromDB($this->fields['calendars_id'])) { return $cal->getActiveTimeBetween($start, $end, $work_in_days); } } else { // No calendar $timestart = strtotime($start); $timeend = strtotime($end); return $timeend - $timestart; } } return 0; }
function plugin_timelineticket_giveItem($type, $ID, $data, $num) { global $CFG_GLPI, $DB; $searchopt =& Search::getOptions($type); $table = $searchopt[$ID]["table"]; $field = $searchopt[$ID]["field"]; switch ($table . '.' . $field) { case "glpi_plugin_timelineticket_grouplevels.groups": if (empty($data["ITEM_{$num}"])) { $out = __('None'); } else { $out = ""; $groups = json_decode($data["ITEM_{$num}"], true); if (!empty($groups)) { foreach ($groups as $key => $val) { $out .= Dropdown::getDropdownName("glpi_groups", $val) . "<br>"; } } } return $out; break; case "glpi_plugin_timelineticket_assigngroups.groups_id": $ptAssignGroup = new PluginTimelineticketAssignGroup(); $group = new Group(); $ticket = new Ticket(); $out = ""; $a_out = array(); $a_groupname = array(); if (!isset($data["ITEM_{$num}"]) or !strstr($data["ITEM_{$num}"], '$$')) { return ""; } $splitg = explode("\$\$\$\$", $data["ITEM_{$num}"]); foreach ($splitg as $datag) { $split = explode("\$\$", $datag); $group->getFromDB($split[0]); $ptAssignGroup->getFromDB($split[1]); $time = $ptAssignGroup->fields['delay']; if ($ptAssignGroup->fields['delay'] === NULL) { $ticket->getFromDB($data["ITEM_0"]); $calendar = new Calendar(); $calendars_id = Entity::getUsedConfig('calendars_id', $ticket->fields['entities_id']); $datedebut = $ptAssignGroup->fields['date']; $enddate = $_SESSION["glpi_currenttime"]; if ($ticket->fields['status'] == Ticket::CLOSED) { $enddate = $ticket->fields['closedate']; } if ($calendars_id > 0 && $calendar->getFromDB($calendars_id)) { $time = $calendar->getActiveTimeBetween($datedebut, $enddate); } else { // cas 24/24 - 7/7 $time = strtotime($enddate) - strtotime($datedebut); } } else { if ($ptAssignGroup->fields['delay'] == 0) { $time = 0; } } $a_groupname[$group->fields['id']] = $group->getLink(); if (isset($a_out[$group->fields['id']])) { $a_out[$group->fields['id']] += $time; } else { $a_out[$group->fields['id']] = $time; } } $a_out_comp = array(); foreach ($a_out as $groups_id => $time) { $a_out_comp[] = $a_groupname[$groups_id] . " : " . Html::timestampToString($time, TRUE, FALSE); } $out = implode("<hr/>", $a_out_comp); return $out; break; } return ""; }
static function getSpecificValueToDisplay($field, $values, array $options = array()) { if (!is_array($values)) { $values = array($field => $values); } switch ($field) { case 'calendars_id': $calendar = new Calendar(); $calendar->getFromDB($values[$field]); return $calendar->getName(1); break; case 'freshness_type': $a_freshness_type = array(); $a_freshness_type['seconds'] = __('Second(s)', 'monitoring'); $a_freshness_type['minutes'] = __('Minute(s)', 'monitoring'); $a_freshness_type['hours'] = __('Hour(s)', 'monitoring'); $a_freshness_type['days'] = __('Day(s)', 'monitoring'); return $a_freshness_type[$values[$field]]; break; } return parent::getSpecificValueToDisplay($field, $values, $options); }
function _addContactUser($a_contacts, $users_id, $i) { $pmContact = new PluginMonitoringContact(); $pmNotificationcommand = new PluginMonitoringNotificationcommand(); $pmContacttemplate = new PluginMonitoringContacttemplate(); $user = new User(); $calendar = new Calendar(); $user->getFromDB($users_id); // Get template $a_pmcontact = current($pmContact->find("`users_id`='" . $users_id . "'", "", 1)); if (empty($a_pmcontact) or isset($a_pmcontact['plugin_monitoring_contacttemplates_id']) and $a_pmcontact['plugin_monitoring_contacttemplates_id'] == '0') { $a_pmcontact = current($pmContacttemplate->find("`is_default`='1'", "", 1)); } else { $a_pmcontact = current($pmContacttemplate->find("`id`='" . $a_pmcontact['plugin_monitoring_contacttemplates_id'] . "'", "", 1)); } $a_contacts[$i]['contact_name'] = $user->fields['name']; $a_contacts[$i]['alias'] = $user->getName(); $a_contacts[$i]['host_notifications_enabled'] = $a_pmcontact['host_notifications_enabled']; $a_contacts[$i]['service_notifications_enabled'] = $a_pmcontact['service_notifications_enabled']; $calendar->getFromDB($a_pmcontact['service_notification_period']); $a_contacts[$i]['service_notification_period'] = $calendar->fields['name']; $calendar->getFromDB($a_pmcontact['host_notification_period']); $a_contacts[$i]['host_notification_period'] = $calendar->fields['name']; $a_servicenotif = array(); if ($a_pmcontact['service_notification_options_w'] == '1') { $a_servicenotif[] = "w"; } if ($a_pmcontact['service_notification_options_u'] == '1') { $a_servicenotif[] = "u"; } if ($a_pmcontact['service_notification_options_c'] == '1') { $a_servicenotif[] = "c"; } if ($a_pmcontact['service_notification_options_r'] == '1') { $a_servicenotif[] = "r"; } if ($a_pmcontact['service_notification_options_f'] == '1') { $a_servicenotif[] = "f"; } if ($a_pmcontact['service_notification_options_n'] == '1') { $a_servicenotif = array("n"); } if (count($a_servicenotif) == "0") { $a_servicenotif = array("n"); } $a_contacts[$i]['service_notification_options'] = implode(",", $a_servicenotif); $a_hostnotif = array(); if ($a_pmcontact['host_notification_options_d'] == '1') { $a_hostnotif[] = "d"; } if ($a_pmcontact['host_notification_options_u'] == '1') { $a_hostnotif[] = "u"; } if ($a_pmcontact['host_notification_options_r'] == '1') { $a_hostnotif[] = "r"; } if ($a_pmcontact['host_notification_options_f'] == '1') { $a_hostnotif[] = "f"; } if ($a_pmcontact['host_notification_options_s'] == '1') { $a_hostnotif[] = "s"; } if ($a_pmcontact['host_notification_options_n'] == '1') { $a_hostnotif = array("n"); } if (count($a_hostnotif) == "0") { $a_hostnotif = array("n"); } $a_contacts[$i]['host_notification_options'] = implode(",", $a_hostnotif); $pmNotificationcommand->getFromDB($a_pmcontact['service_notification_commands']); $a_contacts[$i]['service_notification_commands'] = $pmNotificationcommand->fields['command_name']; $pmNotificationcommand->getFromDB($a_pmcontact['host_notification_commands']); $a_contacts[$i]['host_notification_commands'] = $pmNotificationcommand->fields['command_name']; $a_contacts[$i]['email'] = $user->fields['email']; $a_contacts[$i]['pager'] = $user->fields['phone']; return $a_contacts; }
$delay = $calendar->getActiveTimeBetween($group["date"], $data["closedate"]); } else { $delay = strtotime($data["closedate"]) - strtotime($group["date"]); } if ($delay < 0) { $delay = 0; } $timegroups[$group["groups_id"]] += $delay; } } else { if ($group["delay"] != null) { $timegroups[$group["groups_id"]] = $group["delay"]; } else { $calendar = new Calendar(); $calendars_id = Entity::getUsedConfig('calendars_id', $ticket->fields['entities_id']); if ($calendars_id > 0 && $calendar->getFromDB($calendars_id)) { $delay = $calendar->getActiveTimeBetween($group["date"], $data["closedate"]); } else { $delay = strtotime($data["closedate"]) - strtotime($group["date"]); } if ($delay < 0) { $delay = 0; } $timegroups[$group["groups_id"]] = $delay; } } if (!in_array($group["groups_id"], $ticketgroups)) { $ticketgroups[] = $group["groups_id"]; } } }
/** * Update from 0.78.2 to 0.80 * * @return bool for success (will die for most error) **/ function update0782to080() { global $DB, $migration; $updateresult = true; $ADDTODISPLAYPREF = array(); //TRANS: %s is the number of new version $migration->displayTitle(sprintf(__('Update to %s'), '0.80')); $migration->setVersion('0.80'); $backup_tables = false; $newtables = array('glpi_calendars', 'glpi_calendars_holidays', 'glpi_calendarsegments', 'glpi_computervirtualmachines', 'glpi_computers_softwarelicenses', 'glpi_fieldblacklists', 'glpi_fieldunicities', 'glpi_groups_tickets', 'glpi_holidays', 'glpi_rulecacheprinters', 'glpi_slas', 'glpi_slalevels', 'glpi_slalevels_tickets', 'glpi_slalevelactions', 'glpi_tickets_tickets', 'glpi_tickets_users', 'glpi_ticketsatisfactions', 'glpi_ticketsolutiontemplates', 'glpi_virtualmachinestates', 'glpi_virtualmachinesystems', 'glpi_virtualmachinetypes'); foreach ($newtables as $new_table) { // rename new tables if exists ? if (TableExists($new_table)) { if (TableExists("backup_{$new_table}")) { $query = "DROP TABLE `backup_" . $new_table . "`"; $DB->queryOrDie($query, "0.80 drop backup table 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); } $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Calendar')); // Updating schema $default_calendar_id = 0; if (!TableExists('glpi_calendars')) { $query = "CREATE TABLE `glpi_calendars` (\n `id` int(11) NOT NULL auto_increment,\n `name` varchar(255) default NULL,\n `entities_id` int(11) NOT NULL default '0',\n `is_recursive` tinyint(1) NOT NULL default '0',\n `comment` TEXT DEFAULT NULL ,\n `date_mod` DATETIME DEFAULT NULL ,\n `cache_duration` TEXT DEFAULT NULL ,\n PRIMARY KEY (`id`),\n KEY `name` (`name`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`),\n KEY `date_mod` (`date_mod`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.80 create glpi_calendars"); $ADDTODISPLAYPREF['Calendar'] = array(19); // Create default calendar : use existing config planning_begin _end $query = "INSERT INTO `glpi_calendars`\n (`name`, `entities_id`, `is_recursive`, `comment`)\n VALUES ('Default', 0, 1, 'Default calendar');"; $DB->queryOrDie($query, "0.80 add default glpi_calendars"); $default_calendar_id = $DB->insert_id(); } if (!TableExists('glpi_calendarsegments')) { $query = "CREATE TABLE `glpi_calendarsegments` (\n `id` int(11) NOT NULL auto_increment,\n `calendars_id` int(11) NOT NULL default '0',\n `entities_id` int(11) NOT NULL default '0',\n `is_recursive` tinyint(1) NOT NULL default '0',\n `day` tinyint(1) NOT NULL default '1' COMMENT 'numer of the day based on date(w)',\n `begin` time DEFAULT NULL,\n `end` time DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `calendars_id` (`calendars_id`),\n KEY `day` (`day`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.80 create glpi_calendarsegments"); // add defautl days : from monday to friday if ($default_calendar_id > 0) { $query = "SELECT `planning_begin`, `planning_end`\n FROM `glpi_configs`\n WHERE `id` = '1'"; if ($result = $DB->query($query)) { $begin = $DB->result($result, 0, 'planning_begin'); $end = $DB->result($result, 0, 'planning_end'); if ($begin < $end) { for ($i = 1; $i < 6; $i++) { $query = "INSERT INTO `glpi_calendarsegments`\n (`calendars_id`, `day`, `begin`, `end`)\n VALUES ({$default_calendar_id}, {$i}, '{$begin}', '{$end}')"; $DB->queryOrDie($query, "0.80 add default glpi_calendarsegments"); } } } // Update calendar $calendar = new Calendar(); if ($calendar->getFromDB($default_calendar_id)) { $query = "UPDATE `glpi_calendars`\n SET `cache_duration` = '" . exportArrayToDB($calendar->getDaysDurations()) . "'\n WHERE `id` = '{$default_calendar_id}'"; $DB->queryOrDie($query, "0.80 update default calendar cache"); } } } // Holidays : wrong management : may be a group of several days : will be easy to managed holidays if (!TableExists('glpi_holidays')) { $query = "CREATE TABLE `glpi_holidays` (\n `id` int(11) NOT NULL auto_increment,\n `name` varchar(255) default NULL,\n `entities_id` int(11) NOT NULL default '0',\n `is_recursive` tinyint(1) NOT NULL default '0',\n `comment` TEXT DEFAULT NULL ,\n `begin_date` date default NULL,\n `end_date` date default NULL,\n `is_perpetual` tinyint(1) NOT NULL default '0',\n PRIMARY KEY (`id`),\n KEY `name` (`name`),\n KEY `begin_date` (`begin_date`),\n KEY `end_date` (`end_date`),\n KEY `is_perpetual` (`is_perpetual`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.80 create glpi_holidays"); $ADDTODISPLAYPREF['Holiday'] = array(11, 12, 13); } if (!TableExists('glpi_calendars_holidays')) { $query = "CREATE TABLE `glpi_calendars_holidays` (\n `id` int(11) NOT NULL auto_increment,\n `calendars_id` int(11) NOT NULL default '0',\n `holidays_id` int(11) NOT NULL default '0',\n PRIMARY KEY (`id`),\n UNIQUE KEY `unicity` (`calendars_id`,`holidays_id`),\n KEY `holidays_id` (`holidays_id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.80 create glpi_calendars_holidays"); } $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'SLA')); // Updating schema if (!TableExists('glpi_slas')) { $query = "CREATE TABLE `glpi_slas` (\n `id` int(11) NOT NULL auto_increment,\n `name` varchar(255) default NULL,\n `entities_id` int(11) NOT NULL default '0',\n `is_recursive` tinyint(1) NOT NULL default '0',\n `comment` TEXT DEFAULT NULL ,\n `resolution_time` int(11) NOT NULL,\n `calendars_id` int(11) NOT NULL default '0',\n `date_mod` datetime default NULL,\n PRIMARY KEY (`id`),\n KEY `name` (`name`),\n KEY `calendars_id` (`calendars_id`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`),\n KEY `date_mod` (`date_mod`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.80 create glpi_slas"); $ADDTODISPLAYPREF['SLA'] = array(4); // Get first Ticket template $query = "SELECT `id`\n FROM `glpi_notificationtemplates`\n WHERE `itemtype` LIKE 'Ticket%'\n ORDER BY `id` ASC"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { $query = "INSERT INTO `glpi_notifications`\n (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n `date_mod`)\n VALUES ('Ticket Recall', 0, 'Ticket', 'recall', 'mail',\n " . $DB->result($result, 0, 0) . ", '', 1, 1,\n NOW());"; $DB->queryOrDie($query, "0.80 insert notification"); } } } if (!TableExists('glpi_slalevels')) { $query = "CREATE TABLE `glpi_slalevels` (\n `id` int(11) NOT NULL auto_increment,\n `name` varchar(255) collate utf8_unicode_ci default NULL,\n `slas_id` int(11) NOT NULL default '0',\n `execution_time` int(11) NOT NULL,\n `is_active` tinyint(1) NOT NULL default '1',\n PRIMARY KEY (`id`),\n KEY `name` (`name`),\n KEY `is_active` (`is_active`),\n KEY `slas_id` (`slas_id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.80 create glpi_slalevels"); } if (!TableExists('glpi_slalevelactions')) { $query = "CREATE TABLE `glpi_slalevelactions` (\n `id` int(11) NOT NULL auto_increment,\n `slalevels_id` int(11) NOT NULL default '0',\n `action_type` varchar(255) collate utf8_unicode_ci default NULL,\n `field` varchar(255) collate utf8_unicode_ci default NULL,\n `value` varchar(255) collate utf8_unicode_ci default NULL,\n PRIMARY KEY (`id`),\n KEY `slalevels_id` (`slalevels_id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ;"; $DB->queryOrDie($query, "0.80 create glpi_slalevelactions"); } $migration->addField("glpi_profiles", "calendar", "CHAR( 1 ) NULL", array('update' => "`entity_dropdown`")); $migration->addField("glpi_profiles", "sla", "CHAR( 1 ) NULL", array('update' => "`entity_rule_ticket`")); $migration->addField("glpi_tickets", "slas_id", "INT( 11 ) NOT NULL DEFAULT 0"); $migration->addKey("glpi_tickets", "slas_id"); $migration->addField("glpi_tickets", "slalevels_id", "INT( 11 ) NOT NULL DEFAULT 0"); $migration->addKey("glpi_tickets", "slalevels_id"); if ($migration->addField("glpi_tickets", "due_date", "datetime default NULL")) { $ADDTODISPLAYPREF['Ticket'] = array(18); } $migration->addKey("glpi_tickets", "due_date"); $migration->addField("glpi_tickets", "begin_waiting_date", "datetime default NULL"); $migration->addField("glpi_tickets", "sla_waiting_duration", "INT( 11 ) NOT NULL DEFAULT 0"); if (!TableExists('glpi_slalevels_tickets')) { $query = "CREATE TABLE `glpi_slalevels_tickets` (\n `id` int(11) NOT NULL auto_increment,\n `tickets_id` int(11) NOT NULL default '0',\n `slalevels_id` int(11) NOT NULL default '0',\n `date` datetime default NULL,\n PRIMARY KEY (`id`),\n KEY `tickets_id` (`tickets_id`),\n KEY `slalevels_id` (`slalevels_id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ;"; $DB->queryOrDie($query, "0.80 create glpi_slalevels_tickets"); } if (!countElementsInTable('glpi_crontasks', "`itemtype`='SlaLevel_Ticket' AND `name`='slaticket'")) { $query = "INSERT INTO `glpi_crontasks`\n (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n VALUES ('SlaLevel_Ticket', 'slaticket', 300, NULL, 1, 1, 3,\n 0, 24, 30, NULL, NULL, NULL)"; $DB->queryOrDie($query, "0.80 populate glpi_crontasks for slaticket"); } $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'PasswordForget')); // Updating schema $migration->addField("glpi_users", "token", "char( 40 ) NULL DEFAULT ''"); $migration->addField("glpi_users", "tokendate", "datetime NULL DEFAULT NULL"); $query = "SELECT *\n FROM `glpi_notificationtemplates`\n WHERE `name` = 'Password Forget'"; if ($result = $DB->query($query)) { if ($DB->numrows($result) == 0) { $query = "INSERT INTO `glpi_notificationtemplates`\n (`name`, `itemtype`, `date_mod`)\n VALUES ('Password Forget', 'User', NOW())"; $DB->queryOrDie($query, "0.80 add password forget notification"); $notid = $DB->insert_id(); $query = "INSERT INTO `glpi_notificationtemplatetranslations`\n (`notificationtemplates_id`, `language`, `subject`,\n `content_text`,\n `content_html`)\n VALUES ({$notid}, '', '##user.action##',\n '##user.realname## ##user.firstname##\n\n##lang.passwordforget.information##\n\n##lang.passwordforget.link## ##user.passwordforgeturl##',\n '<p><strong>##user.realname## ##user.firstname##</strong></p>\n<p>##lang.passwordforget.information##</p>\n<p>##lang.passwordforget.link## <a title=\"##user.passwordforgeturl##\" href=\"##user.passwordforgeturl##\">##user.passwordforgeturl##</a></p>')"; $DB->queryOrDie($query, "0.80 add password forget notification translation"); $query = "INSERT INTO `glpi_notifications`\n (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n `date_mod`)\n VALUES ('Password Forget', 0, 'User', 'passwordforget', 'mail',\n {$notid}, '', 1, 1,\n NOW())"; $DB->queryOrDie($query, "0.80 add password forget notification"); $notifid = $DB->insert_id(); $query = "INSERT INTO `glpi_notificationtargets`\n (`id`, `notifications_id`, `type`, `items_id`)\n VALUES (NULL, {$notifid}, 1, 19);"; $DB->queryOrDie($query, "0.80 add password forget notification target"); } } $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Ticket')); // Updating schema $migration->addField("glpi_tickets", "ticket_waiting_duration", "INT( 11 ) NOT NULL DEFAULT 0"); $migration->addField("glpi_entitydatas", "calendars_id", "INT( 11 ) NOT NULL DEFAULT 0"); $migration->addField("glpi_tickets", "close_delay_stat", "INT( 11 ) NOT NULL DEFAULT 0", array('update' => "(UNIX_TIMESTAMP(`glpi_tickets`.`closedate`)\n - UNIX_TIMESTAMP(`glpi_tickets`.`date`))", 'condition' => " WHERE `glpi_tickets`.`status` = 'closed'\n AND `glpi_tickets`.`date` IS NOT NULL\n AND `glpi_tickets`.`closedate` IS NOT NULL\n AND `glpi_tickets`.`closedate` > `glpi_tickets`.`date`")); $migration->addField("glpi_tickets", "solve_delay_stat", "INT( 11 ) NOT NULL DEFAULT 0", array('update' => "(UNIX_TIMESTAMP(`glpi_tickets`.`solvedate`)\n - UNIX_TIMESTAMP(`glpi_tickets`.`date`))", 'condition' => " WHERE (`glpi_tickets`.`status` = 'closed'\n OR `glpi_tickets`.`status` = 'solved')\n AND `glpi_tickets`.`date` IS NOT NULL\n AND `glpi_tickets`.`solvedate` IS NOT NULL\n AND `glpi_tickets`.`solvedate` > `glpi_tickets`.`date`")); if ($migration->addField("glpi_tickets", "takeintoaccount_delay_stat", "INT( 11 ) NOT NULL DEFAULT 0")) { $migration->migrationOneTable('glpi_tickets'); // Manage stat computation for existing tickets // Solved tickets $query = "SELECT `glpi_tickets`.`id` AS ID,\n MIN(UNIX_TIMESTAMP(`glpi_tickets`.`solvedate`)\n - UNIX_TIMESTAMP(`glpi_tickets`.`date`)) AS OPEN,\n MIN(UNIX_TIMESTAMP(`glpi_ticketfollowups`.`date`)\n - UNIX_TIMESTAMP(`glpi_tickets`.`date`)) AS FIRST,\n MIN(UNIX_TIMESTAMP(`glpi_tickettasks`.`date`)\n - UNIX_TIMESTAMP(`glpi_tickets`.`date`)) AS FIRST2\n FROM `glpi_tickets`\n LEFT JOIN `glpi_ticketfollowups`\n ON (`glpi_ticketfollowups`.`tickets_id` = `glpi_tickets`.`id`)\n LEFT JOIN `glpi_tickettasks`\n ON (`glpi_tickettasks`.`tickets_id` = `glpi_tickets`.`id`)\n WHERE (`glpi_tickets`.`status` = 'closed'\n OR `glpi_tickets`.`status` = 'solved')\n AND `glpi_tickets`.`solvedate` IS NOT NULL\n GROUP BY `glpi_tickets`.`id`"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { while ($data = $DB->fetch_assoc($result)) { $firstactiontime = min($data['OPEN'], $data['FIRST'], $data['FIRST2']); $firstactiontime = max(0, $firstactiontime); $query2 = "UPDATE `glpi_tickets`\n SET `takeintoaccount_delay_stat` = '{$firstactiontime}'\n WHERE `id` = '" . $data['ID'] . "'"; $DB->queryOrDie($query2, "0.80 update takeintoaccount_delay_stat values for #" . $data['ID']); } } } // Not solved tickets $query = "SELECT `glpi_tickets`.`id` AS ID,\n MIN(UNIX_TIMESTAMP(`glpi_ticketfollowups`.`date`)\n - UNIX_TIMESTAMP(`glpi_tickets`.`date`)) AS FIRST,\n MIN(UNIX_TIMESTAMP(`glpi_tickettasks`.`date`)\n - UNIX_TIMESTAMP(`glpi_tickets`.`date`)) AS FIRST2\n FROM `glpi_tickets`\n LEFT JOIN `glpi_ticketfollowups`\n ON (`glpi_ticketfollowups`.`tickets_id` = `glpi_tickets`.`id`)\n LEFT JOIN `glpi_tickettasks`\n ON (`glpi_tickettasks`.`tickets_id` = `glpi_tickets`.`id`)\n WHERE (`glpi_tickets`.`status` <> 'closed'\n AND `glpi_tickets`.`status` <> 'solved')\n OR `glpi_tickets`.`solvedate` IS NULL\n GROUP BY `glpi_tickets`.`id`"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { while ($data = $DB->fetch_assoc($result)) { $firstactiontime = min($data['FIRST'], $data['FIRST2']); $firstactiontime = max(0, $firstactiontime); $query2 = "UPDATE `glpi_tickets`\n SET `takeintoaccount_delay_stat` = '{$firstactiontime}'\n WHERE `id` = '" . $data['ID'] . "'"; $DB->queryOrDie($query2, "0.80 update takeintoaccount_delay_stat values for #" . $data['ID']); } } } } // Put realtime in seconds $migration->addField("glpi_tickets", "actiontime", "INT( 11 ) NOT NULL DEFAULT 0", array('update' => "ROUND(realtime * 3600)")); $migration->dropField("glpi_tickets", "realtime"); $migration->addField("glpi_tickettasks", "actiontime", "INT( 11 ) NOT NULL DEFAULT 0", array('update' => "ROUND(realtime * 3600)")); $migration->dropField("glpi_tickettasks", "realtime"); $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Software')); // Updating schema if ($migration->addField("glpi_softwareversions", "operatingsystems_id", "INT( 11 ) NOT NULL DEFAULT '0'")) { $migration->addKey("glpi_softwareversions", "operatingsystems_id"); $migration->migrationOneTable('glpi_softwareversions'); $query = "UPDATE `glpi_softwareversions`,\n (SELECT `id`, `operatingsystems_id`\n FROM `glpi_softwares`) AS SOFT\n SET `glpi_softwareversions`.`operatingsystems_id` = `SOFT`.`operatingsystems_id`\n WHERE `glpi_softwareversions`.`softwares_id` = `SOFT`.`id` "; $DB->queryOrDie($query, "0.80 transfer operatingsystems_id from glpi_softwares to glpi_softwareversions"); $migration->dropField("glpi_softwares", "operatingsystems_id"); } if (!isIndex("glpi_computers_softwareversions", "unicity")) { // clean datas $query = "SELECT `computers_id`,\n `softwareversions_id`,\n COUNT(*) AS CPT\n FROM `glpi_computers_softwareversions`\n GROUP BY `computers_id`, `softwareversions_id`\n HAVING CPT > 1"; if ($result = $DB->query($query)) { if ($DB->numrows($result)) { while ($data = $DB->fetch_assoc($result)) { $query2 = "SELECT `id`\n FROM `glpi_computers_softwareversions`\n WHERE `computers_id` = '" . $data['computers_id'] . "'\n AND `softwareversions_id` = '" . $data['softwareversions_id'] . "'\n LIMIT 1"; if ($result2 = $DB->query($query2)) { if ($DB->numrows($result2)) { $keep_id = $DB->result($result2, 0, 0); $query3 = "DELETE\n FROM `glpi_computers_softwareversions`\n WHERE `computers_id` = '" . $data['computers_id'] . "'\n AND `softwareversions_id` = '" . $data['softwareversions_id'] . "'\n AND `id` <> {$keep_id}"; $DB->queryOrDie($query3, "0.80 clean glpi_computers_softwareversions"); } } } } } $migration->addKey("glpi_computers_softwareversions", array('computers_id', 'softwareversions_id'), 'unicity', "UNIQUE"); } $migration->dropKey("glpi_computers_softwareversions", "computers_id"); // For real count : copy template and deleted information $migration->addField("glpi_computers_softwareversions", "is_deleted", "tinyint(1) NOT NULL DEFAULT 0"); // Gain de temps pour les beta-testeurs if ($migration->addField("glpi_computers_softwareversions", "is_template", "tinyint(1) NOT NULL DEFAULT 0")) { $migration->migrationOneTable('glpi_computers_softwareversions'); // Update datas $query = "SELECT DISTINCT `computers_id`\n FROM `glpi_computers_softwareversions`"; if ($result = $DB->query($query)) { if ($DB->numrows($result)) { while ($data = $DB->fetch_assoc($result)) { $comp = new Computer(); if ($comp->getFromDB($data['computers_id'])) { $query = "UPDATE `glpi_computers_softwareversions`\n SET `is_template` = '" . $comp->getField('is_template') . "',\n `is_deleted` = '" . $comp->getField('is_deleted') . "'\n WHERE `computers_id` = '" . $data['computers_id'] . "';"; $DB->query($query); } } } } } if (!TableExists("glpi_computers_softwarelicenses")) { $query = "CREATE TABLE `glpi_computers_softwarelicenses` (\n `id` int(11) NOT NULL auto_increment,\n `computers_id` int(11) NOT NULL default '0',\n `softwarelicenses_id` int(11) NOT NULL default '0',\n PRIMARY KEY (`id`),\n KEY `computers_id` (`computers_id`),\n KEY `softwarelicenses_id` (`softwarelicenses_id`),\n UNIQUE `unicity` ( `computers_id` , `softwarelicenses_id` )\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.80 create glpi_computers_softwarelicenses"); } if (FieldExists("glpi_softwarelicenses", "computers_id", false)) { $query = "SELECT *\n FROM `glpi_softwarelicenses`\n WHERE `computers_id` > 0\n AND `computers_id` IS NOT NULL"; if ($result = $DB->query($query)) { if ($DB->numrows($result)) { while ($data = $DB->fetch_assoc($result)) { $query = "INSERT INTO `glpi_computers_softwarelicenses`\n (`computers_id`, `softwarelicenses_id`)\n VALUES ('" . $data['computers_id'] . "','" . $data['id'] . "')"; $DB->queryOrDie($query, "0.80 migrate data to computers_softwarelicenses table"); } } } $migration->dropField("glpi_softwarelicenses", "computers_id"); } $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Common')); // Updating schema $migration->addField("glpi_softwarelicenses", "date_mod", "DATETIME NULL"); $migration->addKey("glpi_softwarelicenses", "date_mod"); $migration->renameTable("glpi_cartridges_printermodels", "glpi_cartridgeitems_printermodels"); $migration->addField("glpi_monitors", "have_hdmi", "tinyint(1) NOT NULL DEFAULT 0 AFTER `have_pivot`"); $migration->addField("glpi_monitors", "have_displayport", "tinyint(1) NOT NULL DEFAULT 0 AFTER `have_hdmi`"); $migration->dropField("glpi_configs", "dbreplicate_email"); $migration->addField("glpi_configs", "auto_create_infocoms", "tinyint(1) NOT NULL DEFAULT 0"); $migration->addField("glpi_configs", "csv_delimiter", "CHAR( 1 ) NOT NULL AFTER `number_format`", array('update' => "';'")); $migration->addField("glpi_users", "csv_delimiter", "CHAR( 1 ) NULL AFTER `number_format`"); $migration->addField("glpi_users", "names_format", "INT( 11 ) NULL DEFAULT NULL AFTER `number_format`"); // drop car fait sur mauvais champ $migration->dropKey("glpi_budgets", "end_date"); $migration->migrationOneTable("glpi_budgets"); $migration->addKey("glpi_budgets", "end_date"); $migration->addField("glpi_authldaps", "is_active", "TINYINT( 1 ) NOT NULL DEFAULT '0'", array('update' => "'1'")); $ADDTODISPLAYPREF['AuthLdap'] = array(30); $migration->addField("glpi_authmails", "is_active", "TINYINT( 1 ) NOT NULL DEFAULT '0'", array('update' => "'1'")); $ADDTODISPLAYPREF['AuthMail'] = array(6); $migration->addField("glpi_ocsservers", "is_active", "TINYINT( 1 ) NOT NULL DEFAULT '0'", array('update' => "'1'")); $ADDTODISPLAYPREF['OcsServer'] = array(6); $migration->changeField("glpi_configs", "use_auto_assign_to_tech", "auto_assign_mode", "INT( 11 ) NOT NULL DEFAULT '1'"); $migration->addField("glpi_entitydatas", "auto_assign_mode", "INT( 11 ) NOT NULL DEFAULT '-1'"); $migration->changeField("glpi_entitydatas", "ldapservers_id", "authldaps_id", "INT( 11 ) NOT NULL DEFAULT '0'"); $migration->addField("glpi_users", "user_dn", "TEXT DEFAULT NULL"); $migration->addField("glpi_tickets", "users_id_lastupdater", "INT( 11 ) NOT NULL DEFAULT 0 AFTER `date_mod`"); $migration->addKey("glpi_tickets", "users_id_lastupdater"); $migration->addField("glpi_tickets", "type", "INT( 11 ) NOT NULL DEFAULT 1 AFTER `ticketcategories_id`"); $migration->addKey("glpi_tickets", "type"); $migration->addField("glpi_entitydatas", "tickettype", "INT( 11 ) NOT NULL DEFAULT 0"); // Link between tickets if (!TableExists('glpi_tickets_tickets')) { $query = "CREATE TABLE `glpi_tickets_tickets` (\n `id` int(11) NOT NULL auto_increment,\n `tickets_id_1` int(11) NOT NULL default '0',\n `tickets_id_2` int(11) NOT NULL default '0',\n `link` int(11) NOT NULL default '1',\n PRIMARY KEY (`id`),\n KEY `unicity` (`tickets_id_1`,`tickets_id_2`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.80 create glpi_tickets_tickets"); } //inquest if (!TableExists('glpi_ticketsatisfactions')) { $query = "CREATE TABLE `glpi_ticketsatisfactions` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `tickets_id` int(11) NOT NULL DEFAULT '0',\n `type` int(11) NOT NULL DEFAULT '1',\n `date_begin` DATETIME NULL ,\n `date_answered` DATETIME NULL ,\n `satisfaction` INT(11) NULL ,\n `comment` text COLLATE utf8_unicode_ci,\n PRIMARY KEY (`id`),\n UNIQUE KEY `tickets_id` (`tickets_id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.80 create glpi_ticketsatisfactions"); } // config inquest by entity $migration->addField("glpi_entitydatas", "max_closedate", "DATETIME NULL"); if (!countElementsInTable('glpi_crontasks', "`itemtype`='Ticket' AND `name`='createinquest'")) { $query = "INSERT INTO `glpi_crontasks`\n (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n VALUES ('Ticket', 'createinquest', 86400, NULL, 1, 1, 3,\n 0, 24, 30, NULL, NULL, NULL)"; $DB->queryOrDie($query, "0.80 populate glpi_crontasks for ticketsatisfaction"); } $migration->addField("glpi_entitydatas", "inquest_config", "INT(11) NOT NULL DEFAULT '0'"); $migration->addField("glpi_entitydatas", "inquest_rate", "INT(11) NOT NULL DEFAULT '-1'"); $migration->addField("glpi_entitydatas", "inquest_delay", "INT(11) NOT NULL DEFAULT '-1'"); $migration->addField("glpi_entitydatas", "inquest_URL", "VARCHAR( 255 ) NULL"); $migration->addField("glpi_networkports", "comment", "TEXT COLLATE utf8_unicode_ci"); $migration->addField("glpi_profiles", "rule_dictionnary_printer", "CHAR( 1 ) NULL", array('update' => "`rule_dictionnary_software`")); $query = "SELECT *\n FROM `glpi_notificationtemplates`\n WHERE `name` = 'Ticket Satisfaction'"; if ($result = $DB->query($query)) { if ($DB->numrows($result) == 0) { $query = "INSERT INTO `glpi_notificationtemplates`\n (`name`, `itemtype`, `date_mod`)\n VALUES ('Ticket Satisfaction', 'Ticket', NOW())"; $DB->queryOrDie($query, "0.80 add ticket satisfaction notification"); $notid = $DB->insert_id(); $query = "INSERT INTO `glpi_notificationtemplatetranslations`\n (`notificationtemplates_id`, `language`, `subject`,\n `content_text`, `content_html`)\n VALUES ({$notid}, '', '##ticket.action## ##ticket.title##',\n '##lang.ticket.title## : ##ticket.title##\n\n##lang.ticket.closedate## : ##ticket.closedate##\n\n##lang.satisfaction.text## ##ticket.urlsatisfaction##',\n\n '<p>##lang.ticket.title## : ##ticket.title##</p>\n<p>##lang.ticket.closedate## : ##ticket.closedate##</p>\n<p>##lang.satisfaction.text## <a href=\"##ticket.urlsatisfaction##\">##ticket.urlsatisfaction##</a></p>')"; $DB->queryOrDie($query, "0.80 add ticket satisfaction notification translation"); $query = "INSERT INTO `glpi_notifications`\n (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n `date_mod`)\n VALUES ('Ticket Satisfaction', 0, 'Ticket', 'satisfaction', 'mail',\n {$notid}, '', 1, 1,\n NOW())"; $DB->queryOrDie($query, "0.80 add ticket satisfaction notification"); $notifid = $DB->insert_id(); // $query = "INSERT INTO `glpi_notificationtargets` // (`id`, `notifications_id`, `type`, `items_id`) // VALUES (NULL, $notifid, 1, 3)"; // $DB->queryOrDie($query, "0.80 add ticket satisfaction notification target"); } } //New infocom dates $migration->addField("glpi_infocoms", "order_date", "DATE NULL"); $migration->addField("glpi_infocoms", "delivery_date", "DATE NULL"); $migration->addField("glpi_infocoms", "inventory_date", "DATE NULL"); $migration->addField("glpi_infocoms", "warranty_date", "DATE NULL", array('update' => "`buy_date`")); if (!TableExists('glpi_rulecacheprinters')) { $query = "CREATE TABLE `glpi_rulecacheprinters` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `old_value` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `manufacturer` varchar(255) COLLATE utf8_unicode_ci NOT NULL,\n `rules_id` int(11) NOT NULL DEFAULT '0',\n `new_value` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `new_manufacturer` varchar(255) COLLATE utf8_unicode_ci NOT NULL,\n `ignore_ocs_import` char(1) COLLATE utf8_unicode_ci DEFAULT NULL,\n `is_global` char(1) COLLATE utf8_unicode_ci DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `old_value` (`old_value`),\n KEY `rules_id` (`rules_id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.80 add table glpi_rulecacheprinters"); } $migration->addField("glpi_configs", "use_slave_for_search", "tinyint( 1 ) NOT NULL DEFAULT '0'"); $migration->addField("glpi_configs", "admin_email_name", "varchar( 255 ) collate utf8_unicode_ci default NULL AFTER `admin_email`"); $migration->addField("glpi_configs", "admin_reply_name", "varchar( 255 ) collate utf8_unicode_ci default NULL AFTER `admin_reply`"); $migration->addField("glpi_entitydatas", "admin_email_name", "varchar( 255 ) collate utf8_unicode_ci default NULL AFTER `admin_email`"); $migration->addField("glpi_entitydatas", "admin_reply_name", "varchar( 255 ) collate utf8_unicode_ci default NULL AFTER `admin_reply`"); $migration->addField("glpi_notificationtemplates", "css", "text COLLATE utf8_unicode_ci"); $migration->addField("glpi_configs", "url_maxlength", "int(11) NOT NULL DEFAULT '30' AFTER `list_limit_max`"); $migration->displayMessage(sprintf(__('Data migration - %s'), 'Multi user group for tickets')); if (!TableExists('glpi_groups_tickets')) { $query = "CREATE TABLE `glpi_groups_tickets` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `tickets_id` int(11) NOT NULL DEFAULT '0',\n `groups_id` int(11) NOT NULL DEFAULT '0',\n `type` int(11) NOT NULL DEFAULT '1',\n PRIMARY KEY (`id`),\n KEY `unicity` (`tickets_id`,`type`,`groups_id`),\n KEY `group` (`groups_id`,`type`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.80 add table glpi_groups_tickets"); $query = "SELECT `id`, `groups_id`, `groups_id_assign`\n FROM `glpi_tickets`"; if ($result = $DB->query($query)) { if ($DB->numrows($result)) { while ($data = $DB->fetch_assoc($result)) { if ($data['groups_id'] > 0) { $query = "INSERT INTO `glpi_groups_tickets`\n (`tickets_id`, `groups_id`,\n `type`)\n VALUES ('" . $data['id'] . "', '" . $data['groups_id'] . "',\n '" . CommonITILActor::REQUESTER . "')"; $DB->queryOrDie($query, "0.80 migrate data to glpi_groups_tickets table"); } if ($data['groups_id_assign'] > 0) { $query = "INSERT INTO `glpi_groups_tickets`\n (`tickets_id`, `groups_id`,\n `type`)\n VALUES ('" . $data['id'] . "', '" . $data['groups_id_assign'] . "',\n '" . CommonITILActor::ASSIGN . "')"; $DB->queryOrDie($query, "0.80 migrate data to glpi_groups_tickets table"); } } } } $migration->dropField('glpi_tickets', 'groups_id'); $migration->dropField('glpi_tickets', 'groups_id_assign'); // Migrate templates $from = array('ticket.group##', 'ticket.assigntogroup##', 'ticket.assigntouser##', 'ticket.author.name##', 'ticket.author##'); $to = array('ticket.groups##', 'ticket.assigntogroups##', 'ticket.assigntousers##', 'ticket.authors##', 'author.id##'); $query = "SELECT `glpi_notificationtemplatetranslations`.*\n FROM `glpi_notificationtemplatetranslations`\n INNER JOIN `glpi_notificationtemplates`\n ON (`glpi_notificationtemplates`.`id`\n = `glpi_notificationtemplatetranslations`.`notificationtemplates_id`)\n WHERE `glpi_notificationtemplates`.`itemtype` = 'Ticket'"; if ($result = $DB->query($query)) { if ($DB->numrows($result)) { while ($data = $DB->fetch_assoc($result)) { $query = "UPDATE `glpi_notificationtemplatetranslations`\n SET `subject` = '" . addslashes(str_replace($from, $to, $data['subject'])) . "',\n `content_text` = '" . addslashes(str_replace($from, $to, $data['content_text'])) . "',\n `content_html` = '" . addslashes(str_replace($from, $to, $data['content_html'])) . "'\n WHERE `id` = " . $data['id'] . ""; $DB->queryOrDie($query, "0.80 fix tags usage for multi users"); } } } } if (!TableExists('glpi_tickets_users')) { $query = "CREATE TABLE `glpi_tickets_users` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `tickets_id` int(11) NOT NULL DEFAULT '0',\n `users_id` int(11) NOT NULL DEFAULT '0',\n `type` int(11) NOT NULL DEFAULT '1',\n `use_notification` tinyint(1) NOT NULL DEFAULT '0',\n `alternative_email` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `tickets_id` (`tickets_id`),\n KEY `user` (`users_id`,`type`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.80 add table glpi_tickets_users"); $query = "SELECT `glpi_tickets`.`id`,\n `glpi_tickets`.`users_id_assign`,\n `glpi_tickets`.`users_id`,\n `glpi_tickets`.`use_email_notification`,\n `glpi_tickets`.`user_email`,\n `glpi_users`.`email` AS EMAIL\n FROM `glpi_tickets`\n LEFT JOIN `glpi_users` ON (`glpi_users`.`id` = `glpi_tickets`.`users_id`)"; if ($result = $DB->query($query)) { if ($DB->numrows($result)) { while ($data = $DB->fetch_assoc($result)) { if ($data['users_id_assign'] > 0) { $query = "INSERT INTO `glpi_tickets_users`\n (`tickets_id`, `users_id`,\n `type`, `use_notification`)\n VALUES ('" . $data['id'] . "', '" . $data['users_id_assign'] . "',\n '" . CommonITILActor::ASSIGN . "', '1')"; $DB->queryOrDie($query, "0.80 migrate data to glpi_tickets_users table"); } if ($data['users_id'] > 0 || $data['use_email_notification'] && !empty($data['user_email'])) { $user_id = 0; if ($data['users_id'] > 0) { $user_id = $data['users_id']; } $user_email = ''; if (strcasecmp($data['user_email'], $data['EMAIL']) != 0) { $user_email = addslashes($data['user_email']); } $query = "INSERT INTO `glpi_tickets_users`\n (`tickets_id`, `users_id`,`type`,\n `use_notification`, `alternative_email`)\n VALUES ('" . $data['id'] . "', '{$user_id}', '" . CommonITILActor::REQUESTER . "',\n '" . $data['use_email_notification'] . "', '{$user_email}')"; $DB->queryOrDie($query, "0.80 migrate data to glpi_tickets_users table"); } } } } $migration->dropField('glpi_tickets', 'users_id'); $migration->dropField('glpi_tickets', 'users_id_assign'); $migration->dropField('glpi_tickets', 'use_email_notification'); $migration->dropField('glpi_tickets', 'user_email'); // ADD observer when requester is set : 3>21 / 13>20 / 12 >22 $fromto = array(3 => 21, 13 => 20, 12 => 22); // GROUP_SUPERVISOR foreach ($fromto as $from => $to) { $query = "SELECT *\n FROM `glpi_notificationtargets`\n INNER JOIN `glpi_notifications`\n ON (`glpi_notifications`.`id` = `glpi_notificationtargets`.`notifications_id`)\n WHERE `glpi_notifications`.`itemtype` = 'Ticket'\n AND `glpi_notificationtargets`.`type` = '1'\n AND `glpi_notificationtargets`.`items_id` = '{$from}'"; if ($result = $DB->query($query)) { if ($DB->numrows($result)) { while ($data = $DB->fetch_assoc($result)) { $query = "INSERT INTO `glpi_notificationtargets`\n (`items_id` ,`type` ,`notifications_id`)\n VALUES ('{$to}', '1', '" . $data['notifications_id'] . "')"; $DB->queryOrDie($query, "0.80 insert default notif for observer"); } } } } } $migration->displayMessage(sprintf(__('Data migration - %s'), 'passwords encryption')); if ($migration->addField('glpi_configs', 'proxy_passwd', 'varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL')) { $migration->migrationOneTable('glpi_configs'); $query = "SELECT `proxy_password`\n FROM `glpi_configs`\n WHERE `id` = '1'"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { $value = $DB->result($result, 0, 0); if (!empty($value)) { $query = "UPDATE `glpi_configs`\n SET `proxy_passwd` = '" . addslashes(Toolbox::encrypt($value, GLPIKEY)) . "'\n WHERE `id` = '1' "; $DB->queryOrDie($query, "0.80 update proxy_passwd in glpi_configs"); } } } $migration->dropField('glpi_configs', 'proxy_password'); } if ($migration->addField('glpi_configs', 'smtp_passwd', 'varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL')) { $migration->migrationOneTable('glpi_configs'); $query = "SELECT `smtp_password`\n FROM `glpi_configs`\n WHERE `id` = '1'"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { $value = $DB->result($result, 0, 0); if (!empty($value)) { $query = "UPDATE `glpi_configs`\n SET `smtp_passwd` = '" . addslashes(Toolbox::encrypt($value, GLPIKEY)) . "'\n WHERE `id` = '1' "; $DB->queryOrDie($query, "0.80 update smtp_passwd in glpi_configs"); } } } $migration->dropField('glpi_configs', 'smtp_password'); } if ($migration->addField('glpi_authldaps', 'rootdn_passwd', 'varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL')) { $migration->migrationOneTable('glpi_authldaps'); $query = "SELECT *\n FROM `glpi_authldaps`\n WHERE `rootdn_password` IS NOT NULL\n AND `rootdn_password` <> ''"; if ($result = $DB->query($query)) { if ($DB->numrows($result)) { while ($data = $DB->fetch_assoc($result)) { if (!empty($data['rootdn_password'])) { $query = "UPDATE `glpi_authldaps`\n SET `rootdn_passwd` = '" . addslashes(Toolbox::encrypt($data['rootdn_password'], GLPIKEY)) . "'\n WHERE `id` = '" . $data['id'] . "' "; $DB->queryOrDie($query, "0.80 update rootdn_passwd in glpi_authldaps"); } } } } $migration->dropField('glpi_authldaps', 'rootdn_password'); } //Add date config management fields $migration->addField("glpi_entitydatas", "autofill_warranty_date", "varchar(255) COLLATE utf8_unicode_ci DEFAULT '-1'", array('update' => "'0'", 'condition' => " WHERE `entities_id` = '0'")); $migration->addField("glpi_entitydatas", "autofill_use_date", "varchar(255) COLLATE utf8_unicode_ci DEFAULT '-1'", array('update' => "'0'", 'condition' => " WHERE `entities_id` = '0'")); $migration->addField("glpi_entitydatas", "autofill_buy_date", "varchar(255) COLLATE utf8_unicode_ci DEFAULT '-1'", array('update' => "'0'", 'condition' => " WHERE `entities_id` = '0'")); $migration->addField("glpi_entitydatas", "autofill_delivery_date", "varchar(255) COLLATE utf8_unicode_ci DEFAULT '-1'", array('update' => "'0'", 'condition' => " WHERE `entities_id` = '0'")); $migration->addField("glpi_entitydatas", "autofill_order_date", "varchar(255) COLLATE utf8_unicode_ci DEFAULT '-1'", array('update' => "'0'", 'condition' => " WHERE `entities_id` = '0'")); if (!TableExists('glpi_fieldunicities')) { $query = "CREATE TABLE `glpi_fieldunicities` (\n `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,\n `name` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',\n `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT '0',\n `itemtype` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',\n `entities_id` INT( 11 ) NOT NULL DEFAULT '-1',\n `fields` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',\n `is_active` TINYINT( 1 ) NOT NULL DEFAULT '0',\n `action_refuse` TINYINT( 1 ) NOT NULL DEFAULT '0',\n `action_notify` TINYINT( 1 ) NOT NULL DEFAULT '0',\n `comment` text COLLATE utf8_unicode_ci\n ) ENGINE=MYISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci\n COMMENT = 'Stores field unicity criterias'"; $DB->queryOrDie($query, "0.80 add table glpi_fieldunicities"); $ADDTODISPLAYPREF['FieldUnicity'] = array(1, 80, 4, 3, 86, 30); } $query = "SELECT *\n FROM `glpi_notificationtemplates`\n WHERE `name` = 'Item not unique'"; if ($result = $DB->query($query)) { if ($DB->numrows($result) == 0) { $query = "INSERT INTO `glpi_notificationtemplates`\n (`name`, `itemtype`, `date_mod`)\n VALUES ('Item not unique', 'FieldUnicity', NOW())"; $DB->queryOrDie($query, "0.80 add item not unique notification"); $notid = $DB->insert_id(); $query = "INSERT INTO `glpi_notificationtemplatetranslations` " . "VALUES(NULL, {$notid}, '', '##lang.unicity.action##', " . "'##lang.unicity.entity## : ##unicity.entity## \r\n\n" . "##lang.unicity.itemtype## : ##unicity.itemtype## \r\n\n" . "##lang.unicity.message## : ##unicity.message## \r\n\n" . "##lang.unicity.action_user## : ##unicity.action_user## \r\n\n" . "##lang.unicity.action_type## : ##unicity.action_type## \r\n\n" . "##lang.unicity.date## : ##unicity.date##'," . "'<p>##lang.unicity.entity## : ##unicity.entity##</p>\r\n<p>" . "##lang.unicity.itemtype## : ##unicity.itemtype##</p>\r\n<p>" . "##lang.unicity.message## : ##unicity.message##</p>\r\n<p>" . "##lang.unicity.action_user## : ##unicity.action_user##</p>\r\n<p>" . "##lang.unicity.action_type## : ##unicity.action_type##</p>\r\n<p>" . "##lang.unicity.date## : ##unicity.date##</p>');"; $DB->queryOrDie($query, "0.80 add item not unique notification translation"); $query = "INSERT INTO `glpi_notifications`\n (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n `date_mod`)\n VALUES ('Item not unique', 0, 'FieldUnicity', 'refuse', 'mail',\n {$notid}, '', 1, 1,\n NOW())"; $DB->queryOrDie($query, "0.80 add computer not unique notification"); $notifid = $DB->insert_id(); // $query = "INSERT INTO `glpi_notificationtargets` // (`notifications_id`, `type`, `items_id`) // VALUES ($notifid, 1, 19);"; // $DB->queryOrDie($query, "0.80 add computer not unique notification target"); } } if (!TableExists("glpi_fieldblacklists")) { $query = "CREATE TABLE `glpi_fieldblacklists` (\n `id` INT (11) NOT NULL AUTO_INCREMENT,\n `name` VARCHAR (255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',\n `field` VARCHAR (255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',\n `value` VARCHAR (255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',\n `itemtype` VARCHAR (255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',\n `entities_id` INT (11) NOT NULL DEFAULT '0',\n `is_recursive` TINYINT (1) NOT NULL DEFAULT '0',\n `comment` TEXT COLLATE utf8_unicode_ci,\n PRIMARY KEY (id),\n KEY `name` (`name`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.80 add table glpi_fieldblacklists"); } if ($migration->addField('glpi_mailcollectors', 'passwd', 'varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL')) { $migration->migrationOneTable('glpi_mailcollectors'); $query = "SELECT *\n FROM `glpi_mailcollectors`\n WHERE `password` IS NOT NULL\n AND `password` <> ''"; if ($result = $DB->query($query)) { if ($DB->numrows($result)) { while ($data = $DB->fetch_assoc($result)) { if (!empty($data['password'])) { $query = "UPDATE `glpi_mailcollectors`\n SET `passwd` = '" . addslashes(Toolbox::encrypt($data['password'], GLPIKEY)) . "'\n WHERE `id`= '" . $data['id'] . "' "; $DB->queryOrDie($query, "0.80 update passwd in glpi_mailcollectors"); } } } } $migration->dropField('glpi_mailcollectors', 'password'); } $migration->displayMessage(sprintf(__('Data migration - %s'), 'rule ticket migration')); $changes['RuleTicket'] = array('users_id' => '_users_id_requester', 'groups_id' => '_groups_id_requester', 'users_id_assign' => '_users_id_assign', 'groups_id_assign' => '_groups_id_assign'); // For Rule::RULE_TRACKING_AUTO_ACTION $changes['RuleMailCollector'] = array('username' => '_users_id_requester'); $DB->query("SET SESSION group_concat_max_len = 4194304;"); foreach ($changes as $ruletype => $tab) { // Get rules $query = "SELECT GROUP_CONCAT(`id`)\n FROM `glpi_rules`\n WHERE `sub_type` = '" . $ruletype . "'\n GROUP BY `sub_type`"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { // Get rule string $rules = $DB->result($result, 0, 0); // Update actions foreach ($tab as $old => $new) { $query = "UPDATE `glpi_ruleactions`\n SET `field` = '{$new}'\n WHERE `field` = '{$old}'\n AND `rules_id` IN ({$rules})"; $DB->queryOrDie($query, "0.80 update datas for rules actions"); } // Update criterias foreach ($tab as $old => $new) { $query = "UPDATE `glpi_rulecriterias`\n SET `criteria` = '{$new}'\n WHERE `criteria` = '{$old}'\n AND `rules_id` IN ({$rules})"; $DB->queryOrDie($query, "0.80 update datas for rules criterias"); } } } } // Add watcher crontask if (!countElementsInTable('glpi_crontasks', "`itemtype`='Crontask' AND `name`='watcher'")) { $query = "INSERT INTO `glpi_crontasks`\n (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n VALUES ('Crontask', 'watcher', 86400, NULL, 1, 1, 3,\n 0, 24, 30, NULL, NULL, NULL);"; $DB->queryOrDie($query, "0.80 populate glpi_crontasks for watcher"); } $query = "SELECT *\n FROM `glpi_notificationtemplates`\n WHERE `name` = 'Crontask'"; if ($result = $DB->query($query)) { if ($DB->numrows($result) == 0) { $query = "INSERT INTO `glpi_notificationtemplates`\n (`name`, `itemtype`, `date_mod`)\n VALUES ('Crontask', 'Crontask', NOW())"; $DB->queryOrDie($query, "0.80 add crontask watcher notification"); $notid = $DB->insert_id(); $query = "INSERT INTO `glpi_notificationtemplatetranslations`\n VALUES (NULL, {$notid}, '', '##crontask.action##',\n '##lang.crontask.warning## \r\n\n##FOREACHcrontasks## \n ##crontask.name## : ##crontask.description##\n \n##ENDFOREACHcrontasks##', '<p>##lang.crontask.warning##</p>\r\n<p>##FOREACHcrontasks## <br /><a href=\"##crontask.url##\">##crontask.name##</a> : ##crontask.description##<br /> <br />##ENDFOREACHcrontasks##</p>')"; $DB->queryOrDie($query, "0.80 add crontask notification translation"); $query = "INSERT INTO `glpi_notifications`\n VALUES (NULL, 'Crontask Watcher', 0, 'Crontask', 'alert', 'mail', {$notid}, '', 1, 1,\n NOW())"; $DB->queryOrDie($query, "0.80 add crontask notification"); $notifid = $DB->insert_id(); $query = "INSERT INTO `glpi_notificationtargets`\n (`id`, `notifications_id`, `type`, `items_id`)\n VALUES (NULL, {$notifid}, 1, 1)"; $DB->queryOrDie($query, "0.80 add crontask notification target to global admin"); } } /* OCS-NG new clean links features */ if ($migration->addField('glpi_ocslinks', 'entities_id', 'int(11) NOT NULL DEFAULT \'0\'')) { $migration->migrationOneTable("glpi_ocslinks"); $query = "SELECT `glpi_ocslinks`.`computers_id`, `glpi_computers`.`entities_id`\n FROM `glpi_ocslinks`\n INNER JOIN `glpi_computers`\n ON (`glpi_computers`.`id` = `glpi_ocslinks`.`computers_id`)"; if ($result = $DB->query($query)) { if ($DB->numrows($result)) { while ($data = $DB->fetch_assoc($result)) { $query = "UPDATE `glpi_ocslinks`\n SET `entities_id` = '" . $data['entities_id'] . "'\n WHERE `computers_id` = '" . $data['computers_id'] . "'"; $DB->queryOrDie($query, "0.80 copy entities_id from computers to ocslinks "); } } } } $migration->addField("glpi_profiles", "clean_ocsng", "char(1) COLLATE utf8_unicode_ci DEFAULT NULL", array('update' => "`sync_ocsng`")); /* END - OCS-NG new clean links features */ $migration->addField("glpi_transfers", "keep_disk", "int( 11 ) NOT NULL DEFAULT 0", array('update' => "'1'")); if ($migration->addField("glpi_reminders", "is_helpdesk_visible", "tinyint( 1 ) NOT NULL DEFAULT 0")) { $query = "UPDATE `glpi_profiles`\n SET `reminder_public` = 'r'\n WHERE `interface` = 'helpdesk';"; $DB->queryOrDie($query, "0.80 default set of reminder view for helpdesk users"); } if (!TableExists('glpi_ticketsolutiontemplates')) { $query = "CREATE TABLE `glpi_ticketsolutiontemplates` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `entities_id` int(11) NOT NULL DEFAULT '0',\n `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `content` text COLLATE utf8_unicode_ci,\n `ticketsolutiontypes_id` int(11) NOT NULL DEFAULT '0',\n `comment` text COLLATE utf8_unicode_ci,\n PRIMARY KEY (`id`),\n UNIQUE KEY `unicity` (`entities_id`,`name`),\n KEY `name` (`name`),\n KEY `is_recursive` (`is_recursive`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.80 create glpi_ticketsolutiontemplates"); } // Fix templates tags $updates = array('Ticket' => array('from' => array('##lang.validation.validationstatus##'), 'to' => array('##lang.validation.status## : ##validation.status##'))); foreach ($updates as $itemtype => $changes) { $query = "SELECT `glpi_notificationtemplatetranslations`.*\n FROM `glpi_notificationtemplatetranslations`\n INNER JOIN `glpi_notificationtemplates`\n ON (`glpi_notificationtemplates`.`id`\n = `glpi_notificationtemplatetranslations`.`notificationtemplates_id`)\n WHERE `glpi_notificationtemplates`.`itemtype` = '{$itemtype}'"; if ($result = $DB->query($query)) { if ($DB->numrows($result)) { while ($data = $DB->fetch_assoc($result)) { $query = "UPDATE `glpi_notificationtemplatetranslations`\n SET `subject` = '" . addslashes(str_replace($changes['from'], $changes['to'], $data['subject'])) . "',\n `content_text` = '" . addslashes(str_replace($changes['from'], $changes['to'], $data['content_text'])) . "',\n `content_html` = '" . addslashes(str_replace($changes['from'], $changes['to'], $data['content_html'])) . "'\n WHERE `id` = '" . $data['id'] . "'"; $DB->queryOrDie($query, "0.80 fix template tag usage for {$itemtype}"); } } } } $migration->addField('glpi_profiles', 'update_own_followups', 'char(1) COLLATE utf8_unicode_ci DEFAULT NULL', array('update' => '1', 'condition' => " WHERE `update_followups` = 1")); $migration->addField('glpi_profiles', 'delete_followups', 'char(1) COLLATE utf8_unicode_ci DEFAULT NULL', array('update' => '`update_followups`')); $migration->addField('glpi_ocsservers', 'deleted_behavior', "VARCHAR( 255 ) NOT NULL DEFAULT '1'"); //User registration number $migration->addField('glpi_users', 'registration_number', 'VARCHAR( 255 ) COLLATE utf8_unicode_ci DEFAULT NULL'); $migration->addField('glpi_authldaps', 'registration_number_field', 'VARCHAR( 255 ) COLLATE utf8_unicode_ci DEFAULT NULL'); $migration->addField("glpi_users", "date_sync", "datetime default NULL AFTER `date_mod`", array('update' => "`date_mod`", 'condition' => " WHERE `auths_id` > 0")); //Migrate OCS computers link from static config to rules engine if (FieldExists('glpi_ocsservers', 'is_glpi_link_enabled', false)) { $ocs_servers = getAllDatasFromTable('glpi_ocsservers'); $ranking = 1; foreach ($ocs_servers as $ocs_server) { if ($ocs_server['is_glpi_link_enabled']) { $query = "INSERT INTO `glpi_rules`\n (`entities_id`, `sub_type`, `ranking`, `name`,\n `description`, `match`, `is_active`, `date_mod`, `is_recursive`)\n VALUES ('0', 'RuleImportComputer', '{$ranking}', '" . $ocs_server['name'] . "',\n '', 'AND', 1, NOW(), 1)"; $DB->queryOrDie($query, "0.80 add new rule RuleImportComputer"); $rule_id = $DB->insert_id(); $query = "INSERT INTO `glpi_rulecriterias`\n (`rules_id`, `criteria`, `condition`, `pattern`)\n VALUES ('{$rule_id}', 'ocsservers_id', '0', '" . $ocs_server['id'] . "')"; $DB->queryOrDie($query, "0.80 add new criteria RuleImportComputer"); if ($ocs_server['states_id_linkif']) { $query = "INSERT INTO `glpi_rulecriterias`\n (`rules_id`, `criteria`, `condition`,\n `pattern`)\n VALUES ('{$rule_id}', 'states_id', '0',\n '" . $ocs_server['states_id_linkif'] . "')"; $DB->queryOrDie($query, "0.80 add new criteria RuleImportComputer"); } $simple_criteria = array('use_ip_to_link' => 'IPADDRESS', 'use_mac_to_link' => 'MACADDRESS', 'use_serial_to_link' => 'serial'); foreach ($simple_criteria as $field => $value) { $tmpcriteria = array(); if ($ocs_server[$field]) { $query = "INSERT INTO `glpi_rulecriterias`\n (`rules_id`, `criteria`, `condition`, `pattern`)\n VALUES ('{$rule_id}', '{$value}', '10', '1')"; $DB->queryOrDie($query, "0.80 add new criteria RuleImportComputer"); } } $tmpcriteria = array(); $query = "INSERT INTO `glpi_rulecriterias`\n (`rules_id`, `criteria`, `condition`, `pattern`)"; switch ($ocs_server['use_name_to_link']) { case 1: $query .= "VALUES ('{$rule_id}', 'name', '10', '1')"; $DB->query($query); break; case 2: $query .= "VALUES ('{$rule_id}', 'name', '30', '1')"; $DB->query($query); break; } $query = "INSERT INTO `glpi_ruleactions`\n (`rules_id`, `action_type`, `field`, `value`)\n VALUES ('{$rule_id}', 'assign', '_fusion', '0')"; $DB->queryOrDie($query, "0.80 add new action RuleImportComputer"); $ranking++; } } $todrop = array('is_glpi_link_enabled', 'states_id_linkif', 'use_ip_to_link', 'use_mac_to_link', 'use_name_to_link', 'use_serial_to_link'); foreach ($todrop as $field) { $migration->dropField('glpi_ocsservers', $field); } } /* New automatic transfert feature */ $migration->addField('glpi_configs', 'transfers_id_auto', 'int(11) NOT NULL DEFAULT 0'); $migration->addField('glpi_ocslinks', 'tag', 'varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL'); /* END - New automatic transfert feature */ $migration->addField('glpi_profiles', 'entity_helpdesk', 'char(1) COLLATE utf8_unicode_ci DEFAULT NULL', array('update' => '`notification`')); $migration->addField('glpi_computers', 'uuid', 'varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL'); $migration->addField('glpi_ocsservers', 'import_vms', 'TINYINT(1) NOT NULL DEFAULT 0'); $migration->addField('glpi_ocsservers', 'import_general_uuid', 'TINYINT(1) NOT NULL DEFAULT 0'); $migration->addField('glpi_ocslinks', 'import_vm', 'LONGTEXT COLLATE utf8_unicode_ci DEFAULT NULL'); if (!TableExists('glpi_virtualmachinetypes')) { $query = "CREATE TABLE `glpi_virtualmachinetypes` (\n `id` INT(11) NOT NULL AUTO_INCREMENT,\n `name` VARCHAR(255) NOT NULL DEFAULT '',\n `comment` TEXT NOT NULL,\n PRIMARY KEY (`id`)\n ) ENGINE = MYISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.80 add new table glpi_virtualmachinetypes"); } if (!TableExists('glpi_virtualmachinesystems')) { $query = "CREATE TABLE `glpi_virtualmachinesystems` (\n `id` INT(11) NOT NULL AUTO_INCREMENT,\n `name` VARCHAR(255) NOT NULL DEFAULT '',\n `comment` TEXT NOT NULL,\n PRIMARY KEY (`id`)\n ) ENGINE = MYISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.80 add new table glpi_virtualmachinesystems"); } if (!TableExists('glpi_virtualmachinestates')) { $query = "CREATE TABLE `glpi_virtualmachinestates` (\n `id` INT(11) NOT NULL AUTO_INCREMENT,\n `name` VARCHAR(255) NOT NULL DEFAULT '',\n `comment` TEXT NOT NULL,\n PRIMARY KEY (`id`)\n ) ENGINE = MYISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.80 add new table glpi_virtualmachinestates"); } if (!TableExists('glpi_computervirtualmachines')) { $query = "CREATE TABLE `glpi_computervirtualmachines` (\n `id` INT NOT NULL AUTO_INCREMENT,\n `entities_id` INT(11) NOT NULL DEFAULT '0',\n `computers_id` INT(11) NOT NULL DEFAULT '0',\n `name` VARCHAR(255) NOT NULL DEFAULT '',\n `virtualmachinestates_id` INT(11) NOT NULL DEFAULT '0',\n `virtualmachinesystems_id` INT(11) NOT NULL DEFAULT '0',\n `virtualmachinetypes_id` INT(11) NOT NULL DEFAULT '0',\n `uuid` VARCHAR(255) NOT NULL DEFAULT '',\n `vcpu` INT(11) NOT NULL DEFAULT '0',\n `ram` VARCHAR(255) NOT NULL DEFAULT '',\n PRIMARY KEY (`id`)\n ) ENGINE = MYISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.80 add new table glpi_computervirtualmachines"); } // Clean ticket validations $query = "DELETE\n FROM `glpi_ticketvalidations`\n WHERE `glpi_ticketvalidations`.`tickets_id` NOT IN (SELECT `glpi_tickets`.`id`\n FROM `glpi_tickets`)"; $DB->queryOrDie($query, "0.80 clean glpi_ticketvalidations"); // Keep it at the end $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); } } } } // Change value of autoclose ticket $query = "UPDATE `glpi_configs`\n SET `autoclose_delay` = '-1'\n WHERE `id` = '1'\n AND `autoclose_delay` = '0'"; $DB->queryOrDie($query, "0.80 change autoclose ticket in glpi_configs"); $query = "UPDATE `glpi_entitydatas`\n SET `autoclose_delay` = '-2'\n WHERE `autoclose_delay` = '-1'"; $DB->queryOrDie($query, "0.80 change autoclose ticket in glpi_entitydatas for inherit"); $query = "UPDATE `glpi_entitydatas`\n SET `autoclose_delay` = '-1'\n WHERE `autoclose_delay` = '0'"; $DB->queryOrDie($query, "0.80 change autoclose ticket in glpi_entitydatas for inactive"); // must always be at the end $migration->executeMigration(); return $updateresult; }
function showComponents($componentscatalogs_id) { global $DB, $CFG_GLPI; $this->addComponent($componentscatalogs_id); $rand = mt_rand(); $pmComponent = new PluginMonitoringComponent(); $pmCommand = new PluginMonitoringCommand(); $pmCheck = new PluginMonitoringCheck(); $calendar = new Calendar(); echo "<form method='post' name='componentscatalog_component_form{$rand}' id='componentscatalog_component_form{$rand}' action=\"" . $CFG_GLPI["root_doc"] . "/plugins/monitoring/front/componentscatalog_component.form.php\">"; echo "<table class='tab_cadre_fixe'>"; echo "<tr>"; echo "<th>"; echo __('Associated components', 'monitoring'); echo "</th>"; echo "</tr>"; echo "</table>"; echo "<table class='tab_cadre_fixe'>"; echo "<tr>"; echo "<th width='10'> </th>"; echo "<th>" . __('Name') . "</th>"; echo "<th>" . __('Command name', 'monitoring') . "</th>"; echo "<th>" . __('Check definition', 'monitoring') . "</th>"; echo "<th>" . __('Check period', 'monitoring') . "</th>"; echo "<th>" . __('Remote check', 'monitoring') . "</th>"; echo "</tr>"; $used = array(); $query = "SELECT * FROM `" . $this->getTable() . "`\n WHERE `plugin_monitoring_componentscalalog_id`='" . $componentscatalogs_id . "'"; $result = $DB->query($query); while ($data = $DB->fetch_array($result)) { $used[] = $data['plugin_monitoring_components_id']; $pmComponent->getFromDB($data['plugin_monitoring_components_id']); echo "<tr>"; echo "<td>"; echo "<input type='checkbox' name='item[" . $data["id"] . "]' value='1'>"; echo "</td>"; echo "<td class='center'>"; echo $pmComponent->getLink(1); echo "</td>"; echo "<td class='center'>"; $pmCommand->getFromDB($pmComponent->fields['plugin_monitoring_commands_id']); echo $pmCommand->getLink(); echo "</td>"; echo "<td class='center'>"; $pmCheck->getFromDB($pmComponent->fields['plugin_monitoring_checks_id']); echo $pmCheck->getLink(); echo "</td>"; echo "<td class='center'>"; $calendar->getFromDB($pmComponent->fields['calendars_id']); echo $calendar->getLink(); echo "</td>"; echo "<td class='center'>"; if ($pmComponent->fields['remotesystem'] == '') { echo "-"; } else { echo $pmComponent->fields['remotesystem']; } echo "</td>"; echo "</tr>"; } Html::openArrowMassives("componentscatalog_host_form{$rand}", true); Html::closeArrowMassives(array('deleteitem' => _sx('button', 'Delete permanently'))); Html::closeForm(); echo "</table>"; }
/** * Compute next creation date of a ticket * * New parameter in version 0.84 : $calendars_id * * @param $begin_date datetime Begin date of the recurrent ticket * @param $end_date datetime End date of the recurrent ticket * @param $periodicity timestamp Periodicity of creation * @param $create_before timestamp Create before specific timestamp * @param $calendars_id integer ID of the calendar to used * * @return datetime next creation date **/ function computeNextCreationDate($begin_date, $end_date, $periodicity, $create_before, $calendars_id) { if (empty($begin_date) || $begin_date == 'NULL') { return 'NULL'; } if (!empty($end_date) && $end_date != 'NULL') { if (strtotime($end_date) < time()) { return 'NULL'; } } $check = true; if (preg_match('/([0-9]+)MONTH/', $periodicity) || preg_match('/([0-9]+)YEAR/', $periodicity)) { $check = false; } if ($check && $create_before > $periodicity) { Session::addMessageAfterRedirect(__('Invalid frequency. It must be greater than the preliminary creation.'), false, ERROR); return 'NULL'; } if ($periodicity != 0) { // Standard time computation $timestart = strtotime($begin_date) - $create_before; $now = time(); if ($now > $timestart) { $value = $periodicity; $step = "second"; if (preg_match('/([0-9]+)MONTH/', $periodicity, $matches)) { $value = $matches[1]; $step = 'MONTH'; } else { if (preg_match('/([0-9]+)YEAR/', $periodicity, $matches)) { $value = $matches[1]; $step = 'YEAR'; } else { if ($value % DAY_TIMESTAMP == 0) { $value = $value / DAY_TIMESTAMP; $step = "DAY"; } else { $value = $value / HOUR_TIMESTAMP; $step = "HOUR"; } } } while ($timestart < $now) { $timestart = strtotime("+ {$value} {$step}", $timestart); } } // Time start over end date if (!empty($end_date) && $end_date != 'NULL') { if ($timestart > strtotime($end_date)) { return 'NULL'; } } $calendar = new Calendar(); if ($calendars_id && $calendar->getFromDB($calendars_id)) { $durations = $calendar->getDurationsCache(); if (array_sum($durations) > 0) { // working days exists while (!$calendar->isAWorkingDay($timestart)) { $timestart = strtotime("+ 1 day", $timestart); } } } return date("Y-m-d H:i:s", $timestart); } return 'NULL'; }
static function deleteGroupTicket(Group_Ticket $item) { global $DB; $ticket = new Ticket(); $ptAssignGroup = new PluginTimelineticketAssignGroup(); $ticket->getFromDB($item->fields['tickets_id']); $calendar = new Calendar(); $calendars_id = Entity::getUsedConfig('calendars_id', $ticket->fields['entities_id']); $query = "SELECT MAX(`date`) AS datedebut, id\n FROM `" . $ptAssignGroup->getTable() . "`\n WHERE `tickets_id` = '" . $item->fields['tickets_id'] . "'\n AND `groups_id`='" . $item->fields['groups_id'] . "'\n AND `delay` IS NULL"; $result = $DB->query($query); $datedebut = ''; $input = array(); if ($result && $DB->numrows($result)) { $datedebut = $DB->result($result, 0, 'datedebut'); $input['id'] = $DB->result($result, 0, 'id'); } else { return; } if (!$datedebut) { $delay = 0; // Utilisation calendrier } else { if ($calendars_id > 0 && $calendar->getFromDB($calendars_id)) { $delay = $calendar->getActiveTimeBetween($datedebut, $_SESSION["glpi_currenttime"]); } else { // cas 24/24 - 7/7 $delay = strtotime($_SESSION["glpi_currenttime"]) - strtotime($datedebut); } } $input['delay'] = $delay; $ptAssignGroup->update($input); }
function post_addItem() { global $CFG_GLPI; if (isset($this->input['_planningrecall'])) { $this->input['_planningrecall']['items_id'] = $this->fields['id']; PlanningRecall::manageDatas($this->input['_planningrecall']); } $donotif = $CFG_GLPI["use_mailing"]; if (isset($this->fields["begin"]) && !empty($this->fields["begin"])) { Planning::checkAlreadyPlanned($this->fields["users_id_tech"], $this->fields["begin"], $this->fields["end"], array($this->getType() => array($this->fields["id"]))); $calendars_id = Entity::getUsedConfig('calendars_id', $this->input["_job"]->fields['entities_id']); $calendar = new Calendar(); // Using calendar if ($calendars_id > 0 && $calendar->getFromDB($calendars_id)) { if (!$calendar->isAWorkingHour(strtotime($this->fields["begin"]))) { Session::addMessageAfterRedirect(__('Start of the selected timeframe is not a working hour.'), false, ERROR); } if (!$calendar->isAWorkingHour(strtotime($this->fields["end"]))) { Session::addMessageAfterRedirect(__('End of the selected timeframe is not a working hour.'), false, ERROR); } } } $this->input["_job"]->updateDateMod($this->input[$this->input["_job"]->getForeignKeyField()]); if (isset($this->input["actiontime"]) && $this->input["actiontime"] > 0) { $this->input["_job"]->updateActionTime($this->input[$this->input["_job"]->getForeignKeyField()]); } //change status only if input change if (isset($this->input['_status']) && $this->input['_status'] != $this->input['_job']->fields['status']) { $update['status'] = $this->input['_status']; $update['id'] = $this->input['_job']->fields['id']; $update['_disablenotif'] = true; $this->input['_job']->update($update); } if (!empty($this->fields['begin']) && $this->input["_job"]->isStatusExists(CommonITILObject::PLANNED) && ($this->input["_job"]->fields["status"] == CommonITILObject::INCOMING || $this->input["_job"]->fields["status"] == CommonITILObject::ASSIGNED)) { $input2['id'] = $this->input["_job"]->getID(); $input2['status'] = CommonITILObject::PLANNED; $input2['_disablenotif'] = true; $this->input["_job"]->update($input2); } if ($donotif) { $options = array('task_id' => $this->fields["id"], 'is_private' => $this->isPrivate()); NotificationEvent::raiseEvent('add_task', $this->input["_job"], $options); } // Add log entry in the ITIL object $changes[0] = 0; $changes[1] = ''; $changes[2] = $this->fields['id']; Log::history($this->getField($this->input["_job"]->getForeignKeyField()), $this->input["_job"]->getTYpe(), $changes, $this->getType(), Log::HISTORY_ADD_SUBITEM); }
function showComponents($componentscatalogs_id) { global $DB, $LANG, $CFG_GLPI; $this->addComponent($componentscatalogs_id); $rand = mt_rand(); $pmComponent = new PluginMonitoringComponent(); $pmCommand = new PluginMonitoringCommand(); $pmCheck = new PluginMonitoringCheck(); $calendar = new Calendar(); echo "<form method='post' name='componentscatalog_component_form{$rand}' id='componentscatalog_component_form{$rand}' action=\"" . $CFG_GLPI["root_doc"] . "/plugins/monitoring/front/componentscatalog_component.form.php\">"; echo "<table class='tab_cadre_fixe'>"; echo "<tr>"; echo "<th>"; echo $LANG['plugin_monitoring']['component'][2]; echo "</th>"; echo "</tr>"; echo "</table>"; echo "<table class='tab_cadre_fixe'>"; echo "<tr>"; echo "<th width='10'> </th>"; echo "<th>" . $LANG['common'][16] . "</th>"; echo "<th>" . $LANG['plugin_monitoring']['command'][2] . "</th>"; echo "<th>" . $LANG['plugin_monitoring']['check'][0] . "</th>"; echo "<th>" . $LANG['plugin_monitoring']['host'][9] . "</th>"; echo "<th>" . $LANG['plugin_monitoring']['service'][8] . "</th>"; echo "</tr>"; $used = array(); $query = "SELECT * FROM `" . $this->getTable() . "`\n WHERE `plugin_monitoring_componentscalalog_id`='" . $componentscatalogs_id . "'"; $result = $DB->query($query); while ($data = $DB->fetch_array($result)) { $used[] = $data['plugin_monitoring_components_id']; $pmComponent->getFromDB($data['plugin_monitoring_components_id']); echo "<tr>"; echo "<td>"; echo "<input type='checkbox' name='item[" . $data["id"] . "]' value='1'>"; echo "</td>"; echo "<td class='center'>"; echo $pmComponent->getLink(1); echo "</td>"; echo "<td class='center'>"; $pmCommand->getFromDB($pmComponent->fields['plugin_monitoring_commands_id']); echo $pmCommand->getLink(); echo "</td>"; echo "<td class='center'>"; $pmCheck->getFromDB($pmComponent->fields['plugin_monitoring_checks_id']); echo $pmCheck->getLink(); echo "</td>"; echo "<td class='center'>"; $calendar->getFromDB($pmComponent->fields['calendars_id']); echo $calendar->getLink(); echo "</td>"; echo "<td class='center'>"; if ($pmComponent->fields['remotesystem'] == '') { echo "-"; } else { echo $pmComponent->fields['remotesystem']; } echo "</td>"; echo "</tr>"; } openArrowMassive("componentscatalog_host_form{$rand}", true); closeArrowMassive('deleteitem', $LANG['buttons'][6]); echo "</table>"; }
/** * @since version 0.84 (before in entitydata.class) * * @param $entity Entity object **/ static function showHelpdeskOptions(Entity $entity) { global $CFG_GLPI; $ID = $entity->getField('id'); if (!$entity->can($ID, READ) || !Session::haveRightsOr(self::$rightname, array(self::READHELPDESK, self::UPDATEHELPDESK))) { return false; } $canedit = Session::haveRight(self::$rightname, self::UPDATEHELPDESK) && Session::haveAccessToEntity($ID); echo "<div class='spaced'>"; if ($canedit) { echo "<form method='post' name=form action='" . Toolbox::getItemTypeFormURL(__CLASS__) . "'>"; } echo "<table class='tab_cadre_fixe'>"; echo "<tr class='tab_bg_1'><td colspan='2'>" . _n('Ticket template', 'Ticket templates', 1) . "</td>"; echo "<td colspan='2'>"; $toadd = array(); if ($ID != 0) { $toadd = array(self::CONFIG_PARENT => __('Inheritance of the parent entity')); } $options = array('value' => $entity->fields["tickettemplates_id"], 'entity' => $ID, 'toadd' => $toadd); TicketTemplate::dropdown($options); if ($entity->fields["tickettemplates_id"] == self::CONFIG_PARENT && $ID != 0) { echo "<font class='green'> "; $tt = new TicketTemplate(); $tid = self::getUsedConfig('tickettemplates_id', $ID, '', 0); if (!$tid) { echo Dropdown::EMPTY_VALUE; } else { if ($tt->getFromDB($tid)) { echo $tt->getLink(); } } echo "</font>"; } echo "</td></tr>"; echo "<tr class='tab_bg_1'><td colspan='2'>" . __('Calendar') . "</td>"; echo "<td colspan='2'>"; $options = array('value' => $entity->fields["calendars_id"], 'emptylabel' => __('24/7')); if ($ID != 0) { $options['toadd'] = array(self::CONFIG_PARENT => __('Inheritance of the parent entity')); } Calendar::dropdown($options); if ($entity->fields["calendars_id"] == self::CONFIG_PARENT && $ID != 0) { echo "<font class='green'> "; $calendar = new Calendar(); $cid = self::getUsedConfig('calendars_id', $ID, '', 0); if (!$cid) { _e('24/7'); } else { if ($calendar->getFromDB($cid)) { echo $calendar->getLink(); } } echo "</font>"; } echo "</td></tr>"; echo "<tr class='tab_bg_1'><td colspan='2'>" . __('Tickets default type') . "</td>"; echo "<td colspan='2'>"; $toadd = array(); if ($ID != 0) { $toadd = array(self::CONFIG_PARENT => __('Inheritance of the parent entity')); } Ticket::dropdownType('tickettype', array('value' => $entity->fields["tickettype"], 'toadd' => $toadd)); if ($entity->fields['tickettype'] == self::CONFIG_PARENT && $ID != 0) { echo "<font class='green'> "; echo Ticket::getTicketTypeName(self::getUsedConfig('tickettype', $ID, '', Ticket::INCIDENT_TYPE)); echo "</font>"; } echo "</td></tr>"; echo "<tr class='tab_bg_1'><td colspan='2'>" . __('Automatic assignment of tickets') . "</td>"; echo "<td colspan='2'>"; $autoassign = self::getAutoAssignMode(); if ($ID == 0) { unset($autoassign[self::CONFIG_PARENT]); } Dropdown::showFromArray('auto_assign_mode', $autoassign, array('value' => $entity->fields["auto_assign_mode"])); if ($entity->fields['auto_assign_mode'] == self::CONFIG_PARENT && $ID != 0) { $auto_assign_mode = self::getUsedConfig('auto_assign_mode', $entity->fields['entities_id']); echo "<font class='green'> "; echo $autoassign[$auto_assign_mode]; echo "</font>"; } echo "</td></tr>"; echo "<tr><th colspan='4'>" . __('Automatic closing configuration') . "</th></tr>"; echo "<tr class='tab_bg_1'>" . "<td colspan='2'>" . __('Automatic closing of solved tickets after') . "</td>"; echo "<td colspan='2'>"; $autoclose = array(self::CONFIG_PARENT => __('Inheritance of the parent entity'), self::CONFIG_NEVER => __('Never'), 0 => __('Immediatly')); if ($ID == 0) { unset($autoclose[self::CONFIG_PARENT]); } Dropdown::showNumber('autoclose_delay', array('value' => $entity->fields['autoclose_delay'], 'min' => 1, 'max' => 99, 'step' => 1, 'toadd' => $autoclose, 'unit' => 'day')); if ($entity->fields['autoclose_delay'] == self::CONFIG_PARENT && $ID != 0) { $autoclose_mode = self::getUsedConfig('autoclose_delay', $entity->fields['entities_id'], '', self::CONFIG_NEVER); echo "<br><font class='green'> "; if ($autoclose_mode >= 0) { printf(_n('%d day', '%d days', $autoclose_mode), $autoclose_mode); } else { echo $autoclose[$autoclose_mode]; } echo "</font>"; } echo "</td></tr>"; echo "<tr><th colspan='4'>" . __('Configuring the satisfaction survey') . "</th></tr>"; echo "<tr class='tab_bg_1'>" . "<td colspan='2'>" . __('Configuring the satisfaction survey') . "</td>"; echo "<td colspan='2'>"; /// no inquest case = rate 0 $typeinquest = array(self::CONFIG_PARENT => __('Inheritance of the parent entity'), 1 => __('Internal survey'), 2 => __('External survey')); // No inherit from parent for root entity if ($ID == 0) { unset($typeinquest[self::CONFIG_PARENT]); if ($entity->fields['inquest_config'] == self::CONFIG_PARENT) { $entity->fields['inquest_config'] = 1; } } $rand = Dropdown::showFromArray('inquest_config', $typeinquest, $options = array('value' => $entity->fields['inquest_config'])); echo "</td></tr>\n"; // Do not display for root entity in inherit case if ($entity->fields['inquest_config'] == self::CONFIG_PARENT && $ID != 0) { $inquestconfig = self::getUsedConfig('inquest_config', $entity->fields['entities_id']); $inquestrate = self::getUsedConfig('inquest_config', $entity->fields['entities_id'], 'inquest_rate'); echo "<tr class='tab_bg_1'><td colspan='4' class='green center'>"; if ($inquestrate == 0) { _e('Disabled'); } else { echo $typeinquest[$inquestconfig] . '<br>'; $inqconf = self::getUsedConfig('inquest_config', $entity->fields['entities_id'], 'inquest_delay'); printf(_n('%d day', '%d days', $inqconf), $inqconf); echo "<br>"; //TRANS: %d is the percentage. %% to display % printf(__('%d%%'), $inquestrate); if ($inquestconfig == 2) { echo "<br>"; echo self::getUsedConfig('inquest_config', $entity->fields['entities_id'], 'inquest_URL'); } } echo "</td></tr>\n"; } echo "<tr class='tab_bg_1'><td colspan='4'>"; $_POST = array('inquest_config' => $entity->fields['inquest_config'], 'entities_id' => $ID); $params = array('inquest_config' => '__VALUE__', 'entities_id' => $ID); echo "<div id='inquestconfig'>"; include GLPI_ROOT . '/ajax/ticketsatisfaction.php'; echo "</div>\n"; echo "</td></tr>"; if ($canedit) { echo "<tr class='tab_bg_2'>"; echo "<td class='center' colspan='4'>"; echo "<input type='hidden' name='id' value='" . $entity->fields["id"] . "'>"; echo "<input type='submit' name='update' value=\"" . _sx('button', 'Save') . "\"\n class='submit'>"; echo "</td></tr>"; echo "</table>"; Html::closeForm(); } else { echo "</table>"; } echo "</div>"; Ajax::updateItemOnSelectEvent("dropdown_inquest_config{$rand}", "inquestconfig", $CFG_GLPI["root_doc"] . "/ajax/ticketsatisfaction.php", $params); }
/** * Display form for service configuration * * @param $items_id integer ID * @param $options array * *@return bool true if form is ok * **/ function showForm($items_id, $options = array()) { $pMonitoringCommand = new PluginMonitoringCommand(); if ($items_id == '0') { $this->getEmpty(); } else { $this->getFromDB($items_id); } $this->showFormHeader($options); echo "<tr>"; echo "<td>"; echo __('Template name') . " :"; echo "</td>"; echo "<td>"; echo "<input type='hidden' name='is_template' value='1' />"; $objectName = autoName($this->fields["name"], "name", 1, $this->getType()); Html::autocompletionTextField($this, 'name', array('value' => $objectName)); echo "</td>"; // * commande echo "<td>"; echo __('Command', 'monitoring') . " :"; echo "</td>"; echo "<td align='center'>"; if ($this->fields['is_template'] == '1') { $pMonitoringCommand->getFromDB($this->fields['plugin_monitoring_commands_id']); echo $pMonitoringCommand->getLink(1); } else { $pMonitoringCommand->getFromDB($this->fields['plugin_monitoring_commands_id']); Dropdown::show("PluginMonitoringCommand", array('name' => 'plugin_monitoring_commands_id', 'value' => $this->fields['plugin_monitoring_commands_id'])); } echo "</td>"; echo "</tr>"; echo "<tr>"; // * checks echo "<td>" . __('Check definition', 'monitoring') . " :</td>"; echo "<td align='center'>"; if ($this->fields['is_template'] == '1') { $pMonitoringCheck = new PluginMonitoringCheck(); $pMonitoringCheck->getFromDB($this->fields['plugin_monitoring_checks_id']); echo $pMonitoringCheck->getLink(1); } else { Dropdown::show("PluginMonitoringCheck", array('name' => 'plugin_monitoring_checks_id', 'value' => $this->fields['plugin_monitoring_checks_id'])); } echo "</td>"; // * active check echo "<td>"; echo __('Active checks enable', 'monitoring') . " :"; echo "</td>"; echo "<td align='center'>"; if ($this->fields['is_template'] == '1') { echo Dropdown::getYesNo($this->fields['active_checks_enabled']); } else { Dropdown::showYesNo("active_checks_enabled", $this->fields['active_checks_enabled']); } echo "</td>"; echo "</tr>"; echo "<tr>"; // * passive check echo "<td>"; echo __('Passive checks enable', 'monitoring') . " :"; echo "</td>"; echo "<td align='center'>"; if ($this->fields['is_template'] == '1') { echo Dropdown::getYesNo($this->fields['passive_checks_enabled']); } else { Dropdown::showYesNo("passive_checks_enabled", $this->fields['passive_checks_enabled']); } echo "</td>"; // * calendar echo "<td>" . __('Check period', 'monitoring') . " :</td>"; echo "<td align='center'>"; if ($this->fields['is_template'] == '1') { $calendar = new Calendar(); $calendar->getFromDB($this->fields['calendars_id']); echo $calendar->getLink(1); } else { dropdown::show("Calendar", array('name' => 'calendars_id', 'value' => $this->fields['calendars_id'])); } echo "</td>"; echo "</tr>"; echo "<tr>"; echo "<th colspan='4'>" . __('Remote check', 'monitoring') . "</th>"; echo "</tr>"; echo "<tr>"; // * remotesystem echo "<td>"; echo __('Utility used for remote check', 'monitoring') . " :"; echo "</td>"; echo "<td>"; $input = array(); $input[''] = '------'; $input['byssh'] = __('By ssh', 'monitoring'); $input['nrpe'] = 'nrpe'; $input['nsca'] = 'nsca'; if ($this->fields['is_template'] == '1') { echo $input[$this->fields['remotesystem']]; } else { Dropdown::showFromArray("remotesystem", $input, array('value' => $this->fields['remotesystem'])); } echo "</td>"; // * is_argument echo "<td>"; echo __('Use arguments (Only for NRPE)', 'monitoring') . " :"; echo "</td>"; echo "<td>"; if ($this->fields['is_template'] == '1') { echo Dropdown::getYesNo($this->fields['is_arguments']); } else { Dropdown::showYesNo("is_arguments", $this->fields['is_arguments']); } echo "</td>"; echo "</tr>"; echo "<tr>"; // alias command echo "<td>"; echo __('Alias command if required (Only for NRPE)', 'monitoring') . " :"; echo "</td>"; echo "<td>"; if ($this->fields['is_template'] == '1') { echo "<input type='text' name='alias_commandservice' value='" . $this->fields['alias_command'] . "' />"; } else { echo "<input type='text' name='alias_command' value='" . $this->fields['alias_command'] . "' />"; } echo "</td>"; echo "<td>"; echo __('Command link (used for graphs generation)', 'monitoring') . " :"; echo "</td>"; echo "<td>"; if ($this->fields['is_template'] == '1') { $pMonitoringCommand->getFromDB($this->fields['aliasperfdata_commands_id']); echo $pMonitoringCommand->getLink(1); } else { $pMonitoringCommand->getFromDB($this->fields['aliasperfdata_commands_id']); Dropdown::show("PluginMonitoringCommand", array('name' => 'aliasperfdata_commands_id', 'value' => $this->fields['aliasperfdata_commands_id'])); } echo "</td>"; echo "</tr>"; // * Manage arguments $array = array(); $a_displayarg = array(); if (isset($pMonitoringCommand->fields['command_line'])) { preg_match_all("/\\\$(ARG\\d+)\\\$/", $pMonitoringCommand->fields['command_line'], $array); $a_arguments = importArrayFromDB($this->fields['arguments']); foreach ($array[0] as $arg) { if (strstr($arg, "ARG")) { $arg = str_replace('$', '', $arg); if (!isset($a_arguments[$arg])) { $a_arguments[$arg] = ''; } $a_displayarg[$arg] = $a_arguments[$arg]; } } } if (count($a_displayarg) > 0) { $a_argtext = importArrayFromDB($pMonitoringCommand->fields['arguments']); echo "<tr>"; echo "<th colspan='4'>" . __('Arguments', 'monitoring') . " </th>"; echo "</tr>"; foreach ($a_displayarg as $key => $value) { echo "<tr>"; echo "<th>" . $key . "</th>"; echo "<td colspan='2'>"; if (isset($a_argtext[$key])) { echo nl2br($a_argtext[$key]) . " :"; } else { echo __('Argument', 'monitoring') . " :"; } echo "</td>"; echo "<td>"; echo "<input type='text' name='arg[" . $key . "]' value='" . $value . "'/><br/>"; echo "</td>"; echo "</tr>"; } } $this->showFormButtons($options); return true; }
/** * Generic Function to display Items * * @param $itemtype item type * @param $ID ID of the SEARCH_OPTION item * @param $data array containing data results * @param $num item num in the request * @param $meta is a meta item ? (default 0) * @param $addobjectparams array added parameters for union search * * @return string to print **/ static function giveItem($itemtype, $ID, array $data, $num, $meta = 0, array $addobjectparams = array()) { global $CFG_GLPI, $DB; $searchopt =& self::getOptions($itemtype); if (isset($CFG_GLPI["union_search_type"][$itemtype]) && $CFG_GLPI["union_search_type"][$itemtype] == $searchopt[$ID]["table"]) { if (isset($searchopt[$ID]['addobjectparams']) && $searchopt[$ID]['addobjectparams']) { return self::giveItem($data["TYPE"], $ID, $data, $num, $meta, $searchopt[$ID]['addobjectparams']); } return self::giveItem($data["TYPE"], $ID, $data, $num, $meta); } if (count($addobjectparams)) { $searchopt[$ID] = array_merge($searchopt[$ID], $addobjectparams); } // Plugin can override core definition for its type if ($plug = isPluginItemType($itemtype)) { $function = 'plugin_' . $plug['plugin'] . '_giveItem'; if (function_exists($function)) { $out = $function($itemtype, $ID, $data, $num); if (!empty($out)) { return $out; } } } $NAME = "ITEM_"; // if ($meta) { // $NAME = "META_"; // } if (isset($searchopt[$ID]["table"])) { $table = $searchopt[$ID]["table"]; $field = $searchopt[$ID]["field"]; $linkfield = $searchopt[$ID]["linkfield"]; /// TODO try to clean all specific cases using SpecificToDisplay switch ($table . '.' . $field) { case "glpi_users.name": // USER search case if ($itemtype != 'User' && isset($searchopt[$ID]["forcegroupby"]) && $searchopt[$ID]["forcegroupby"]) { $out = ""; $count_display = 0; $added = array(); $showuserlink = 0; if (Session::haveRight('user', READ)) { $showuserlink = 1; } for ($k = 0; $k < $data[$num]['count']; $k++) { if (isset($data[$num][$k]['name']) && $data[$num][$k]['name'] > 0 || isset($data[$num][$k][2]) && $data[$num][$k][2] != '') { if ($count_display) { $out .= self::LBBR; } if ($itemtype == 'Ticket') { if (isset($data[$num][$k]['name']) && $data[$num][$k]['name'] > 0) { $userdata = getUserName($data[$num][$k]['name'], 2); $tooltip = ""; if (Session::haveRight('user', READ)) { $tooltip = Html::showToolTip($userdata["comment"], array('link' => $userdata["link"], 'display' => false)); } $out .= sprintf(__('%1$s %2$s'), $userdata['name'], $tooltip); $count_display++; } } else { $out .= getUserName($data[$num][$k]['name'], $showuserlink); $count_display++; } // Manage alternative_email for tickets_users if ($itemtype == 'Ticket' && isset($data[$num][$k][2])) { $split = explode(self::LONGSEP, $data[$num][$k][2]); for ($l = 0; $l < count($split); $l++) { $split2 = explode(" ", $split[$l]); if (count($split2) == 2 && $split2[0] == 0 && !empty($split2[1])) { if ($count_display) { $out .= self::LBBR; } $count_display++; $out .= "<a href='mailto:" . $split2[1] . "'>" . $split2[1] . "</a>"; } } } } } return $out; } if ($itemtype != 'User') { $toadd = ''; if ($itemtype == 'Ticket' && $data[$num][0]['id'] > 0) { $userdata = getUserName($data[$num][0]['id'], 2); $toadd = Html::showToolTip($userdata["comment"], array('link' => $userdata["link"], 'display' => false)); } $usernameformat = formatUserName($data[$num][0]['id'], $data[$num][0]['name'], $data[$num][0]['realname'], $data[$num][0]['firstname'], 1); return sprintf(__('%1$s %2$s'), $usernameformat, $toadd); } break; case "glpi_profiles.name": if ($itemtype == 'User' && $ID == 20) { $out = ""; $count_display = 0; $added = array(); for ($k = 0; $k < $data[$num]['count']; $k++) { if (strlen(trim($data[$num][$k]['name'])) > 0) { $text = sprintf(__('%1$s - %2$s'), $data[$num][$k]['name'], Dropdown::getDropdownName('glpi_entities', $data[$num][$k]['entities_id'])); $comp = ''; if ($data[$num][$k]['is_recursive']) { $comp = __('R'); if ($data[$num][$k]['is_dynamic']) { $comp = sprintf(__('%1$s%2$s'), $comp, ", "); } } if ($data[$num][$k]['is_dynamic']) { $comp = sprintf(__('%1$s%2$s'), $comp, __('D')); } if (!empty($comp)) { $text = sprintf(__('%1$s %2$s'), $text, "(" . $comp . ")"); } if (!in_array($text, $added)) { if ($count_display) { $out .= self::LBBR; } $count_display++; $out .= $text; $added[] = $text; } } } return $out; } break; case "glpi_entities.completename": if ($itemtype == 'User') { $out = ""; $added = array(); $count_display = 0; for ($k = 0; $k < $data[$num]['count']; $k++) { if (strlen(trim($data[$num][$k]['name'])) > 0) { $text = sprintf(__('%1$s - %2$s'), $data[$num][$k]['name'], Dropdown::getDropdownName('glpi_profiles', $data[$num][$k]['profiles_id'])); $comp = ''; if ($data[$num][$k]['is_recursive']) { $comp = __('R'); if ($data[$num][$k]['is_dynamic']) { $comp = sprintf(__('%1$s%2$s'), $comp, ", "); } } if ($data[$num][$k]['is_dynamic']) { $comp = sprintf(__('%1$s%2$s'), $comp, __('D')); } if (!empty($comp)) { $text = sprintf(__('%1$s %2$s'), $text, "(" . $comp . ")"); } if (!in_array($text, $added)) { if ($count_display) { $out .= self::LBBR; } $count_display++; $out .= $text; $added[] = $text; } } } return $out; } break; case "glpi_documenttypes.icon": if (!empty($data[$num][0]['name'])) { return "<img class='middle' alt='' src='" . $CFG_GLPI["typedoc_icon_dir"] . "/" . $data[$num][0]['name'] . "'>"; } return " "; case "glpi_documents.filename": $doc = new Document(); if ($doc->getFromDB($data['id'])) { return $doc->getDownloadLink(); } return NOT_AVAILABLE; case "glpi_tickets_tickets.tickets_id_1": $out = ""; $displayed = array(); for ($k = 0; $k < $data[$num]['count']; $k++) { $linkid = $data[$num][$k]['tickets_id_2'] == $data['id'] ? $data[$num][$k]['name'] : $data[$num][$k]['tickets_id_2']; if ($linkid > 0 && !isset($displayed[$linkid])) { $text = "<a "; $text .= "href=\"" . $CFG_GLPI["root_doc"] . "/front/ticket.form.php?id={$linkid}\">"; $text .= Dropdown::getDropdownName('glpi_tickets', $linkid) . "</a>"; if (count($displayed)) { $out .= self::LBBR; } $displayed[$linkid] = $linkid; $out .= $text; } } return $out; case "glpi_problems.id": if ($searchopt[$ID]["datatype"] == 'count') { if ($data[$num][0]['name'] > 0 && Session::haveRight("problem", Problem::READALL)) { if ($itemtype == 'ITILCategory') { $options['criteria'][0]['field'] = 7; $options['criteria'][0]['searchtype'] = 'equals'; $options['criteria'][0]['value'] = $data['id']; $options['criteria'][0]['link'] = 'AND'; } else { $options['criteria'][0]['field'] = 12; $options['criteria'][0]['searchtype'] = 'equals'; $options['criteria'][0]['value'] = 'all'; $options['criteria'][0]['link'] = 'AND'; $options['metacriteria'][0]['itemtype'] = $itemtype; $options['metacriteria'][0]['field'] = self::getOptionNumber($itemtype, 'name'); $options['metacriteria'][0]['searchtype'] = 'equals'; $options['metacriteria'][0]['value'] = $data['id']; $options['metacriteria'][0]['link'] = 'AND'; } $options['reset'] = 'reset'; $out = "<a id='problem{$itemtype}" . $data['id'] . "' "; $out .= "href=\"" . $CFG_GLPI["root_doc"] . "/front/problem.php?" . Toolbox::append_params($options, '&') . "\">"; $out .= $data[$num][0]['name'] . "</a>"; return $out; } } break; case "glpi_tickets.id": if ($searchopt[$ID]["datatype"] == 'count') { if ($data[$num][0]['name'] > 0 && Session::haveRight("ticket", Ticket::READALL)) { if ($itemtype == 'User') { // Requester if ($ID == 60) { $options['criteria'][0]['field'] = 4; $options['criteria'][0]['searchtype'] = 'equals'; $options['criteria'][0]['value'] = $data['id']; $options['criteria'][0]['link'] = 'AND'; } // Writer if ($ID == 61) { $options['criteria'][0]['field'] = 22; $options['criteria'][0]['searchtype'] = 'equals'; $options['criteria'][0]['value'] = $data['id']; $options['criteria'][0]['link'] = 'AND'; } // Assign if ($ID == 64) { $options['criteria'][0]['field'] = 5; $options['criteria'][0]['searchtype'] = 'equals'; $options['criteria'][0]['value'] = $data['id']; $options['criteria'][0]['link'] = 'AND'; } } else { if ($itemtype == 'ITILCategory') { $options['criteria'][0]['field'] = 7; $options['criteria'][0]['searchtype'] = 'equals'; $options['criteria'][0]['value'] = $data['id']; $options['criteria'][0]['link'] = 'AND'; } else { $options['criteria'][0]['field'] = 12; $options['criteria'][0]['searchtype'] = 'equals'; $options['criteria'][0]['value'] = 'all'; $options['criteria'][0]['link'] = 'AND'; $options['metacriteria'][0]['itemtype'] = $itemtype; $options['metacriteria'][0]['field'] = self::getOptionNumber($itemtype, 'name'); $options['metacriteria'][0]['searchtype'] = 'equals'; $options['metacriteria'][0]['value'] = $data['id']; $options['metacriteria'][0]['link'] = 'AND'; } } $options['reset'] = 'reset'; $out = "<a id='ticket{$itemtype}" . $data['id'] . "' "; $out .= "href=\"" . $CFG_GLPI["root_doc"] . "/front/ticket.php?" . Toolbox::append_params($options, '&') . "\">"; $out .= $data[$num][0]['name'] . "</a>"; return $out; } } break; case "glpi_tickets.due_date": case "glpi_problems.due_date": case "glpi_changes.due_date": // Due date + progress if ($ID == 151) { $out = Html::convDate($data[$num][0]['name']); // No due date in waiting status if ($data[$num][0]['status'] == CommonITILObject::WAITING) { return ''; } if (empty($data[$num][0]['name'])) { return ''; } if ($data[$num][0]['status'] == Ticket::SOLVED || $data[$num][0]['status'] == Ticket::CLOSED) { return $out; } $itemtype = getItemTypeForTable($table); $item = new $itemtype(); $item->getFromDB($data['id']); $percentage = 0; $totaltime = 0; $currenttime = 0; if ($item->isField('slas_id') && $item->fields['slas_id'] != 0) { // Have SLA $sla = new SLA(); $sla->getFromDB($item->fields['slas_id']); $currenttime = $sla->getActiveTimeBetween($item->fields['date'], date('Y-m-d H:i:s')); $totaltime = $sla->getActiveTimeBetween($item->fields['date'], $data[$num][0]['name']); } else { $calendars_id = Entity::getUsedConfig('calendars_id', $item->fields['entities_id']); if ($calendars_id != 0) { // Ticket entity have calendar $calendar = new Calendar(); $calendar->getFromDB($calendars_id); $currenttime = $calendar->getActiveTimeBetween($item->fields['date'], date('Y-m-d H:i:s')); $totaltime = $calendar->getActiveTimeBetween($item->fields['date'], $data[$num][0]['name']); } else { // No calendar $currenttime = strtotime(date('Y-m-d H:i:s')) - strtotime($item->fields['date']); $totaltime = strtotime($data[$num][0]['name']) - strtotime($item->fields['date']); } } if ($totaltime != 0) { $percentage = round(100 * $currenttime / $totaltime); } else { // Total time is null : no active time $percentage = 100; } if ($percentage > 100) { $percentage = 100; } $percentage_text = $percentage; if ($_SESSION['glpiduedatewarning_unit'] == '%') { $less_warn_limit = $_SESSION['glpiduedatewarning_less']; $less_warn = 100 - $percentage; } else { if ($_SESSION['glpiduedatewarning_unit'] == 'hour') { $less_warn_limit = $_SESSION['glpiduedatewarning_less'] * HOUR_TIMESTAMP; $less_warn = $totaltime - $currenttime; } else { if ($_SESSION['glpiduedatewarning_unit'] == 'day') { $less_warn_limit = $_SESSION['glpiduedatewarning_less'] * DAY_TIMESTAMP; $less_warn = $totaltime - $currenttime; } } } if ($_SESSION['glpiduedatecritical_unit'] == '%') { $less_crit_limit = $_SESSION['glpiduedatecritical_less']; $less_crit = 100 - $percentage; } else { if ($_SESSION['glpiduedatecritical_unit'] == 'hour') { $less_crit_limit = $_SESSION['glpiduedatecritical_less'] * HOUR_TIMESTAMP; $less_crit = $totaltime - $currenttime; } else { if ($_SESSION['glpiduedatecritical_unit'] == 'day') { $less_crit_limit = $_SESSION['glpiduedatecritical_less'] * DAY_TIMESTAMP; $less_crit = $totaltime - $currenttime; } } } $color = $_SESSION['glpiduedateok_color']; if ($less_crit < $less_crit_limit) { $color = $_SESSION['glpiduedatecritical_color']; } else { if ($less_warn < $less_warn_limit) { $color = $_SESSION['glpiduedatewarning_color']; } } //Calculate bar progress $out .= "<div class='center' style='background-color: #ffffff; width: 100%;\n border: 1px solid #9BA563; position: relative;' >"; $out .= "<div style='position:absolute;'> " . $percentage_text . "%</div>"; $out .= "<div class='center' style='background-color: " . $color . ";\n width: " . $percentage . "%; height: 12px' ></div>"; $out .= "</div>"; return $out; } break; case "glpi_softwarelicenses.number": if ($data[$num][0]['min'] == -1) { return __('Unlimited'); } if (empty($data[$num][0]['name'])) { return 0; } return $data[$num][0]['name']; case "glpi_auth_tables.name": return Auth::getMethodName($data[$num][0]['name'], $data[$num][0]['auths_id'], 1, $data[$num][0]['ldapname'] . $data[$num][0]['mailname']); case "glpi_reservationitems.comment": if (empty($data[$num][0]['name'])) { return "<a title=\"" . __s('Modify the comment') . "\"\n href='" . $CFG_GLPI["root_doc"] . "/front/reservationitem.form.php?id=" . $data["refID"] . "' >" . __('None') . "</a>"; } return "<a title=\"" . __s('Modify the comment') . "\"\n href='" . $CFG_GLPI["root_doc"] . "/front/reservationitem.form.php?id=" . $data['refID'] . "' >" . Html::resume_text($data[$num][0]['name']) . "</a>"; case 'glpi_crontasks.description': $tmp = new CronTask(); return $tmp->getDescription($data[$num][0]['name']); case 'glpi_changes.status': $status = Change::getStatus($data[$num][0]['name']); return "<img src=\"" . Change::getStatusIconURL($data[$num][0]['name']) . "\"\n alt=\"{$status}\" title=\"{$status}\"> {$status}"; case 'glpi_problems.status': $status = Problem::getStatus($data[$num][0]['name']); return "<img src=\"" . Problem::getStatusIconURL($data[$num][0]['name']) . "\"\n alt=\"{$status}\" title=\"{$status}\"> {$status}"; case 'glpi_tickets.status': $status = Ticket::getStatus($data[$num][0]['name']); return "<img src=\"" . Ticket::getStatusIconURL($data[$num][0]['name']) . "\"\n alt=\"{$status}\" title=\"{$status}\"> {$status}"; case 'glpi_projectstates.name': $out = ''; $query = "SELECT `color`\n FROM `glpi_projectstates`\n WHERE `name` = '" . $data[$num][0]['name'] . "'"; foreach ($DB->request($query) as $color) { $color = $color['color']; $out = "<div style=\"background-color:" . $color . ";\">"; $name = $data[$num][0]['name']; if (isset($data[$num][0]['trans'])) { $name = $data[$num][0]['trans']; } if ($itemtype == 'ProjectState') { $out .= "<a href='" . $CFG_GLPI["root_doc"] . "/front/projectstate.form.php?id=" . $data[$num][0]["id"] . "'>" . $name . "</a></div>"; } else { $out .= $name . "</div>"; } } return $out; case 'glpi_items_tickets.items_id': case 'glpi_items_problems.items_id': if (!empty($data[$num])) { $items = array(); foreach ($data[$num] as $key => $val) { if (is_numeric($key)) { if (!empty($val['itemtype']) && ($item = getItemForItemtype($val['itemtype']))) { if ($item->getFromDB($val['name'])) { $items[] = $item->getLink(array('comments' => true)); } } } } if (!empty($items)) { return implode("<br>", $items); } } return ' '; case 'glpi_items_tickets.itemtype': case 'glpi_items_problems.itemtype': if (!empty($data[$num])) { $itemtypes = array(); foreach ($data[$num] as $key => $val) { if (is_numeric($key)) { if (!empty($val['name'])) { if (substr($val['name'], 0, 6) == 'Plugin') { $plug = new $val['name'](); $name = $plug->getTypeName(); $itemtypes[] = __($name); } else { $itemtypes[] = __($val['name']); } } } } if (!empty($itemtypes)) { return implode("<br>", $itemtypes); } } return ' '; case 'glpi_tickets.name': case 'glpi_problems.name': case 'glpi_changes.name': if (isset($data[$num][0]['content']) && isset($data[$num][0]['id']) && isset($data[$num][0]['status'])) { $link = Toolbox::getItemTypeFormURL($itemtype); $out = "<a id='{$itemtype}" . $data[$num][0]['id'] . "' href=\"" . $link; $out .= strstr($link, '?') ? '&' : '?'; $out .= 'id=' . $data[$num][0]['id']; // Force solution tab if solved if ($item = getItemForItemtype($itemtype)) { if (in_array($data[$num][0]['status'], $item->getSolvedStatusArray())) { $out .= "&forcetab={$itemtype}\$2"; } } $out .= "\">"; $name = $data[$num][0]['name']; if ($_SESSION["glpiis_ids_visible"] || empty($data[$num][0]['name'])) { $name = sprintf(__('%1$s (%2$s)'), $name, $data[$num][0]['id']); } $out .= $name . "</a>"; $hdecode = Html::entity_decode_deep($data[$num][0]['content']); $content = Toolbox::unclean_cross_side_scripting_deep($hdecode); $out = sprintf(__('%1$s %2$s'), $out, Html::showToolTip(nl2br(Html::Clean($content)), array('applyto' => $itemtype . $data[$num][0]['id'], 'display' => false))); return $out; } case 'glpi_ticketvalidations.status': $out = ''; for ($k = 0; $k < $data[$num]['count']; $k++) { if ($data[$num][$k]['name']) { $status = TicketValidation::getStatus($data[$num][$k]['name']); $bgcolor = TicketValidation::getStatusColor($data[$num][$k]['name']); $out .= (empty($out) ? '' : self::LBBR) . "<div style=\"background-color:" . $bgcolor . ";\">" . $status . '</div>'; } } return $out; case 'glpi_ticketsatisfactions.satisfaction': if (self::$output_type == self::HTML_OUTPUT) { return TicketSatisfaction::displaySatisfaction($data[$num][0]['name']); } break; case 'glpi_projects._virtual_planned_duration': return Html::timestampToString(ProjectTask::getTotalPlannedDurationForProject($data["id"]), false); case 'glpi_projects._virtual_effective_duration': return Html::timestampToString(ProjectTask::getTotalEffectiveDurationForProject($data["id"]), false); case 'glpi_cartridgeitems._virtual': return Cartridge::getCount($data["id"], $data[$num][0]['alarm_threshold'], self::$output_type != self::HTML_OUTPUT); case 'glpi_printers._virtual': return Cartridge::getCountForPrinter($data["id"], self::$output_type != self::HTML_OUTPUT); case 'glpi_consumableitems._virtual': return Consumable::getCount($data["id"], $data[$num][0]['alarm_threshold'], self::$output_type != self::HTML_OUTPUT); case 'glpi_links._virtual': $out = ''; $link = new Link(); if (($item = getItemForItemtype($itemtype)) && $item->getFromDB($data['id']) && $link->getfromDB($data[$num][0]['id']) && $item->fields['entities_id'] == $link->fields['entities_id']) { if (count($data[$num])) { $count_display = 0; foreach ($data[$num] as $val) { if (is_array($val)) { $links = Link::getAllLinksFor($item, $val); foreach ($links as $link) { if ($count_display) { $out .= self::LBBR; } $out .= $link; $count_display++; } } } } } return $out; case 'glpi_reservationitems._virtual': if ($data[$num][0]['is_active']) { return "<a href='reservation.php?reservationitems_id=" . $data["refID"] . "' title=\"" . __s('See planning') . "\">" . "<img src=\"" . $CFG_GLPI["root_doc"] . "/pics/reservation-3.png\" alt='' title=''></a>"; } else { return " "; } } } //// Default case // Link with plugin tables : need to know left join structure if (isset($table)) { if (preg_match("/^glpi_plugin_([a-z0-9]+)/", $table . '.' . $field, $matches)) { if (count($matches) == 2) { $plug = $matches[1]; $function = 'plugin_' . $plug . '_giveItem'; if (function_exists($function)) { $out = $function($itemtype, $ID, $data, $num); if (!empty($out)) { return $out; } } } } } $unit = ''; if (isset($searchopt[$ID]['unit'])) { $unit = $searchopt[$ID]['unit']; } // Preformat items if (isset($searchopt[$ID]["datatype"])) { switch ($searchopt[$ID]["datatype"]) { case "itemlink": $linkitemtype = getItemTypeForTable($searchopt[$ID]["table"]); $out = ""; $count_display = 0; $separate = self::LBBR; if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) { $separate = self::LBHR; } for ($k = 0; $k < $data[$num]['count']; $k++) { if (isset($data[$num][$k]['id'])) { if ($count_display) { $out .= $separate; } $count_display++; $page = $linkitemtype::getFormUrl(); $page .= strpos($page, '?') ? '&id' : '?id'; $name = Dropdown::getValueWithUnit($data[$num][$k]['name'], $unit); if ($_SESSION["glpiis_ids_visible"] || empty($data[$num][$k]['name'])) { $name = sprintf(__('%1$s (%2$s)'), $name, $data[$num][$k]['id']); } $out .= "<a id='" . $linkitemtype . "_" . $data['id'] . "_" . $data[$num][$k]['id'] . "' href='{$page}=" . $data[$num][$k]['id'] . "'>" . $name . "</a>"; } } return $out; case "text": $separate = self::LBBR; if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) { $separate = self::LBHR; } $out = ''; $count_display = 0; for ($k = 0; $k < $data[$num]['count']; $k++) { if (strlen(trim($data[$num][$k]['name'])) > 0) { if ($count_display) { $out .= $separate; } $count_display++; $text = ""; if (isset($searchopt[$ID]['htmltext']) && $searchopt[$ID]['htmltext']) { $text = Html::clean(Toolbox::unclean_cross_side_scripting_deep(nl2br($data[$num][$k]['name']))); } else { $text = nl2br($data[$num][$k]['name']); } if (self::$output_type == self::HTML_OUTPUT && Toolbox::strlen($text) > $CFG_GLPI['cut']) { $rand = mt_rand(); $out .= sprintf(__('%1$s %2$s'), "<span id='text{$rand}'>" . Html::resume_text($text, $CFG_GLPI['cut']) . '</span>', Html::showToolTip($text, array('applyto' => "text{$rand}", 'display' => false))); } else { $out .= $text; } } } return $out; case "date": case "date_delay": $out = ''; for ($k = 0; $k < $data[$num]['count']; $k++) { if (is_null($data[$num][$k]['name']) && isset($searchopt[$ID]['emptylabel']) && $searchopt[$ID]['emptylabel']) { $out .= (empty($out) ? '' : self::LBBR) . $searchopt[$ID]['emptylabel']; } else { $out .= (empty($out) ? '' : self::LBBR) . Html::convDate($data[$num][$k]['name']); } } return $out; case "datetime": $out = ''; for ($k = 0; $k < $data[$num]['count']; $k++) { if (is_null($data[$num][$k]['name']) && isset($searchopt[$ID]['emptylabel']) && $searchopt[$ID]['emptylabel']) { $out .= (empty($out) ? '' : self::LBBR) . $searchopt[$ID]['emptylabel']; } else { $out .= (empty($out) ? '' : self::LBBR) . Html::convDateTime($data[$num][$k]['name']); } } return $out; case "timestamp": $withseconds = false; if (isset($searchopt[$ID]['withseconds'])) { $withseconds = $searchopt[$ID]['withseconds']; } $withdays = true; if (isset($searchopt[$ID]['withdays'])) { $withdays = $searchopt[$ID]['withdays']; } $out = ''; for ($k = 0; $k < $data[$num]['count']; $k++) { $out .= (empty($out) ? '' : '<br>') . Html::timestampToString($data[$num][$k]['name'], $withseconds, $withdays); } return $out; case "email": $out = ''; $count_display = 0; for ($k = 0; $k < $data[$num]['count']; $k++) { if ($count_display) { $out .= self::LBBR; } $count_display++; if (!empty($data[$num][$k]['name'])) { $out .= empty($out) ? '' : self::LBBR; $out .= "<a href='mailto:" . $data[$num][$k]['name'] . "'>" . $data[$num][$k]['name']; $out .= "</a>"; } } return empty($out) ? " " : $out; case "weblink": $orig_link = trim($data[$num][0]['name']); if (!empty($orig_link)) { // strip begin of link $link = preg_replace('/https?:\\/\\/(www[^\\.]*\\.)?/', '', $orig_link); $link = preg_replace('/\\/$/', '', $link); if (Toolbox::strlen($link) > $CFG_GLPI["url_maxlength"]) { $link = Toolbox::substr($link, 0, $CFG_GLPI["url_maxlength"]) . "..."; } return "<a href=\"" . formatOutputWebLink($orig_link) . "\" target='_blank'>{$link}</a>"; } return " "; case "count": case "number": $out = ""; $count_display = 0; for ($k = 0; $k < $data[$num]['count']; $k++) { if (strlen(trim($data[$num][$k]['name'])) > 0) { if ($count_display) { $out .= self::LBBR; } $count_display++; if (isset($searchopt[$ID]['toadd']) && isset($searchopt[$ID]['toadd'][$data[$num][$k]['name']])) { $out .= $searchopt[$ID]['toadd'][$data[$num][$k]['name']]; } else { $number = str_replace(' ', ' ', Html::formatNumber($data[$num][$k]['name'], false, 0)); $out .= Dropdown::getValueWithUnit($number, $unit); } } } return $out; case "decimal": $out = ""; $count_display = 0; for ($k = 0; $k < $data[$num]['count']; $k++) { if (strlen(trim($data[$num][$k]['name'])) > 0) { if ($count_display) { $out .= self::LBBR; } $count_display++; if (isset($searchopt[$ID]['toadd']) && isset($searchopt[$ID]['toadd'][$data[$num][$k]['name']])) { $out .= $searchopt[$ID]['toadd'][$data[$num][$k]['name']]; } else { $number = str_replace(' ', ' ', Html::formatNumber($data[$num][$k]['name'])); $out .= Dropdown::getValueWithUnit($number, $unit); } } } return $out; case "bool": $out = ""; $count_display = 0; for ($k = 0; $k < $data[$num]['count']; $k++) { if (strlen(trim($data[$num][$k]['name'])) > 0) { if ($count_display) { $out .= self::LBBR; } $count_display++; $out .= Dropdown::getValueWithUnit(Dropdown::getYesNo($data[$num][$k]['name']), $unit); } } return $out; case "itemtypename": if ($obj = getItemForItemtype($data[$num][0]['name'])) { return $obj->getTypeName(); } return ""; case "language": if (isset($CFG_GLPI['languages'][$data[$num][0]['name']])) { return $CFG_GLPI['languages'][$data[$num][0]['name']][0]; } return __('Default value'); } } // Manage items with need group by / group_concat $out = ""; $count_display = 0; $separate = self::LBBR; if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) { $separate = self::LBHR; } for ($k = 0; $k < $data[$num]['count']; $k++) { if (strlen(trim($data[$num][$k]['name'])) > 0) { if ($count_display) { $out .= $separate; } $count_display++; // Get specific display if available $itemtype = getItemTypeForTable($table); if ($item = getItemForItemtype($itemtype)) { $tmpdata = $data[$num][$k]; // Copy name to real field $tmpdata[$field] = $data[$num][$k]['name']; $specific = $item->getSpecificValueToDisplay($field, $tmpdata, array('html' => true, 'searchopt' => $searchopt[$ID])); } if (!empty($specific)) { $out .= $specific; } else { if (isset($searchopt[$ID]['toadd']) && isset($searchopt[$ID]['toadd'][$data[$num][$k]['name']])) { $out .= $searchopt[$ID]['toadd'][$data[$num][$k]['name']]; } else { // Empty is 0 or empty if (empty($split[0]) && isset($searchopt[$ID]['emptylabel'])) { $out .= $searchopt[$ID]['emptylabel']; } else { // Trans field exists if (isset($data[$num][$k]['trans']) && !empty($data[$num][$k]['trans'])) { $out .= Dropdown::getValueWithUnit($data[$num][$k]['trans'], $unit); } else { $out .= Dropdown::getValueWithUnit($data[$num][$k]['name'], $unit); } } } } } } return $out; // Trans in group concat if (count($split) == 3 && !empty($split[1])) { return Dropdown::getValueWithUnit($split[1], $unit); } return Dropdown::getValueWithUnit($split[0], $unit); }
/** * Generic Function to display Items * * @param $itemtype item type * @param $ID ID of the SEARCH_OPTION item * @param $data array containing data results * @param $num item num in the request * @param $meta is a meta item ? (default 0) * @param $addobjectparams array added parameters for union search * * @return string to print **/ static function giveItem($itemtype, $ID, array $data, $num, $meta = 0, array $addobjectparams = array()) { global $CFG_GLPI; $showuserlink = 0; if (Session::haveRight('user', READ)) { $showuserlink = 1; } $searchopt =& self::getOptions($itemtype); if (isset($CFG_GLPI["union_search_type"][$itemtype]) && $CFG_GLPI["union_search_type"][$itemtype] == $searchopt[$ID]["table"]) { if (isset($searchopt[$ID]['addobjectparams']) && $searchopt[$ID]['addobjectparams']) { return self::giveItem($data["TYPE"], $ID, $data, $num, $meta, $searchopt[$ID]['addobjectparams']); } return self::giveItem($data["TYPE"], $ID, $data, $num, $meta); } if (count($addobjectparams)) { $searchopt[$ID] = array_merge($searchopt[$ID], $addobjectparams); } // Plugin can override core definition for its type if ($plug = isPluginItemType($itemtype)) { $function = 'plugin_' . $plug['plugin'] . '_giveItem'; if (function_exists($function)) { $out = $function($itemtype, $ID, $data, $num); if (!empty($out)) { return $out; } } } $NAME = "ITEM_"; if ($meta) { $NAME = "META_"; } $table = $searchopt[$ID]["table"]; $field = $searchopt[$ID]["field"]; $linkfield = $searchopt[$ID]["linkfield"]; /// TODO try to clean all specific cases using SpecificToDisplay switch ($table . '.' . $field) { case "glpi_users.name": // USER search case if ($itemtype != 'User' && isset($searchopt[$ID]["forcegroupby"]) && $searchopt[$ID]["forcegroupby"]) { $out = ""; $split = explode("\$\$\$\$", $data[$NAME . $num]); $count_display = 0; $added = array(); for ($k = 0; $k < count($split); $k++) { if ($split[$k] > 0) { if ($count_display) { $out .= "<br>"; } $count_display++; if ($itemtype == 'Ticket') { $userdata = getUserName($split[$k], 2); $tooltip = ""; if (Session::haveRight('user', READ)) { $tooltip = Html::showToolTip($userdata["comment"], array('link' => $userdata["link"], 'display' => false)); } $out .= sprintf(__('%1$s %2$s'), $userdata['name'], $tooltip); } else { $out .= getUserName($split[$k], $showuserlink); } } } // Manage alternative_email for tickets_users if ($itemtype == 'Ticket' && isset($data[$NAME . $num . '_2'])) { $split = explode("\$\$\$\$", $data[$NAME . $num . '_2']); for ($k = 0; $k < count($split); $k++) { $split2 = explode(" ", $split[$k]); if (count($split2) == 2 && $split2[0] == 0 && !empty($split2[1])) { if ($count_display) { $out .= "<br>"; } $count_display++; $out .= "<a href='mailto:" . $split2[1] . "'>" . $split2[1] . "</a>"; } } } return $out; } if ($itemtype != 'User') { $toadd = ''; if ($itemtype == 'Ticket' && $data[$NAME . $num . "_3"] > 0) { $userdata = getUserName($data[$NAME . $num . "_3"], 2); $toadd = Html::showToolTip($userdata["comment"], array('link' => $userdata["link"], 'display' => false)); } if (Session::haveRight('user', READ)) { $usernameformat = formatUserName($data[$NAME . $num . "_3"], $data[$NAME . $num], $data[$NAME . $num . "_2"], $data[$NAME . $num . "_4"], 1); } else { $usernameformat = formatUserName($data[$NAME . $num . "_3"], $data[$NAME . $num], $data[$NAME . $num . "_2"], $data[$NAME . $num . "_4"], 0); } return sprintf(__('%1$s %2$s'), $usernameformat, $toadd); } break; case "glpi_profiles.interface": return Profile::getInterfaceName($data[$NAME . $num]); case "glpi_profiles.name": if ($itemtype == 'User' && $ID == 20) { $out = ""; $split = explode("\$\$\$\$", $data[$NAME . $num]); $split2 = explode("\$\$\$\$", $data[$NAME . $num . "_2"]); $split3 = explode("\$\$\$\$", $data[$NAME . $num . "_3"]); $split4 = explode("\$\$\$\$", $data[$NAME . $num . "_4"]); $count_display = 0; $added = array(); for ($k = 0; $k < count($split); $k++) { if (strlen(trim($split[$k])) > 0) { $text = sprintf(__('%1$s - %2$s'), $split[$k], Dropdown::getDropdownName('glpi_entities', $split2[$k])); $comp = ''; if ($split3[$k]) { $comp = __(READ); if ($split4[$k]) { $comp = sprintf(__('%1$s%2$s'), $comp, ", "); } } if ($split4[$k]) { $comp = sprintf(__('%1$s%2$s'), $comp, __('D')); } if (!empty($comp)) { $text = sprintf(__('%1$s %2$s'), $text, "(" . $comp . ")"); } if (!in_array($text, $added)) { if ($count_display) { $out .= "<br>"; } $count_display++; $out .= $text; $added[] = $text; } } } return $out; } break; case "glpi_entities.completename": if ($itemtype == 'User') { $out = ""; $split = explode("\$\$\$\$", $data[$NAME . $num]); $split2 = explode("\$\$\$\$", $data[$NAME . $num . "_2"]); $split3 = explode("\$\$\$\$", $data[$NAME . $num . "_3"]); $split4 = explode("\$\$\$\$", $data[$NAME . $num . "_4"]); $added = array(); $count_display = 0; for ($k = 0; $k < count($split); $k++) { if (strlen(trim($split[$k])) > 0) { $text = sprintf(__('%1$s - %2$s'), $split[$k], Dropdown::getDropdownName('glpi_profiles', $split2[$k])); $comp = ''; if ($split3[$k]) { $comp = __(READ); if ($split4[$k]) { $comp = sprintf(__('%1$s%2$s'), $comp, ", "); } } if ($split4[$k]) { $comp = sprintf(__('%1$s%2$s'), $comp, __('D')); } if (!empty($comp)) { $text = sprintf(__('%1$s %2$s'), $text, "(" . $comp . ")"); } if (!in_array($text, $added)) { if ($count_display) { $out .= "<br>"; } $count_display++; $out .= $text; $added[] = $text; } } } return $out; } break; case "glpi_documenttypes.icon": if (!empty($data[$NAME . $num])) { return "<img class='middle' alt='' src='" . $CFG_GLPI["typedoc_icon_dir"] . "/" . $data[$NAME . $num] . "'>"; } return " "; case "glpi_documents.filename": $doc = new Document(); if ($doc->getFromDB($data['id'])) { return $doc->getDownloadLink(); } return NOT_AVAILABLE; case "glpi_deviceharddrives.specificity": case "glpi_devicememories.specificity": case "glpi_deviceprocessors.specificity": return $data[$NAME . $num]; case "glpi_networkports.mac": $out = ""; if ($itemtype == 'Computer') { $displayed = array(); if (!empty($data[$NAME . $num . "_2"])) { $split = explode("\$\$\$\$", $data[$NAME . $num . "_2"]); $count_display = 0; for ($k = 0; $k < count($split); $k++) { $lowstr = Toolbox::strtolower($split[$k]); if (strlen(trim($split[$k])) > 0 && !in_array($lowstr, $displayed)) { if ($count_display) { $out .= "<br>"; } $count_display++; $out .= $split[$k]; $displayed[] = $lowstr; } } if (!empty($data[$NAME . $num])) { $out .= "<br>"; } } if (!empty($data[$NAME . $num])) { $split = explode("\$\$\$\$", $data[$NAME . $num]); $count_display = 0; for ($k = 0; $k < count($split); $k++) { $lowstr = Toolbox::strtolower($split[$k]); if (strlen(trim($split[$k])) > 0 && !in_array($lowstr, $displayed)) { if ($count_display) { $out .= "<br>"; } $count_display++; $out .= $split[$k]; $displayed[] = $lowstr; } } } return $out; } break; case "glpi_contracts.duration": case "glpi_contracts.notice": case "glpi_contracts.periodicity": case "glpi_contracts.billing": if (!empty($data[$NAME . $num])) { $split = explode('$$$$', $data[$NAME . $num]); $output = ""; foreach ($split as $duration) { $output .= (empty($output) ? '' : '<br>') . sprintf(_n('%d month', '%d months', $duration), $duration); } return $output; } return " "; case "glpi_contracts.renewal": return Contract::getContractRenewalName($data[$NAME . $num]); // case "glpi_infocoms.sink_time" : // if (!empty($data[$NAME.$num])) { // $split = explode("$$$$", $data[$NAME.$num]); // $out = ''; // foreach ($split as $val) { // $out .= (empty($out)?'':'<br>'); // if ($val > 0) { // //TRANS: %d is a number of years // $out .= sprintf(_n('%d year', '%d years', $val), $val); // } // } // return $out; // } // return " "; // // case "glpi_infocoms.warranty_duration" : // if (!empty($data[$NAME.$num])) { // $split = explode("$$$$", $data[$NAME.$num]); // $out = ''; // foreach ($split as $val) { // $out .= (empty($out)?'':'<br>'); // if ($val > 0) { // $out .= sprintf(_n('%d month', '%d months', $val), $val); // } // if ($val < 0) { // $out .= __('Lifelong'); // } // } // return $out; // } // return " "; // case "glpi_infocoms.sink_time" : // if (!empty($data[$NAME.$num])) { // $split = explode("$$$$", $data[$NAME.$num]); // $out = ''; // foreach ($split as $val) { // $out .= (empty($out)?'':'<br>'); // if ($val > 0) { // //TRANS: %d is a number of years // $out .= sprintf(_n('%d year', '%d years', $val), $val); // } // } // return $out; // } // return " "; // // case "glpi_infocoms.warranty_duration" : // if (!empty($data[$NAME.$num])) { // $split = explode("$$$$", $data[$NAME.$num]); // $out = ''; // foreach ($split as $val) { // $out .= (empty($out)?'':'<br>'); // if ($val > 0) { // $out .= sprintf(_n('%d month', '%d months', $val), $val); // } // if ($val < 0) { // $out .= __('Lifelong'); // } // } // return $out; // } // return " "; case "glpi_infocoms.sink_type": $split = explode("\$\$\$\$", $data[$NAME . $num]); $out = ''; foreach ($split as $val) { $out .= (empty($out) ? '' : '<br>') . Infocom::getAmortTypeName($val); } return $out; case "glpi_infocoms.alert": if ($data[$NAME . $num] == pow(2, Alert::END)) { return __s('Warranty expiration date'); } return ""; case "glpi_contracts.alert": switch ($data[$NAME . $num]) { case pow(2, Alert::END): return __('End'); case pow(2, Alert::NOTICE): return __('Notice'); case pow(2, Alert::END) + pow(2, Alert::NOTICE): return __('End + Notice'); } return ""; case "glpi_tickets_tickets.tickets_id_1": $out = ""; $split = explode("\$\$\$\$", $data[$NAME . $num]); $split2 = explode("\$\$\$\$", $data[$NAME . $num . "_2"]); $displayed = array(); for ($k = 0; $k < count($split); $k++) { $linkid = $split[$k] == $data['id'] ? $split2[$k] : $split[$k]; if ($linkid > 0 && !isset($displayed[$linkid])) { $text = "<a "; $text .= "href=\"" . $CFG_GLPI["root_doc"] . "/front/ticket.form.php?id={$linkid}\">"; $text .= Dropdown::getDropdownName('glpi_tickets', $linkid) . "</a>"; if (count($displayed)) { $out .= "<br>"; } $displayed[$linkid] = $linkid; $out .= $text; } } return $out; case "glpi_problems.count": if ($data[$NAME . $num] > 0 && Session::haveRight("problem", Problem::READALL)) { if ($itemtype == 'ITILCategory') { $options['field'][0] = 7; $options['searchtype'][0] = 'equals'; $options['contains'][0] = $data['id']; $options['link'][0] = 'AND'; } $options['reset'] = 'reset'; $out = "<a id='problem{$itemtype}" . $data['id'] . "' "; $out .= "href=\"" . $CFG_GLPI["root_doc"] . "/front/problem.php?" . Toolbox::append_params($options, '&') . "\">"; $out .= $data[$NAME . $num] . "</a>"; } else { $out = $data[$NAME . $num]; } return $out; case "glpi_tickets.count": if ($data[$NAME . $num] > 0 && Session::haveRight("ticket", Ticket::READALL)) { if ($itemtype == 'User') { $options['field'][0] = 4; $options['searchtype'][0] = 'equals'; $options['contains'][0] = $data['id']; $options['link'][0] = 'AND'; $options['field'][1] = 22; $options['searchtype'][1] = 'equals'; $options['contains'][1] = $data['id']; $options['link'][1] = 'OR'; $options['field'][2] = 5; $options['searchtype'][2] = 'equals'; $options['contains'][2] = $data['id']; $options['link'][2] = 'OR'; } else { if ($itemtype == 'ITILCategory') { $options['field'][0] = 7; $options['searchtype'][0] = 'equals'; $options['contains'][0] = $data['id']; $options['link'][0] = 'AND'; } else { $options['field'][0] = 12; $options['searchtype'][0] = 'equals'; $options['contains'][0] = 'all'; $options['link'][0] = 'AND'; $options['itemtype2'][0] = $itemtype; $options['field2'][0] = self::getOptionNumber($itemtype, 'name'); $options['searchtype2'][0] = 'equals'; $options['contains2'][0] = $data['id']; $options['link2'][0] = 'AND'; } } $options['reset'] = 'reset'; $out = "<a id='ticket{$itemtype}" . $data['id'] . "' "; $out .= "href=\"" . $CFG_GLPI["root_doc"] . "/front/ticket.php?" . Toolbox::append_params($options, '&') . "\">"; $out .= $data[$NAME . $num] . "</a>"; } else { $out = $data[$NAME . $num]; } return $out; case "glpi_tickets.due_date": // Due date + progress if ($ID == 151) { $out = Html::convDate($data[$NAME . $num]); // No due date in waiting status if ($data[$NAME . $num . '_2'] == CommonITILObject::WAITING) { return ''; } if (empty($data[$NAME . $num])) { return ''; } if ($data[$NAME . $num . '_2'] == Ticket::SOLVED || $data[$NAME . $num . '_2'] == Ticket::CLOSED) { return $data[$NAME . $num]; } $ticket = new Ticket(); $ticket->getFromDB($data['ITEM_0']); $percentage = 0; $totaltime = 0; $currenttime = 0; if ($ticket->fields['slas_id'] != 0) { // Have SLA $sla = new SLA(); $sla->getFromDB($ticket->fields['slas_id']); $currenttime = $sla->getActiveTimeBetween($ticket->fields['date'], date('Y-m-d H:i:s')); $totaltime = $sla->getActiveTimeBetween($ticket->fields['date'], $data[$NAME . $num]); } else { $calendars_id = Entity::getUsedConfig('calendars_id', $ticket->fields['entities_id']); if ($calendars_id != 0) { // Ticket entity have calendar $calendar = new Calendar(); $calendar->getFromDB($calendars_id); $currenttime = $calendar->getActiveTimeBetween($ticket->fields['date'], date('Y-m-d H:i:s')); $totaltime = $calendar->getActiveTimeBetween($ticket->fields['date'], $data[$NAME . $num]); } else { // No calendar $currenttime = strtotime(date('Y-m-d H:i:s')) - strtotime($ticket->fields['date']); $totaltime = strtotime($data[$NAME . $num]) - strtotime($ticket->fields['date']); } } if ($totaltime != 0) { $percentage = round(100 * $currenttime / $totaltime); } else { // Total time is null : no active time $percentage = 100; } if ($percentage > 100) { $percentage = 100; } $percentage_text = $percentage; if ($_SESSION['glpiduedatewarning_unit'] == '%') { $less_warn_limit = $_SESSION['glpiduedatewarning_less']; $less_warn = 100 - $percentage; } else { if ($_SESSION['glpiduedatewarning_unit'] == 'hours') { $less_warn_limit = $_SESSION['glpiduedatewarning_less'] * HOUR_TIMESTAMP; $less_warn = $totaltime - $currenttime; } else { if ($_SESSION['glpiduedatewarning_unit'] == 'days') { $less_warn_limit = $_SESSION['glpiduedatewarning_less'] * DAY_TIMESTAMP; $less_warn = $totaltime - $currenttime; } } } if ($_SESSION['glpiduedatecritical_unit'] == '%') { $less_crit_limit = $_SESSION['glpiduedatecritical_less']; $less_crit = 100 - $percentage; } else { if ($_SESSION['glpiduedatecritical_unit'] == 'hours') { $less_crit_limit = $_SESSION['glpiduedatecritical_less'] * HOUR_TIMESTAMP; $less_crit = $totaltime - $currenttime; } else { if ($_SESSION['glpiduedatecritical_unit'] == 'days') { $less_crit_limit = $_SESSION['glpiduedatecritical_less'] * DAY_TIMESTAMP; $less_crit = $totaltime - $currenttime; } } } $color = $_SESSION['glpiduedateok_color']; if ($less_crit < $less_crit_limit) { $color = $_SESSION['glpiduedatecritical_color']; } else { if ($less_warn < $less_warn_limit) { $color = $_SESSION['glpiduedatewarning_color']; } } //Calculate bar progress $out .= "<div class='center' style='background-color: #ffffff; width: 100%;\n border: 1px solid #9BA563;' >"; $out .= "<div style='position:absolute;'> " . $percentage_text . "%</div>"; $out .= "<div class='center' style='background-color: " . $color . ";\n width: " . $percentage . "%; height: 12px' ></div>"; $out .= "</div>"; return $out; } break; case "glpi_softwarelicenses.number": if ($data[$NAME . $num . "_2"] == -1) { return __('Unlimited'); } if (empty($data[$NAME . $num])) { return 0; } return $data[$NAME . $num]; case "glpi_auth_tables.name": return Auth::getMethodName($data[$NAME . $num], $data[$NAME . $num . "_2"], 1, $data[$NAME . $num . "_3"] . $data[$NAME . $num . "_4"]); case "glpi_reservationitems.comment": if (empty($data[$NAME . $num])) { return "<a title=\"" . __s('Modify the comment') . "\"\n href='" . $CFG_GLPI["root_doc"] . "/front/reservationitem.form.php?id=" . $data["refID"] . "' >" . __('None') . "</a>"; } return "<a title=\"" . __s('Modify the comment') . "\"\n href='" . $CFG_GLPI["root_doc"] . "/front/reservationitem.form.php?id=" . $data['refID'] . "' >" . Html::resume_text($data[$NAME . $num]) . "</a>"; case 'glpi_notifications.mode': return Notification::getMode($data[$NAME . $num]); case 'glpi_notifications.event': $item = NotificationTarget::getInstanceByType($data['itemtype']); if ($item) { $events = $item->getAllEvents(); if (isset($events[$data[$NAME . $num]])) { return $events[$data[$NAME . $num]]; } } return ''; case 'glpi_reminders.state': return Planning::getState($data[$NAME . $num]); case 'glpi_crontasks.description': $tmp = new CronTask(); return $tmp->getDescription($data['id']); case 'glpi_crontasks.state': return CronTask::getStateName($data[$NAME . $num]); case 'glpi_crontasks.mode': return CronTask::getModeName($data[$NAME . $num]); case 'glpi_crontasks.itemtype': if ($plug = isPluginItemType($data[$NAME . $num])) { return $plug['plugin']; } return ''; case 'glpi_changes.status': $status = Change::getStatus($data[$NAME . $num]); return "<img src=\"" . Change::getStatusIconURL($data[$NAME . $num]) . "\"\n alt=\"{$status}\" title=\"{$status}\"> {$status}"; case 'glpi_problems.status': $status = Problem::getStatus($data[$NAME . $num]); return "<img src=\"" . Problem::getStatusIconURL($data[$NAME . $num]) . "\"\n alt=\"{$status}\" title=\"{$status}\"> {$status}"; case 'glpi_tickets.status': $status = Ticket::getStatus($data[$NAME . $num]); return "<img src=\"" . Ticket::getStatusIconURL($data[$NAME . $num]) . "\"\n alt=\"{$status}\" title=\"{$status}\"> {$status}"; case 'glpi_tickets.items_id': if (!empty($data[$NAME . $num . "_2"]) && ($item = getItemForItemtype($data[$NAME . $num . "_2"]))) { if ($item->getFromDB($data[$NAME . $num])) { return $item->getLink(array('comments' => true)); } } return ' '; case 'glpi_tickets.name': if (isset($searchopt[$ID]['forcegroupby']) && $searchopt[$ID]['forcegroupby']) { $split = explode("\$\$\$\$", $data[$NAME . $num]); $out = ''; $link = Toolbox::getItemTypeFormURL('Ticket'); foreach ($split as $val) { if (!empty($val)) { $split2 = self::explodeWithID("\$\$", $val); $out .= "<a id='ticket" . $split2[1] . "' href=\"" . $link; $out .= strstr($link, '?') ? '&' : '?'; $out .= 'id=' . $split2[1]; $out .= "\">"; $name = $split2[0]; if ($_SESSION["glpiis_ids_visible"] || empty($split2[0])) { $name = sprintf(__('%1$s (%2$s)'), $name, $split2[1]); } $out .= $name . "</a><br>"; } } return $out; } $link = Toolbox::getItemTypeFormURL('Ticket'); $out = "<a id='ticket" . $data[$NAME . $num . "_2"] . "' href=\"" . $link; $out .= strstr($link, '?') ? '&' : '?'; $out .= 'id=' . $data[$NAME . $num . "_2"]; // Force solution tab if solved if ($data[$NAME . $num . "_4"] == CommonITILObject::SOLVED) { $out .= "&forcetab=Ticket\$2"; } $out .= "\">"; $name = $data[$NAME . $num]; if ($_SESSION["glpiis_ids_visible"] || empty($data[$NAME . $num])) { $name = sprintf(__('%1$s (%2$s)'), $name, $data[$NAME . $num . "_2"]); } $out .= $name . "</a>"; $out = sprintf(__('%1$s %2$s'), $out, Html::showToolTip(nl2br($data[$NAME . $num . "_3"]), array('applyto' => 'ticket' . $data[$NAME . $num . "_2"], 'display' => false))); return $out; case 'glpi_ticketvalidations.status': $split = explode("\$\$\$\$", $data[$NAME . $num]); $out = ''; foreach ($split as $val) { if (!empty($val)) { $split2 = self::explodeWithID("\$\$", $val); $status = TicketValidation::getStatus($split2[0]); $bgcolor = TicketValidation::getStatusColor($split2[0]); $out .= (empty($out) ? '' : '<br>') . "<div style=\"background-color:" . $bgcolor . ";\">" . $status . '</div>'; } } return $out; case 'glpi_ticketsatisfactions.type': return TicketSatisfaction::getTypeInquestName($data[$NAME . $num]); case 'glpi_ticketsatisfactions.satisfaction': return TicketSatisfaction::displaySatisfaction($data[$NAME . $num]); case 'glpi_notimportedemails.reason': return NotImportedEmail::getReason($data[$NAME . $num]); case 'glpi_notimportedemails.messageid': $clean = array('<' => '', '>' => ''); return strtr($data[$NAME . $num], $clean); } //// Default case // Link with plugin tables : need to know left join structure if (preg_match("/^glpi_plugin_([a-z0-9]+)/", $table . '.' . $field, $matches)) { if (count($matches) == 2) { $plug = $matches[1]; $function = 'plugin_' . $plug . '_giveItem'; if (function_exists($function)) { $out = $function($itemtype, $ID, $data, $num); if (!empty($out)) { return $out; } } } } $unit = ''; if (isset($searchopt[$ID]['unit'])) { $unit = $searchopt[$ID]['unit']; } /// TODO try to use getvalueToDisplay instead of redefine display system // Preformat items if (isset($searchopt[$ID]["datatype"])) { switch ($searchopt[$ID]["datatype"]) { case "itemlink": $linkitemtype = getItemTypeForTable($searchopt[$ID]["table"]); if (isset($data[$NAME . $num . "_2"]) && strlen($data[$NAME . $num . "_2"])) { $link = Toolbox::getItemTypeFormURL($linkitemtype); $out = "<a id='" . $itemtype . "_" . $data[$NAME . $num . "_2"] . "' href=\"" . $link; $out .= strstr($link, '?') ? '&' : '?'; $out .= 'id=' . $data[$NAME . $num . "_2"]; if (isset($searchopt[$ID]['forcetab'])) { $out .= "&forcetab=" . $searchopt[$ID]['forcetab']; } $out .= "\">"; $name = Dropdown::getValueWithUnit($data[$NAME . $num], $unit); if ($_SESSION["glpiis_ids_visible"] || empty($data[$NAME . $num])) { $name = sprintf(__('%1$s (%2$s)'), $name, $data[$NAME . $num . "_2"]); } $out .= $name . "</a>"; return $out; } $out = ""; $split = explode("\$\$\$\$", $data[$NAME . $num]); $count_display = 0; $separate = '<br>'; if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) { $separate = '<hr>'; } for ($k = 0; $k < count($split); $k++) { if (strlen(trim($split[$k])) > 0) { $split2 = self::explodeWithID("\$\$", $split[$k]); if (isset($split2[1]) && $split2[1] > 0) { if ($count_display) { $out .= $separate; } $count_display++; $page = Toolbox::getItemTypeFormURL($linkitemtype); $page .= strpos($page, '?') ? '&id' : '?id'; $name = Dropdown::getValueWithUnit($split2[0], $unit); if ($_SESSION["glpiis_ids_visible"] || empty($split2[0])) { $name = sprintf(__('%1$s (%2$s)'), $name, $split2[1]); } $out .= "<a id='" . $linkitemtype . "_" . $data['id'] . "_" . $split2[1] . "' href='{$page}=" . $split2[1] . "'>" . $name . "</a>"; } } } return $out; case "text": $separate = '<br>'; if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) { $separate = '<hr>'; } $split = explode("\$\$\$\$", $data[$NAME . $num]); $out = ''; $count_display = 0; foreach ($split as $val) { if (strlen(trim($val)) > 0) { $split2 = self::explodeWithID("\$\$", $val); if ($count_display) { $out .= $separate; } $count_display++; if (isset($searchopt[$ID]['htmltext']) && $searchopt[$ID]['htmltext']) { $text = Html::clean(Toolbox::unclean_cross_side_scripting_deep(nl2br($split2[0]))); } else { $text = nl2br($split2[0]); } if (self::$output_type == self::HTML_OUTPUT && Toolbox::strlen($text) > $CFG_GLPI['cut']) { $rand = mt_rand(); $out .= sprintf(__('%1$s %2$s'), "<span id='text{$rand}'>" . Html::resume_text($text, $CFG_GLPI['cut']) . '</span>', Html::showToolTip($text, array('applyto' => "text{$rand}", 'display' => false))); } else { $out .= $text; } } } return $out; case "date": case "date_delay": $split = explode("\$\$\$\$", $data[$NAME . $num]); $out = ''; foreach ($split as $val) { $out .= (empty($out) ? '' : '<br>') . Html::convDate($val); } return $out; case "datetime": $split = explode("\$\$\$\$", $data[$NAME . $num]); $out = ''; foreach ($split as $val) { $out .= (empty($out) ? '' : '<br>') . Html::convDateTime($val); } return $out; case "timestamp": $withseconds = false; if (isset($searchopt[$ID]['withseconds'])) { $withseconds = $searchopt[$ID]['withseconds']; } $withdays = true; if (isset($searchopt[$ID]['withdays'])) { $withdays = $searchopt[$ID]['withdays']; } $split = explode("\$\$\$\$", $data[$NAME . $num]); $out = ''; foreach ($split as $val) { $out .= (empty($out) ? '' : '<br>') . Html::timestampToString($val, $withseconds, $withdays); } return $out; case "email": $split = explode('$$$$', $data[$NAME . $num]); $out = ''; $count_display = 0; foreach ($split as $val) { $split2 = self::explodeWithID("\$\$", $val); if ($count_display) { $out .= "<br>"; } $count_display++; if (!empty($val)) { $out .= empty($out) ? '' : '<br>'; $out .= "<a href='mailto:{$split2['0']}'>{$split2['0']}</a>"; } } return empty($out) ? " " : $out; case "weblink": $orig_link = trim($data[$NAME . $num]); if (!empty($orig_link)) { // strip begin of link $link = preg_replace('/https?:\\/\\/(www[^\\.]*\\.)?/', '', $orig_link); $link = preg_replace('/\\/$/', '', $link); if (Toolbox::strlen($link) > $CFG_GLPI["url_maxlength"]) { $link = Toolbox::substr($link, 0, $CFG_GLPI["url_maxlength"]) . "..."; } return "<a href=\"" . formatOutputWebLink($orig_link) . "\" target='_blank'>{$link}</a>"; } return " "; case "number": if (isset($searchopt[$ID]['forcegroupby']) && $searchopt[$ID]['forcegroupby']) { $out = ""; $split = explode("\$\$\$\$", $data[$NAME . $num]); $count_display = 0; for ($k = 0; $k < count($split); $k++) { if (strlen(trim($split[$k])) > 0) { $split2 = self::explodeWithID("\$\$", $split[$k]); if ($count_display) { $out .= "<br>"; } $count_display++; if (isset($searchopt[$ID]['toadd']) && isset($searchopt[$ID]['toadd'][$split2[0]])) { $out .= $searchopt[$ID]['toadd'][$split2[0]]; } else { $number = str_replace(' ', ' ', Html::formatNumber($split2[0], false, 0)); $out .= Dropdown::getValueWithUnit($number, $unit); } } } return $out; } if (isset($searchopt[$ID]['toadd']) && isset($searchopt[$ID]['toadd'][$data[$NAME . $num]])) { return $searchopt[$ID]['toadd'][$data[$NAME . $num]]; } else { $number = str_replace(' ', ' ', Html::formatNumber($data[$NAME . $num], false, 0)); return Dropdown::getValueWithUnit($number, $unit); } case "decimal": if (isset($searchopt[$ID]['forcegroupby']) && $searchopt[$ID]['forcegroupby']) { $out = ""; $split = explode("\$\$\$\$", $data[$NAME . $num]); $count_display = 0; for ($k = 0; $k < count($split); $k++) { if (strlen(trim($split[$k])) > 0) { $split2 = self::explodeWithID("\$\$", $split[$k]); if ($count_display) { $out .= "<br>"; } $count_display++; if (isset($searchopt[$ID]['toadd']) && isset($searchopt[$ID]['toadd'][$split2[0]])) { $out .= $searchopt[$ID]['toadd'][$split2[0]]; } else { $number = str_replace(' ', ' ', Html::formatNumber($split2[0])); $out .= Dropdown::getValueWithUnit($number, $unit); } } } return $out; } $number = str_replace(' ', ' ', Html::formatNumber($data[$NAME . $num])); return Dropdown::getValueWithUnit($number, $unit); case "bool": if (isset($searchopt[$ID]['forcegroupby']) && $searchopt[$ID]['forcegroupby']) { $out = ""; $split = explode("\$\$\$\$", $data[$NAME . $num]); $count_display = 0; for ($k = 0; $k < count($split); $k++) { if (strlen(trim($split[$k])) > 0) { $split2 = self::explodeWithID("\$\$", $split[$k]); if ($count_display) { $out .= "<br>"; } $count_display++; $out .= Dropdown::getValueWithUnit(Dropdown::getYesNo($split2[0]), $unit); } } return $out; } return Dropdown::getValueWithUnit(Dropdown::getYesNo($data[$NAME . $num]), $unit); case "right": return Profile::getRightValue($data[$NAME . $num]); case "itemtypename": if ($obj = getItemForItemtype($data[$NAME . $num])) { return $obj->getTypeName(); } return ""; case "language": if (isset($CFG_GLPI['languages'][$data[$NAME . $num]])) { return $CFG_GLPI['languages'][$data[$NAME . $num]][0]; } return __('Default value'); } } // Manage items with need group by / group_concat if (isset($searchopt[$ID]['forcegroupby']) && $searchopt[$ID]['forcegroupby']) { $out = ""; $split = explode("\$\$\$\$", $data[$NAME . $num]); $count_display = 0; $separate = '<br>'; if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) { $separate = '<hr>'; } for ($k = 0; $k < count($split); $k++) { if (strlen(trim($split[$k])) > 0) { if ($count_display) { $out .= $separate; } $withoutid = self::explodeWithID("\$\$", $split[$k]); $count_display++; // Get specific display if available $itemtype = getItemTypeForTable($table); if ($item = getItemForItemtype($itemtype)) { $tmpdata = array($field => $withoutid[0]); $specific = $item->getSpecificValueToDisplay($field, $tmpdata, array('html' => true)); } if (!empty($specific)) { $out .= $specific; } else { $out .= Dropdown::getValueWithUnit($withoutid[0], $unit); } } } return $out; } // Get specific display if available $itemtype = getItemTypeForTable($table); if ($item = getItemForItemtype($itemtype)) { $tmpdata = array($field => $data[$NAME . $num]); if (isset($searchopt[$ID]['additionalfields']) && count($searchopt[$ID]['additionalfields'])) { foreach ($searchopt[$ID]['additionalfields'] as $key) { $tmpdata[$key] = $data[$NAME . $num . '_' . $key]; } } $specific = $item->getSpecificValueToDisplay($field, $tmpdata, array('html' => true)); if (!empty($specific)) { return $specific; } } // Manage auto CONCAT id $split = self::explodeWithID('$$', $data[$NAME . $num]); $split[0] = trim($split[0]); if (isset($searchopt[$ID]['toadd']) && isset($searchopt[$ID]['toadd'][$split[0]])) { return $searchopt[$ID]['toadd'][$split[0]]; } // Empty is 0 or empty if (empty($split[0]) && isset($searchopt[$ID]['emptylabel'])) { return $searchopt[$ID]['emptylabel']; } return Dropdown::getValueWithUnit($split[0], $unit); }
function _addContactUser($a_contacts, $users_id, $i) { $pmContact = new PluginMonitoringContact(); $pmNotificationcommand = new PluginMonitoringNotificationcommand(); $pmContacttemplate = new PluginMonitoringContacttemplate(); $user = new User(); $calendar = new Calendar(); $user->getFromDB($users_id); // Get contact template $a_pmcontact = current($pmContact->find("`users_id`='".$users_id."'", "", 1)); if (empty($a_pmcontact) OR (isset($a_pmcontact['plugin_monitoring_contacttemplates_id']) AND $a_pmcontact['plugin_monitoring_contacttemplates_id'] == '0')) { // Use default template $a_pmcontact = current($pmContacttemplate->find("`is_default`='1'", "", 1)); } else { // Use contact defined template $a_pmcontact = current($pmContacttemplate->find("`id`='".$a_pmcontact['plugin_monitoring_contacttemplates_id']."'", "", 1)); } $a_contacts[$i]['contact_name'] = $user->fields['name']; $a_contacts[$i]['alias'] = $user->getName(); PluginMonitoringToolbox::logIfExtradebug( 'pm-shinken', "- contact ".$user->fields['name']." - ".$user->getName()."\n" ); // Toolbox::logInFile("pm-contacts", "- contact ".serialize($user->fields)."\n"); if (!isset($a_pmcontact['host_notification_period'])) { $a_calendars = current($calendar->find("", "", 1)); $cal = '24x7'; if (isset($a_calendars['name'])) { $cal = $a_calendars['name']; } $a_pmcontact['host_notifications_enabled'] = '0'; $a_pmcontact['service_notifications_enabled'] = '0'; $a_pmcontact['service_notification_period'] = $cal; $a_pmcontact['host_notification_period'] = $cal; $a_pmcontact['service_notification_options_w'] = '0'; $a_pmcontact['service_notification_options_u'] = '0'; $a_pmcontact['service_notification_options_c'] = '0'; $a_pmcontact['service_notification_options_r'] = '0'; $a_pmcontact['service_notification_options_f'] = '0'; $a_pmcontact['service_notification_options_n'] = '0'; $a_pmcontact['host_notification_options_d'] = '0'; $a_pmcontact['host_notification_options_u'] = '0'; $a_pmcontact['host_notification_options_r'] = '0'; $a_pmcontact['host_notification_options_f'] = '0'; $a_pmcontact['host_notification_options_s'] = '0'; $a_pmcontact['host_notification_options_n'] = '0'; $a_pmcontact['service_notification_commands'] = '2'; $a_pmcontact['host_notification_commands'] = '1'; } $a_contacts[$i]['host_notifications_enabled'] = $a_pmcontact['host_notifications_enabled']; $a_contacts[$i]['service_notifications_enabled'] = $a_pmcontact['service_notifications_enabled']; $calendar->getFromDB($a_pmcontact['service_notification_period']); if (isset($calendar->fields['name'])) { $a_contacts[$i]['service_notification_period'] = $calendar->fields['name']; } else { $a_contacts[$i]['service_notification_period'] = '24x7'; } $calendar->getFromDB($a_pmcontact['host_notification_period']); if (isset($calendar->fields['name'])) { $a_contacts[$i]['host_notification_period'] = $calendar->fields['name']; } else { $a_contacts[$i]['host_notification_period'] = '24x7'; } $a_servicenotif = array(); if ($a_pmcontact['service_notification_options_w'] == '1') $a_servicenotif[] = "w"; if ($a_pmcontact['service_notification_options_u'] == '1') $a_servicenotif[] = "u"; if ($a_pmcontact['service_notification_options_c'] == '1') $a_servicenotif[] = "c"; if ($a_pmcontact['service_notification_options_r'] == '1') $a_servicenotif[] = "r"; if ($a_pmcontact['service_notification_options_f'] == '1') $a_servicenotif[] = "f"; if ($a_pmcontact['service_notification_options_n'] == '1') $a_servicenotif = array("n"); if (count($a_servicenotif) == "0") $a_servicenotif = array("n"); $a_contacts[$i]['service_notification_options'] = implode(",", $a_servicenotif); $a_hostnotif = array(); if ($a_pmcontact['host_notification_options_d'] == '1') $a_hostnotif[] = "d"; if ($a_pmcontact['host_notification_options_u'] == '1') $a_hostnotif[] = "u"; if ($a_pmcontact['host_notification_options_r'] == '1') $a_hostnotif[] = "r"; if ($a_pmcontact['host_notification_options_f'] == '1') $a_hostnotif[] = "f"; if ($a_pmcontact['host_notification_options_s'] == '1') $a_hostnotif[] = "s"; if ($a_pmcontact['host_notification_options_n'] == '1') $a_hostnotif = array("n"); if (count($a_hostnotif) == "0") $a_hostnotif = array("n"); $a_contacts[$i]['host_notification_options'] = implode(",", $a_hostnotif); $pmNotificationcommand->getFromDB($a_pmcontact['service_notification_commands']); if (isset($pmNotificationcommand->fields['command_name'])) { $a_contacts[$i]['service_notification_commands'] = PluginMonitoringCommand::$command_prefix . $pmNotificationcommand->fields['command_name']; } else { $a_contacts[$i]['service_notification_commands'] = ''; } $pmNotificationcommand->getFromDB($a_pmcontact['host_notification_commands']); if (isset($pmNotificationcommand->fields['command_name'])) { $a_contacts[$i]['host_notification_commands'] = PluginMonitoringCommand::$command_prefix . $pmNotificationcommand->fields['command_name']; } else { $a_contacts[$i]['host_notification_commands'] = ''; } // Get first email $a_emails = UserEmail::getAllForUser($users_id); $first = 0; foreach ($a_emails as $email) { if ($first == 0) { $a_contacts[$i]['email'] = $email; } $first++; } if (!isset($a_contacts[$i]['email'])) { $a_contacts[$i]['email'] = ''; } $a_contacts[$i]['pager'] = $user->fields['phone']; if (isset($a_pmcontact['shinken_administrator'])) { $a_contacts[$i]['is_admin'] = $a_pmcontact['shinken_administrator']; } else { $a_contacts[$i]['is_admin'] = self::$shinkenParameters['webui']['contacts']['is_admin']; } if (isset($a_pmcontact['shinken_can_submit_commands'])) { $a_contacts[$i]['can_submit_commands'] = $a_pmcontact['shinken_can_submit_commands']; } else { $a_contacts[$i]['can_submit_commands'] = self::$shinkenParameters['webui']['contacts']['can_submit_commands']; } if (empty($user->fields['password'])) { $a_contacts[$i]['password'] = self::$shinkenParameters['webui']['contacts']['password']; } else { $a_contacts[$i]['password'] = $user->fields['password']; } /* TODO: address1, address2, ..., address6 are available in Shinken */ return $a_contacts; }
private function groups($closed = true) { global $DB; $DB->connect(); $a_storedate_temp = self::$storedate; $a_states = getAllDatasFromTable('glpi_plugin_timelineticket_assigngroups', '', FALSE, 'id'); $this->assertEquals(3, count($a_states), 'Number of lines in assigngroup table of plugin'); $ticket = new Ticket(); $calendar = new Calendar(); $ticket->getFromDB(1); $calendars_id = EntityData::getUsedConfig('calendars_id', $ticket->fields['entities_id']); // * 07/ if ($calendars_id > 0 && $calendar->getFromDB($calendars_id)) { $begin = $calendar->getActiveTimeBetween($ticket->fields['date'], $a_storedate_temp[3]); } else { // case 24/24 - 7/7 $begin = strtotime($a_storedate_temp[3]) - strtotime($ticket->fields['date']); } $a_ref = array('id' => '1', 'tickets_id' => '1', 'date' => $a_storedate_temp[3], 'groups_id' => '1', 'begin' => $begin, 'delay' => strtotime($a_storedate_temp[7]) - strtotime($a_storedate_temp[3])); $this->assertEquals($a_ref, $a_states[1], '(07/) Group 1'); // * 14/ if ($calendars_id > 0 && $calendar->getFromDB($calendars_id)) { $begin = $calendar->getActiveTimeBetween($ticket->fields['date'], $a_storedate_temp[9]); } else { // case 24/24 - 7/7 $begin = strtotime($a_storedate_temp[9]) - strtotime($ticket->fields['date']); } $a_ref = array('id' => '2', 'tickets_id' => '1', 'date' => $a_storedate_temp[9], 'groups_id' => '2', 'begin' => $begin, 'delay' => strtotime($a_storedate_temp[13]) - strtotime($a_storedate_temp[9])); $this->assertEquals($a_ref, $a_states[2], '(14/) Group 2'); // * 20/ if ($calendars_id > 0 && $calendar->getFromDB($calendars_id)) { $begin = $calendar->getActiveTimeBetween($ticket->fields['date'], $a_storedate_temp[13]); } else { // case 24/24 - 7/7 $begin = strtotime($a_storedate_temp[13]) - strtotime($ticket->fields['date']); } $a_ref = array('id' => '3', 'tickets_id' => '1', 'date' => $a_storedate_temp[13], 'groups_id' => '1', 'begin' => $begin, 'delay' => NULL); $this->assertEquals($a_ref, $a_states[3], '(20/) Group 1'); }