static function displayLine($data, $displayhost = 1) { global $DB, $CFG_GLPI; $pMonitoringService = new PluginMonitoringService(); $networkPort = new NetworkPort(); $pMonitoringComponent = new PluginMonitoringComponent(); $pmComponentscatalog_Host = new PluginMonitoringComponentscatalog_Host(); $entity = new Entity(); $pMonitoringService->getFromDB($data['id']); echo "<td width='32' class='center'>"; $shortstate = self::getState($data['state'], $data['state_type'], $data['event'], $data['is_acknowledged']); $alt = __('Ok', 'monitoring'); if ($shortstate == 'orange') { $alt = __('Warning (data)', 'monitoring'); } else { if ($shortstate == 'yellow') { $alt = __('Warning (connection)', 'monitoring'); } else { if ($shortstate == 'red') { $alt = __('Critical', 'monitoring'); } else { if ($shortstate == 'redblue') { $alt = __('Critical / Acknowledge', 'monitoring'); } } } } echo "<img src='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/pics/box_" . $shortstate . "_32.png'\n title='" . $alt . "' alt='" . $alt . "' />"; echo "</td>"; echo "<td>"; $entity->getFromDB($data['entities_id']); echo $entity->fields['completename']; echo "</td>"; $pMonitoringComponent->getFromDB($data['plugin_monitoring_components_id']); echo "<td class='center'>"; $timezone = '0'; if (isset($_SESSION['plugin_monitoring_timezone'])) { $timezone = $_SESSION['plugin_monitoring_timezone']; } if ($pMonitoringComponent->fields['graph_template'] != '') { echo "<a href='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/display.form.php?itemtype=PluginMonitoringService&items_id=" . $data['id'] . "'>"; $pmServicegraph = new PluginMonitoringServicegraph(); ob_start(); $pmServicegraph->displayGraph($pMonitoringComponent->fields['graph_template'], "PluginMonitoringService", $data['id'], "0", '2h', "div", "600"); $div = ob_get_contents(); ob_end_clean(); $chart = "<table width='600' class='tab_cadre'><tr><td>" . $div . "</td></tr></table>"; Html::showToolTip($chart, array('img' => $CFG_GLPI['root_doc'] . "/plugins/monitoring/pics/stats_32.png")); $pmServicegraph->displayGraph($pMonitoringComponent->fields['graph_template'], "PluginMonitoringService", $data['id'], "0", '2h', "js"); } echo "</a>"; echo "</td>"; if ($displayhost == '1') { $pmComponentscatalog_Host->getFromDB($data["plugin_monitoring_componentscatalogs_hosts_id"]); if (isset($pmComponentscatalog_Host->fields['itemtype']) and $pmComponentscatalog_Host->fields['itemtype'] != '') { $itemtype = $pmComponentscatalog_Host->fields['itemtype']; $item = new $itemtype(); $item->getFromDB($pmComponentscatalog_Host->fields['items_id']); echo "<td>"; echo $item->getTypeName() . " : " . $item->getLink(); if (!is_null($pMonitoringService->fields['networkports_id']) and $pMonitoringService->fields['networkports_id'] > 0) { $networkPort->getFromDB($pMonitoringService->fields['networkports_id']); echo " [" . $networkPort->getLink() . "]"; } echo "</td>"; } else { echo "<td>" . __('Resources', 'monitoring') . "</td>"; } } echo "<td>" . $pMonitoringComponent->getLink(); if (!is_null($pMonitoringService->fields['networkports_id']) and $pMonitoringService->fields['networkports_id'] > 0) { $networkPort->getFromDB($pMonitoringService->fields['networkports_id']); echo " [" . $networkPort->getLink() . "]"; } echo "</td>"; // $nameitem = ''; // if (isset($itemmat->fields['name'])) { // $nameitem = "[".$itemmat->getLink(1)."]"; // } //if ($pMonitoringService->fields['plugin_monitoring_services_id'] == '0') { //echo "<td>".$itemmat->getLink(1)."</td>"; // } else { // $pMonitoringServiceH->getFromDB($pMonitoringService->fields['plugin_monitoring_services_id']); // $itemtypemat = $pMonitoringServiceH->fields['itemtype']; // $itemmat = new $itemtypemat(); // $itemmat->getFromDB($pMonitoringServiceH->fields['items_id']); // echo "<td>".$pMonitoringService->getLink(1).$nameitem." ".__('on', 'monitoring')." ".$itemmat->getLink(1)."</td>"; // } // unset($itemmat); echo "<td class='center'>"; if ($shortstate == 'red') { echo "<table>"; echo "<tr>"; echo "<td>"; echo $data['state']; echo "</td>"; echo "<td>"; echo "<a href='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/acknowledge.form.php?id=" . $data['id'] . "'>" . "<img src='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/pics/acknowledge_checked.png'" . " alt='" . __('Define an acknowledge', 'monitoring') . "'" . " title='" . __('Define an acknowledge', 'monitoring') . "'/>" . "</a>"; echo "</td>"; echo "</tr>"; echo "</table>"; } else { echo $data['state']; } echo "</td>"; echo "<td>"; echo Html::convDate($data['last_check']) . ' ' . substr($data['last_check'], 11, 8); echo "</td>"; echo "<td>"; echo $data['event']; echo "</td>"; echo "<td align='center'>"; $segments = CalendarSegment::getSegmentsBetween($pMonitoringComponent->fields['calendars_id'], date('w', date('U')), date('H:i:s'), date('w', date('U')), date('H:i:s')); if (count($segments) == '0') { echo "<img src='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/pics/service_pause.png' />"; } else { echo "<img src='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/pics/service_run.png' />"; } echo "</td>"; if ($displayhost == '0') { $pmUnavaibility = new PluginMonitoringUnavaibility(); $pmUnavaibility->displayValues($pMonitoringService->fields['id'], 'currentmonth', 1); $pmUnavaibility->displayValues($pMonitoringService->fields['id'], 'lastmonth', 1); $pmUnavaibility->displayValues($pMonitoringService->fields['id'], 'currentyear', 1); echo "<td class='center'>"; echo "<a href='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/unavaibility.php?" . "field[0]=2&searchtype[0]=equals&contains[0]=" . $pMonitoringService->fields['id'] . "&sort=3&order=DESC&itemtype=PluginMonitoringUnavaibility'>\n <img src='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/pics/info.png'/></a>"; echo "</td>"; } echo "<td>"; if ($shortstate == 'redblue') { echo "<i>" . _n('User', 'Users', 1) . " : </i>"; $user = new User(); $user->getFromDB($data['acknowledge_users_id']); echo $user->getName(1); echo "<br/>"; echo "<i>" . __('Comments') . " : </i>" . $data['acknowledge_comment']; } echo "</td>"; if ($displayhost == '0') { echo "<td>"; if (PluginMonitoringProfile::haveRight("componentscatalog", 'w')) { $a_arg = importArrayFromDB($pMonitoringService->fields['arguments']); $cnt = ''; if (count($a_arg) > 0) { $cnt = " (" . count($a_arg) . ")"; } echo "<a href='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/servicearg.form.php?id=" . $data['id'] . "'>" . __('Configure', 'monitoring') . $cnt . "</a>"; } echo "</td>"; } }
/** * Get comments for host * $id, host id * default is current host instance * */ function getComments($id=-1) { global $CFG_GLPI; if ($id == -1) { $pm_Host = $this; } else { $pm_Host = new PluginMonitoringHost(); $pm_Host->getFromDB($id); } // Toolbox::logInFile("pm", "Host getcomments : $id : ".$pm_Host->getID()."\n"); $comment = ""; $toadd = array(); // associated computer ... $item = new $pm_Host->fields['itemtype']; $item->getFromDB($pm_Host->fields['items_id']); if ($pm_Host->getField('itemtype') == 'Computer') { if ($item->isField('completename')) { $toadd[] = array('name' => __('Complete name'), 'value' => nl2br($item->getField('completename'))); } $type = new ComputerType(); if ($item->getField("computertypes_id")) { $type->getFromDB($item->getField("computertypes_id")); $type = $type->getName(); if (! empty($type)) { $toadd[] = array('name' => __('Type'), 'value' => nl2br($type)); } } else { return $comment; } $model = new ComputerModel(); if ($item->getField("computermodels_id")) { $model->getFromDB($item->getField("computermodels_id")); $model = $model->getName(); if (! empty($model)) { $toadd[] = array('name' => __('Model'), 'value' => nl2br($model)); } } $state = new State(); $state->getFromDB($item->fields["states_id"]); $state = $state->getName(); if (! empty($state)) { $toadd[] = array('name' => __('State'), 'value' => nl2br($state)); } $entity = new Entity(); $entity->getFromDB($item->fields["entities_id"]); $entity = $entity->getName(); if (! empty($entity)) { $toadd[] = array('name' => __('Entity'), 'value' => nl2br($entity)); } $location = new Location(); $location->getFromDB($item->fields["locations_id"]); $location = $location->getName(array('complete' => true)); if (! empty($location)) { $toadd[] = array('name' => __('Location'), 'value' => nl2br($location)); } if (! empty($item->fields["serial"])) { $toadd[] = array('name' => __('Serial'), 'value' => nl2br($item->fields["serial"])); } if (! empty($item->fields["otherserial"])) { $toadd[] = array('name' => __('Inventory number'), 'value' => nl2br($item->fields["otherserial"])); } if (($pm_Host instanceof CommonDropdown) && $pm_Host->isField('comment')) { $toadd[] = array('name' => __('Comments'), 'value' => nl2br($pm_Host->getField('comment'))); } if (count($toadd)) { foreach ($toadd as $data) { $comment .= sprintf(__('%1$s: %2$s')."<br>", "<span class='b'>".$data['name'], "</span>".$data['value']); } } } else { $toadd[] = array('name' => __('Host type'), 'value' => nl2br($item->getTypeName())); if ($item->isField('completename')) { $toadd[] = array('name' => __('Complete name'), 'value' => nl2br($item->getField('completename'))); } } if (!empty($comment)) { return Html::showToolTip($comment, array('display' => false)); } }
along with GLPI. If not, see <http://www.gnu.org/licenses/>. -------------------------------------------------------------------------- */ /** @file * @brief */ // Direct access to file if (strpos($_SERVER['PHP_SELF'], "ticketsatisfaction.php")) { $AJAX_INCLUDE = 1; include '../inc/includes.php'; header("Content-Type: text/html; charset=UTF-8"); Html::header_nocache(); } $entity = new Entity(); if (isset($_POST['inquest_config']) && isset($_POST['entities_id'])) { if ($entity->getFromDB($_POST['entities_id'])) { $inquest_config = $entity->getfield('inquest_config'); $inquest_delay = $entity->getfield('inquest_delay'); $inquest_rate = $entity->getfield('inquest_rate'); $inquest_duration = $entity->getfield('inquest_duration'); $max_closedate = $entity->getfield('max_closedate'); } else { $inquest_config = $_POST['inquest_config']; $inquest_delay = -1; $inquest_rate = -1; $inquest_duration = -1; $max_closedate = ''; } if ($_POST['inquest_config'] > 0) { echo "<table class='tab_cadre_fixe' width='50%'>"; echo "<tr class='tab_bg_1'><td width='50%'>" . __('Create survey after') . "</td>";
/** * @param $item CommonDBTM object * @param $options array * @param $simple (false by default) **/ function getDatasForObject(CommonDBTM $item, array $options, $simple = false) { global $CFG_GLPI, $DB; $objettype = strtolower($item->getType()); $datas["##{$objettype}.title##"] = $item->getField('name'); $datas["##{$objettype}.content##"] = $item->getField('content'); $datas["##{$objettype}.description##"] = $item->getField('content'); $datas["##{$objettype}.id##"] = sprintf("%07d", $item->getField("id")); $datas["##{$objettype}.url##"] = $this->formatURL($options['additionnaloption']['usertype'], $objettype . "_" . $item->getField("id")); $datas["##{$objettype}.urlapprove##"] = $this->formatURL($options['additionnaloption']['usertype'], $objettype . "_" . $item->getField("id") . "_" . $item->getType() . '$2'); $entity = new Entity(); if ($entity->getFromDB($this->getEntity())) { $datas["##{$objettype}.entity##"] = $entity->getField('completename'); $datas["##{$objettype}.shortentity##"] = $entity->getField('name'); } $datas["##{$objettype}.storestatus##"] = $item->getField('status'); $datas["##{$objettype}.status##"] = $item->getStatus($item->getField('status')); $datas["##{$objettype}.urgency##"] = $item->getUrgencyName($item->getField('urgency')); $datas["##{$objettype}.impact##"] = $item->getImpactName($item->getField('impact')); $datas["##{$objettype}.priority##"] = $item->getPriorityName($item->getField('priority')); $datas["##{$objettype}.time##"] = $item->getActionTime($item->getField('actiontime')); $datas["##{$objettype}.creationdate##"] = Html::convDateTime($item->getField('date')); $datas["##{$objettype}.closedate##"] = Html::convDateTime($item->getField('closedate')); $datas["##{$objettype}.solvedate##"] = Html::convDateTime($item->getField('solvedate')); $datas["##{$objettype}.duedate##"] = Html::convDateTime($item->getField('due_date')); $datas["##{$objettype}.category##"] = ''; if ($item->getField('itilcategories_id')) { $datas["##{$objettype}.category##"] = Dropdown::getDropdownName('glpi_itilcategories', $item->getField('itilcategories_id')); } $datas["##{$objettype}.authors##"] = ''; $datas['authors'] = array(); if ($item->countUsers(CommonITILActor::REQUESTER)) { $users = array(); foreach ($item->getUsers(CommonITILActor::REQUESTER) as $tmpusr) { $uid = $tmpusr['users_id']; $user_tmp = new User(); if ($uid && $user_tmp->getFromDB($uid)) { $users[] = $user_tmp->getName(); $tmp = array(); $tmp['##author.id##'] = $uid; $tmp['##author.name##'] = $user_tmp->getName(); if ($user_tmp->getField('locations_id')) { $tmp['##author.location##'] = Dropdown::getDropdownName('glpi_locations', $user_tmp->getField('locations_id')); } else { $tmp['##author.location##'] = ''; } if ($user_tmp->getField('usertitles_id')) { $tmp['##author.title##'] = Dropdown::getDropdownName('glpi_usertitles', $user_tmp->getField('usertitles_id')); } else { $tmp['##author.title##'] = ''; } if ($user_tmp->getField('usercategories_id')) { $tmp['##author.category##'] = Dropdown::getDropdownName('glpi_usercategories', $user_tmp->getField('usercategories_id')); } else { $tmp['##author.category##'] = ''; } $tmp['##author.email##'] = $user_tmp->getDefaultEmail(); $tmp['##author.mobile##'] = $user_tmp->getField('mobile'); $tmp['##author.phone##'] = $user_tmp->getField('phone'); $tmp['##author.phone2##'] = $user_tmp->getField('phone2'); $datas['authors'][] = $tmp; } else { // Anonymous users only in xxx.authors, not in authors $users[] = $tmpusr['alternative_email']; } } $datas["##{$objettype}.authors##"] = implode(', ', $users); } $datas["##{$objettype}.openbyuser##"] = ''; if ($item->getField('users_id_recipient')) { $user_tmp = new User(); $user_tmp->getFromDB($item->getField('users_id_recipient')); $datas["##{$objettype}.openbyuser##"] = $user_tmp->getName(); } $datas["##{$objettype}.lastupdater##"] = ''; if ($item->getField('users_id_lastupdater')) { $user_tmp = new User(); $user_tmp->getFromDB($item->getField('users_id_lastupdater')); $datas["##{$objettype}.lastupdater##"] = $user_tmp->getName(); } $datas["##{$objettype}.assigntousers##"] = ''; if ($item->countUsers(CommonITILActor::ASSIGN)) { $users = array(); foreach ($item->getUsers(CommonITILActor::ASSIGN) as $tmp) { $uid = $tmp['users_id']; $user_tmp = new User(); if ($user_tmp->getFromDB($uid)) { $users[$uid] = $user_tmp->getName(); } } $datas["##{$objettype}.assigntousers##"] = implode(', ', $users); } $datas["##{$objettype}.assigntosupplier##"] = ''; if ($item->countSuppliers(CommonITILActor::ASSIGN)) { $suppliers = array(); foreach ($item->getSuppliers(CommonITILActor::ASSIGN) as $tmp) { $uid = $tmp['suppliers_id']; $supplier_tmp = new Supplier(); if ($supplier_tmp->getFromDB($uid)) { $suppliers[$uid] = $supplier_tmp->getName(); } } $datas["##{$objettype}.assigntosupplier##"] = implode(', ', $suppliers); } $datas["##{$objettype}.groups##"] = ''; if ($item->countGroups(CommonITILActor::REQUESTER)) { $groups = array(); foreach ($item->getGroups(CommonITILActor::REQUESTER) as $tmp) { $gid = $tmp['groups_id']; $groups[$gid] = Dropdown::getDropdownName('glpi_groups', $gid); } $datas["##{$objettype}.groups##"] = implode(', ', $groups); } $datas["##{$objettype}.observergroups##"] = ''; if ($item->countGroups(CommonITILActor::OBSERVER)) { $groups = array(); foreach ($item->getGroups(CommonITILActor::OBSERVER) as $tmp) { $gid = $tmp['groups_id']; $groups[$gid] = Dropdown::getDropdownName('glpi_groups', $gid); } $datas["##{$objettype}.observergroups##"] = implode(', ', $groups); } $datas["##{$objettype}.observerusers##"] = ''; if ($item->countUsers(CommonITILActor::OBSERVER)) { $users = array(); foreach ($item->getUsers(CommonITILActor::OBSERVER) as $tmp) { $uid = $tmp['users_id']; $user_tmp = new User(); if ($uid && $user_tmp->getFromDB($uid)) { $users[] = $user_tmp->getName(); } else { $users[] = $tmp['alternative_email']; } } $datas["##{$objettype}.observerusers##"] = implode(', ', $users); } $datas["##{$objettype}.assigntogroups##"] = ''; if ($item->countGroups(CommonITILActor::ASSIGN)) { $groups = array(); foreach ($item->getGroups(CommonITILActor::ASSIGN) as $tmp) { $gid = $tmp['groups_id']; $groups[$gid] = Dropdown::getDropdownName('glpi_groups', $gid); } $datas["##{$objettype}.assigntogroups##"] = implode(', ', $groups); } $datas["##{$objettype}.solution.type##"] = ''; if ($item->getField('solutiontypes_id')) { $datas["##{$objettype}.solution.type##"] = Dropdown::getDropdownName('glpi_solutiontypes', $item->getField('solutiontypes_id')); } $datas["##{$objettype}.solution.description##"] = Toolbox::unclean_cross_side_scripting_deep($item->getField('solution')); $datas['log'] = array(); // Use list_limit_max or load the full history ? foreach (Log::getHistoryData($item, 0, $CFG_GLPI['list_limit_max']) as $data) { $tmp = array(); $tmp["##{$objettype}.log.date##"] = $data['date_mod']; $tmp["##{$objettype}.log.user##"] = $data['user_name']; $tmp["##{$objettype}.log.field##"] = $data['field']; $tmp["##{$objettype}.log.content##"] = $data['change']; $datas['log'][] = $tmp; } $datas["##{$objettype}.numberoflogs##"] = count($datas['log']); // Get unresolved items $restrict = "`" . $item->getTable() . "`.`status`\n NOT IN ('" . implode("', '", array_merge($item->getSolvedStatusArray(), $item->getClosedStatusArray())) . "'\n )"; if ($item->maybeDeleted()) { $restrict .= " AND `" . $item->getTable() . "`.`is_deleted` = '0' "; } $datas["##{$objettype}.numberofunresolved##"] = countElementsInTableForEntity($item->getTable(), $this->getEntity(), $restrict); // Document $query = "SELECT `glpi_documents`.*\n FROM `glpi_documents`\n LEFT JOIN `glpi_documents_items`\n ON (`glpi_documents`.`id` = `glpi_documents_items`.`documents_id`)\n WHERE `glpi_documents_items`.`itemtype` = '{$objettype}'\n AND `glpi_documents_items`.`items_id` = '" . $item->getField('id') . "'"; $datas["documents"] = array(); if ($result = $DB->query($query)) { while ($data = $DB->fetch_assoc($result)) { $tmp = array(); $tmp['##document.id##'] = $data['id']; $tmp['##document.name##'] = $data['name']; $tmp['##document.weblink##'] = $data['link']; $tmp['##document.url##'] = $this->formatURL($options['additionnaloption']['usertype'], "document_" . $data['id']); $tmp['##document.heading##'] = Dropdown::getDropdownName('glpi_documentcategories', $data['documentcategories_id']); $tmp['##document.filename##'] = $data['filename']; $datas['documents'][] = $tmp; } } $datas["##{$objettype}.urldocument##"] = $this->formatURL($options['additionnaloption']['usertype'], $objettype . "_" . $item->getField("id") . '_Document_Item$1'); $datas["##{$objettype}.numberofdocuments##"] = count($datas['documents']); return $datas; }
function updateGenericServicesCatalogs($action = 'update') { global $DB; $entity = new Entity(); $pmServicescatalog = new PluginMonitoringServicescatalog(); $pmBusinessrulegroup = new PluginMonitoringBusinessrulegroup(); $pmBusinessrulecomponent = new PluginMonitoringBusinessrule_component(); $existingSCs = array(); // Find existing instances of generic services catalog ... $a_SCs = $this->find("`name` LIKE '" . $this->getName() . "%'"); foreach ($a_SCs as $a_SC) { // Toolbox::logInFile("pm", "SC : ".$a_SC['id'].", name : ".$a_SC['name'].", generic : ".$a_SC['is_generic']."\n"); if ($a_SC['name'] == $this->getField('name')) { continue; } $existingSCs[$a_SC['name']] = $a_SC; } if ($action == 'delete') { foreach ($existingSCs as $name => $a_SC) { $pmServicescatalog->getFromDB($a_SC['id']); $pmServicescatalog->delete($pmServicescatalog->fields); // Toolbox::logInFile("pm", "Deleted : ".$a_SC['name']."\n"); $pmBusinessrulecomponent = new PluginMonitoringBusinessrule_component(); $pmBusinessrule = new PluginMonitoringBusinessrule(); // Get business rules groups ... $a_BRgroups = $pmBusinessrulegroup->find("`plugin_monitoring_servicescatalogs_id`='" . $a_SC['id'] . "'"); // Delete business groups components foreach ($a_BRgroups as $a_BRgroup) { // Toolbox::logInFile("pm", "a_BRgroup : ".$a_BRgroup['id']."\n"); $a_brcomponents = $pmBusinessrulecomponent->find("`plugin_monitoring_businessrulegroups_id`='" . $a_BRgroup['id'] . "'"); foreach ($a_brcomponents as $a_brcomponent) { // Toolbox::logInFile("pm", "a_brcomponent : ".$a_brcomponent['id']."\n"); $pmBusinessrulecomponent->getFromDB($a_brcomponent['id']); $pmBusinessrulecomponent->delete($pmBusinessrulecomponent->fields); } } // Delete business groups rules foreach ($a_BRgroups as $a_BRgroup) { $a_brs = $pmBusinessrule->find("`plugin_monitoring_businessrulegroups_id`='" . $a_BRgroup['id'] . "'"); foreach ($a_brs as $a_br) { // Toolbox::logInFile("pm", "a_br : ".$a_br['id']."\n"); $pmBusinessrulecomponent->getFromDB($a_brcomponent['id']); $pmBusinessrulecomponent->delete($pmBusinessrulecomponent->fields); } } } return; } else { foreach ($existingSCs as $name => $a_SC) { $pmServicescatalog->getFromDB($a_SC['id']); $pmBusinessrulegroup = new PluginMonitoringBusinessrulegroup(); $pmBusinessrulecomponent = new PluginMonitoringBusinessrule_component(); $pmBusinessrule = new PluginMonitoringBusinessrule(); // Get business rules groups ... $a_BRgroups = $pmBusinessrulegroup->find("`plugin_monitoring_servicescatalogs_id`='" . $a_SC['id'] . "'"); // Delete business groups components foreach ($a_BRgroups as $a_BRgroup) { // Toolbox::logInFile("pm", "a_BRgroup : ".$a_BRgroup['id']."\n"); $a_brcomponents = $pmBusinessrulecomponent->find("`plugin_monitoring_businessrulegroups_id`='" . $a_BRgroup['id'] . "'"); foreach ($a_brcomponents as $a_brcomponent) { // Toolbox::logInFile("pm", "a_brcomponent : ".$a_brcomponent['id']."\n"); $pmBusinessrulecomponent->getFromDB($a_brcomponent['id']); $pmBusinessrulecomponent->delete($pmBusinessrulecomponent->fields); } } // Delete business groups rules foreach ($a_BRgroups as $a_BRgroup) { $a_brs = $pmBusinessrule->find("`plugin_monitoring_businessrulegroups_id`='" . $a_BRgroup['id'] . "'"); foreach ($a_brs as $a_br) { // Toolbox::logInFile("pm", "a_br : ".$a_br['id']."\n"); $pmBusinessrulecomponent->getFromDB($a_brcomponent['id']); $pmBusinessrulecomponent->delete($pmBusinessrulecomponent->fields); } } } } // Find entities concerned ... $a_entitiesServices = $this->getGenericServicesEntities(); foreach ($a_entitiesServices as $idEntity => $a_entityServices) { // New entity ... so it must exist a derivated SC ! $entity->getFromDB($idEntity); // Toolbox::logInFile("pm", "Found entity : ".$idEntity." / ".$entity->getName()."\n"); $scName = $this->getName() . " - " . $entity->getName(); if (isset($existingSCs[$scName])) { // Update SC $pmServicescatalog->getFromDB($existingSCs[$scName]['id']); $pmServicescatalog->fields = $this->fields; unset($pmServicescatalog->fields['id']); $pmServicescatalog->fields['id'] = $existingSCs[$scName]['id']; $pmServicescatalog->fields['entities_id'] = $idEntity; $pmServicescatalog->fields['is_generic'] = 0; $pmServicescatalog->fields['name'] = $DB->escape($scName); $pmServicescatalog->update($pmServicescatalog->fields); /* // Finish updating if needed ... $a_BRgroups = $pmBusinessrulegroup->find("`plugin_monitoring_servicescatalogs_id`='".$this->fields['id']."'"); foreach ($a_BRgroups as $a_BRgroup) { $pmBusinessrulegroup = $pmBusinessrulegroup->find("`plugin_monitoring_servicescatalogs_id`='".$a_SC['id']."' AND `name`='".$a_BRgroup['name']."'"); $pmBusinessrulegroup->fields = $a_BRgroup->fields; unset($pmBusinessrulegroup->fields['id']); $pmBusinessrulegroup->fields['plugin_monitoring_servicescatalogs_id'] = $pmServicescatalog->fields['id']; $pmBusinessrulegroup->update($pmBusinessrulegroup->fields); } */ // Toolbox::logInFile("pm", "Updated : ".$scName."\n"); } else { // Add SC $pmServicescatalog = new PluginMonitoringServicescatalog(); $pmServicescatalog->getEmpty(); $pmServicescatalog->fields = $this->fields; unset($pmServicescatalog->fields['id']); $pmServicescatalog->fields['entities_id'] = $idEntity; $pmServicescatalog->fields['is_recursive'] = 0; $pmServicescatalog->fields['is_generic'] = 0; $pmServicescatalog->fields['name'] = $DB->escape($scName); $pmServicescatalog->fields['plugin_monitoring_servicescatalogs_id'] = $this->fields['id']; $pmServicescatalog->add($pmServicescatalog->fields); /* // Finish updating if needed ... $a_BRgroups = $pmBusinessrulegroup->find("`plugin_monitoring_servicescatalogs_id`='".$this->fields['id']."'"); foreach ($a_BRgroups as $a_BRgroup) { $ref = new PluginMonitoringBusinessrulegroup(); $ref->getFromDB($a_BRgroup['id']); $pmBusinessrulegroup = new PluginMonitoringBusinessrulegroup(); $pmBusinessrulegroup->getEmpty(); $pmBusinessrulegroup->fields = $ref->fields; unset($pmBusinessrulegroup->fields['id']); $pmBusinessrulegroup->fields['plugin_monitoring_servicescatalogs_id'] = $pmServicescatalog->fields['id']; $pmBusinessrulegroup->add($pmBusinessrulegroup->fields); $a_brcomponents = $pmBusinessrulecomponent->find("`plugin_monitoring_businessrulegroups_id`='".$a_BRgroup['id']."'"); foreach ($a_brcomponents as $a_brcomponent) { $ref = new PluginMonitoringBusinessrule_component(); $ref->getFromDB($a_brcomponent['id']); $pmBusinessrule_component = new PluginMonitoringBusinessrule_component(); $pmBusinessrule_component->getEmpty(); $pmBusinessrule_component->fields = $ref->fields; unset($pmBusinessrule_component->fields['id']); $pmBusinessrule_component->fields['plugin_monitoring_businessrulegroups_id'] = $pmBusinessrulegroup->fields['id']; $pmBusinessrule_component->add($pmBusinessrule_component->fields); } } */ // Toolbox::logInFile("pm", "Added : ".$scName."\n"); } } }
/** * @param $options array * @param $delete (false by default) **/ static function manageValuesInSession($options = array(), $delete = false) { $fields = array('action', 'authldaps_id', 'basedn', 'begin_date', 'criterias', 'end_date', 'entities_id', 'interface', 'ldap_filter', 'mode'); //If form accessed via modal, do not show expert mode link // Manage new value is set : entity or mode if (isset($options['entity']) || isset($options['mode'])) { if (isset($options['_in_modal']) && $options['_in_modal']) { //If coming form the helpdesk form : reset all criterias $_SESSION['ldap_import']['_in_modal'] = 1; $_SESSION['ldap_import']['no_expert_mode'] = 1; $_SESSION['ldap_import']['action'] = 'show'; $_SESSION['ldap_import']['interface'] = self::SIMPLE_INTERFACE; $_SESSION['ldap_import']['mode'] = self::ACTION_IMPORT; } else { $_SESSION['ldap_import']['_in_modal'] = 0; } } if (!$delete) { if (!isset($_SESSION['ldap_import']['entities_id'])) { $options['entities_id'] = $_SESSION['glpiactive_entity']; } if (isset($options['toprocess'])) { $_SESSION['ldap_import']['action'] = 'process'; } if (isset($options['change_directory'])) { $options['ldap_filter'] = ''; } if (!isset($_SESSION['ldap_import']['authldaps_id'])) { $_SESSION['ldap_import']['authldaps_id'] = NOT_AVAILABLE; } if (!Config::canUpdate() && !Entity::canUpdate() || !isset($_SESSION['ldap_import']['interface']) && !isset($options['interface'])) { $options['interface'] = self::SIMPLE_INTERFACE; } foreach ($fields as $field) { if (isset($options[$field])) { $_SESSION['ldap_import'][$field] = $options[$field]; } } if (isset($_SESSION['ldap_import']['begin_date']) && $_SESSION['ldap_import']['begin_date'] == 'NULL') { $_SESSION['ldap_import']['begin_date'] = ''; } if (isset($_SESSION['ldap_import']['end_date']) && $_SESSION['ldap_import']['end_date'] == 'NULL') { $_SESSION['ldap_import']['end_date'] = ''; } if (!isset($_SESSION['ldap_import']['criterias'])) { $_SESSION['ldap_import']['criterias'] = array(); } $authldap = new self(); //Filter computation if ($_SESSION['ldap_import']['interface'] == self::SIMPLE_INTERFACE) { $entity = new Entity(); if ($entity->getFromDB($_SESSION['ldap_import']['entities_id']) && $entity->getField('authldaps_id') > 0) { $authldap->getFromDB($_SESSION['ldap_import']['authldaps_id']); $_SESSION['ldap_import']['authldaps_id'] = $entity->getField('authldaps_id'); $_SESSION['ldap_import']['basedn'] = $entity->getField('ldap_dn'); // No dn specified in entity : use standard one if (empty($_SESSION['ldap_import']['basedn'])) { $_SESSION['ldap_import']['basedn'] = $authldap->getField('basedn'); } if ($entity->getField('entity_ldapfilter') != NOT_AVAILABLE) { $_SESSION['ldap_import']['entity_filter'] = $entity->getField('entity_ldapfilter'); } } else { $_SESSION['ldap_import']['authldaps_id'] = self::getDefault(); if ($_SESSION['ldap_import']['authldaps_id'] > 0) { $authldap->getFromDB($_SESSION['ldap_import']['authldaps_id']); $_SESSION['ldap_import']['basedn'] = $authldap->getField('basedn'); } } if ($_SESSION['ldap_import']['authldaps_id'] > 0) { $_SESSION['ldap_import']['ldap_filter'] = self::buildLdapFilter($authldap); } } else { if ($_SESSION['ldap_import']['authldaps_id'] == NOT_AVAILABLE || !$_SESSION['ldap_import']['authldaps_id']) { $_SESSION['ldap_import']['authldaps_id'] = self::getDefault(); if ($_SESSION['ldap_import']['authldaps_id'] > 0) { $authldap->getFromDB($_SESSION['ldap_import']['authldaps_id']); $_SESSION['ldap_import']['basedn'] = $authldap->getField('basedn'); } } if (!isset($_SESSION['ldap_import']['ldap_filter']) || $_SESSION['ldap_import']['ldap_filter'] == '') { $authldap->getFromDB($_SESSION['ldap_import']['authldaps_id']); $_SESSION['ldap_import']['basedn'] = $authldap->getField('basedn'); $_SESSION['ldap_import']['ldap_filter'] = self::buildLdapFilter($authldap); } } //Unset all values in session } else { unset($_SESSION['ldap_import']); } }
/** * Cron for ticketsatisfaction's automatic generated * * @param $task : crontask object * * @return integer (0 : nothing done - 1 : done) **/ static function cronCreateInquest($task) { global $DB; $conf = new Entity(); $inquest = new TicketSatisfaction(); $tot = 0; $maxentity = array(); $tabentities = array(); $rate = Entity::getUsedConfig('inquest_config', 0, 'inquest_rate'); if ($rate > 0) { $tabentities[0] = $rate; } foreach ($DB->request('glpi_entities') as $entity) { $rate = Entity::getUsedConfig('inquest_config', $entity['id'], 'inquest_rate'); $parent = Entity::getUsedConfig('inquest_config', $entity['id'], 'entities_id'); if ($rate > 0) { $tabentities[$entity['id']] = $rate; } } foreach ($tabentities as $entity => $rate) { $parent = Entity::getUsedConfig('inquest_config', $entity, 'entities_id'); $delay = Entity::getUsedConfig('inquest_config', $entity, 'inquest_delay'); $duration = Entity::getUsedConfig('inquest_config', $entity, 'inquest_duration'); $type = Entity::getUsedConfig('inquest_config', $entity); $max_closedate = Entity::getUsedConfig('inquest_config', $entity, 'max_closedate'); $query = "SELECT `glpi_tickets`.`id`,\n `glpi_tickets`.`closedate`,\n `glpi_tickets`.`entities_id`\n FROM `glpi_tickets`\n LEFT JOIN `glpi_ticketsatisfactions`\n ON `glpi_ticketsatisfactions`.`tickets_id` = `glpi_tickets`.`id`\n LEFT JOIN `glpi_entities`\n ON `glpi_tickets`.`entities_id` = `glpi_entities`.`id`\n WHERE `glpi_tickets`.`entities_id` = '{$entity}'\n AND `glpi_tickets`.`is_deleted` = 0\n AND `glpi_tickets`.`status` = '" . self::CLOSED . "'\n AND `glpi_tickets`.`closedate` > '{$max_closedate}'\n AND ADDDATE(`glpi_tickets`.`closedate`, INTERVAL {$delay} DAY)<=NOW()\n AND ADDDATE(`glpi_entities`.`max_closedate`, INTERVAL {$duration} DAY)<=NOW()\n AND `glpi_ticketsatisfactions`.`id` IS NULL\n ORDER BY `closedate` ASC"; $nb = 0; $max_closedate = ''; foreach ($DB->request($query) as $tick) { $max_closedate = $tick['closedate']; if (mt_rand(1, 100) <= $rate) { if ($inquest->add(array('tickets_id' => $tick['id'], 'date_begin' => $_SESSION["glpi_currenttime"], 'entities_id' => $tick['entities_id'], 'type' => $type))) { $nb++; } } } // conservation de toutes les max_closedate des entites filles if (!empty($max_closedate) && (!isset($maxentity[$parent]) || $max_closedate > $maxentity[$parent])) { $maxentity[$parent] = $max_closedate; } if ($nb) { $tot += $nb; $task->addVolume($nb); $task->log(sprintf(__('%1$s: %2$s'), Dropdown::getDropdownName('glpi_entities', $entity), $nb)); } } // Sauvegarde du max_closedate pour ne pas tester les même tickets 2 fois foreach ($maxentity as $parent => $maxdate) { $conf->getFromDB($parent); $conf->update(array('id' => $conf->fields['id'], 'max_closedate' => $maxdate)); } return $tot > 0; }
/** * @see NotificationTarget::getDatasForTemplate() **/ function getDatasForTemplate($event, $options = array()) { global $CFG_GLPI, $DB; //----------- Reservation infos -------------- // $events = $this->getAllEvents(); $item = $this->obj; $this->datas['##project.action##'] = $events[$event]; $this->datas['##project.url##'] = $this->formatURL($options['additionnaloption']['usertype'], "Project_" . $item->getField("id")); $this->datas["##project.name##"] = $item->getField('name'); $this->datas["##project.code##"] = $item->getField('code'); $this->datas["##project.description##"] = $item->getField('content'); $this->datas["##project.comments##"] = $item->getField('comment'); $this->datas["##project.creationdate##"] = Html::convDateTime($item->getField('date')); $this->datas["##project.lastupdatedate##"] = Html::convDateTime($item->getField('date_mod')); $this->datas["##project.priority##"] = CommonITILObject::getPriorityName($item->getField('priority')); $this->datas["##project.percent##"] = Dropdown::getValueWithUnit($item->getField('percent_done'), "%"); $this->datas["##project.planstartdate##"] = Html::convDateTime($item->getField('plan_start_date')); $this->datas["##project.planenddate##"] = Html::convDateTime($item->getField('plan_end_date')); $this->datas["##project.realstartdate##"] = Html::convDateTime($item->getField('real_start_date')); $this->datas["##project.realenddate##"] = Html::convDateTime($item->getField('real_end_date')); $this->datas["##project.plannedduration##"] = Html::timestampToString(ProjectTask::getTotalPlannedDurationForProject($item->getID()), false); $this->datas["##project.effectiveduration##"] = Html::timestampToString(ProjectTask::getTotalEffectiveDurationForProject($item->getID()), false); $entity = new Entity(); $this->datas["##project.entity##"] = ''; $this->datas["##project.shortentity##"] = ''; if ($entity->getFromDB($this->getEntity())) { $this->datas["##project.entity##"] = $entity->getField('completename'); $this->datas["##project.shortentity##"] = $entity->getField('name'); } $this->datas["##project.father##"] = ''; if ($item->getField('projects_id')) { $this->datas["##project.father##"] = Dropdown::getDropdownName('glpi_projects', $item->getField('projects_id')); } $this->datas["##project.state##"] = ''; if ($item->getField('projectstates_id')) { $this->datas["##project.state##"] = Dropdown::getDropdownName('glpi_projectstates', $item->getField('projectstates_id')); } $this->datas["##project.type##"] = ''; if ($item->getField('projecttypes_id')) { $this->datas["##project.type##"] = Dropdown::getDropdownName('glpi_projecttypes', $item->getField('projecttypes_id')); } $this->datas["##project.manager##"] = ''; if ($item->getField('users_id')) { $user_tmp = new User(); $user_tmp->getFromDB($item->getField('users_id')); $this->datas["##project.manager##"] = $user_tmp->getName(); } $this->datas["##project.managergroup##"] = ''; if ($item->getField('groups_id')) { $this->datas["##project.managergroup##"] = Dropdown::getDropdownName('glpi_groups', $item->getField('groups_id')); } // Team infos $restrict = "`projects_id` = '" . $item->getField('id') . "'"; $items = getAllDatasFromTable('glpi_projectteams', $restrict); $this->datas['teammembers'] = array(); if (count($items)) { foreach ($items as $data) { if ($item2 = getItemForItemtype($data['itemtype'])) { if ($item2->getFromDB($data['items_id'])) { $tmp = array(); $tmp['##teammember.itemtype##'] = $item2->getTypeName(); $tmp['##teammember.name##'] = $item2->getName(); $this->datas['teammembers'][] = $tmp; } } } } $this->datas['##project.numberofteammembers##'] = count($this->datas['teammembers']); // Task infos $restrict = "`projects_id`='" . $item->getField('id') . "'"; $restrict .= " ORDER BY `date` DESC, `id` ASC"; $tasks = getAllDatasFromTable('glpi_projecttasks', $restrict); $this->datas['tasks'] = array(); foreach ($tasks as $task) { $tmp = array(); $tmp['##task.creationdate##'] = Html::convDateTime($task['date']); $tmp['##task.lastupdatedate##'] = Html::convDateTime($task['date_mod']); $tmp['##task.name##'] = $task['name']; $tmp['##task.description##'] = $task['content']; $tmp['##task.comments##'] = $task['comment']; $tmp['##task.state##'] = Dropdown::getDropdownName('glpi_projectstates', $task['projectstates_id']); $tmp['##task.type##'] = Dropdown::getDropdownName('glpi_projecttasktypes', $task['projecttasktypes_id']); $tmp['##task.percent##'] = Dropdown::getValueWithUnit($task['percent_done'], "%"); $this->datas["##task.planstartdate##"] = ''; $this->datas["##task.planenddate##"] = ''; $this->datas["##task.realstartdate##"] = ''; $this->datas["##task.realenddate##"] = ''; if (!is_null($task['plan_start_date'])) { $tmp['##task.planstartdate##'] = Html::convDateTime($task['plan_start_date']); } if (!is_null($task['plan_end_date'])) { $tmp['##task.planenddate##'] = Html::convDateTime($task['plan_end_date']); } if (!is_null($task['real_start_date'])) { $tmp['##task.realstartdate##'] = Html::convDateTime($task['real_start_date']); } if (!is_null($task['real_end_date'])) { $tmp['##task.realenddate##'] = Html::convDateTime($task['real_end_date']); } $this->datas['tasks'][] = $tmp; } $this->datas["##project.numberoftasks##"] = count($this->datas['tasks']); //costs infos $restrict = "`projects_id`='" . $item->getField('id') . "'"; $restrict .= " ORDER BY `begin_date` DESC, `id` ASC"; $costs = getAllDatasFromTable('glpi_projectcosts', $restrict); $this->datas['costs'] = array(); $this->datas["##project.totalcost##"] = 0; foreach ($costs as $cost) { $tmp = array(); $tmp['##cost.name##'] = $cost['name']; $tmp['##cost.comment##'] = $cost['comment']; $tmp['##cost.datebegin##'] = Html::convDate($cost['begin_date']); $tmp['##cost.dateend##'] = Html::convDate($cost['end_date']); $tmp['##cost.cost##'] = Html::formatNumber($cost['cost']); $tmp['##cost.budget##'] = Dropdown::getDropdownName('glpi_budgets', $cost['budgets_id']); $this->datas["##project.totalcost##"] += $cost['cost']; $this->datas['costs'][] = $tmp; /// TODO add ticket costs ? } $this->datas["##project.numberofcosts##"] = count($this->datas['costs']); // History infos $this->datas['log'] = array(); // Use list_limit_max or load the full history ? foreach (Log::getHistoryData($item, 0, $CFG_GLPI['list_limit_max']) as $data) { $tmp = array(); $tmp["##project.log.date##"] = $data['date_mod']; $tmp["##project.log.user##"] = $data['user_name']; $tmp["##project.log.field##"] = $data['field']; $tmp["##project.log.content##"] = $data['change']; $this->datas['log'][] = $tmp; } $this->datas["##project.numberoflogs##"] = count($this->datas['log']); // Changes infos $restrict = "`projects_id`='" . $item->getField('id') . "'"; $changes = getAllDatasFromTable('glpi_changes_projects', $restrict); $this->datas['changes'] = array(); if (count($changes)) { $change = new Change(); foreach ($changes as $data) { if ($change->getFromDB($data['changes_id'])) { $tmp = array(); $tmp['##change.id##'] = $data['changes_id']; $tmp['##change.date##'] = $change->getField('date'); $tmp['##change.title##'] = $change->getField('name'); $tmp['##change.url##'] = $this->formatURL($options['additionnaloption']['usertype'], "change_" . $data['changes_id']); $tmp['##change.content##'] = $change->getField('content'); $this->datas['changes'][] = $tmp; } } } $this->datas['##project.numberofchanges##'] = count($this->datas['changes']); // Document $query = "SELECT `glpi_documents`.*\n FROM `glpi_documents`\n LEFT JOIN `glpi_documents_items`\n ON (`glpi_documents`.`id` = `glpi_documents_items`.`documents_id`)\n WHERE `glpi_documents_items`.`itemtype` = 'Project'\n AND `glpi_documents_items`.`items_id` = '" . $item->getField('id') . "'"; $this->datas["documents"] = array(); if ($result = $DB->query($query)) { while ($data = $DB->fetch_assoc($result)) { $tmp = array(); $tmp['##document.id##'] = $data['id']; $tmp['##document.name##'] = $data['name']; $tmp['##document.weblink##'] = $data['link']; $tmp['##document.url##'] = $this->formatURL($options['additionnaloption']['usertype'], "document_" . $data['id']); $downloadurl = "/front/document.send.php?docid=" . $data['id']; $tmp['##document.downloadurl##'] = $this->formatURL($options['additionnaloption']['usertype'], $downloadurl); $tmp['##document.heading##'] = Dropdown::getDropdownName('glpi_documentcategories', $data['documentcategories_id']); $tmp['##document.filename##'] = $data['filename']; $this->datas['documents'][] = $tmp; } } $this->datas["##project.urldocument##"] = $this->formatURL($options['additionnaloption']['usertype'], "Project_" . $item->getField("id") . '_Document_Item$1'); $this->datas["##project.numberofdocuments##"] = count($this->datas['documents']); // Items infos $restrict = "`projects_id` = '" . $item->getField('id') . "'"; $items = getAllDatasFromTable('glpi_items_projects', $restrict); $this->datas['items'] = array(); if (count($items)) { foreach ($items as $data) { if ($item2 = getItemForItemtype($data['itemtype'])) { if ($item2->getFromDB($data['items_id'])) { $tmp = array(); $tmp['##item.itemtype##'] = $item2->getTypeName(); $tmp['##item.name##'] = $item2->getField('name'); $tmp['##item.serial##'] = $item2->getField('serial'); $tmp['##item.otherserial##'] = $item2->getField('otherserial'); $tmp['##item.contact##'] = $item2->getField('contact'); $tmp['##item.contactnum##'] = $item2->getField('contactnum'); $tmp['##item.location##'] = ''; $tmp['##item.user##'] = ''; $tmp['##item.group##'] = ''; $tmp['##item.model##'] = ''; //Object location if ($item2->getField('locations_id') != NOT_AVAILABLE) { $tmp['##item.location##'] = Dropdown::getDropdownName('glpi_locations', $item2->getField('locations_id')); } //Object user if ($item2->getField('users_id')) { $user_tmp = new User(); if ($user_tmp->getFromDB($item2->getField('users_id'))) { $tmp['##item.user##'] = $user_tmp->getName(); } } //Object group if ($item2->getField('groups_id')) { $tmp['##item.group##'] = Dropdown::getDropdownName('glpi_groups', $item2->getField('groups_id')); } $modeltable = getSingular($item2->getTable()) . "models"; $modelfield = getForeignKeyFieldForTable($modeltable); if ($item2->isField($modelfield)) { $tmp['##item.model##'] = $item2->getField($modelfield); } $this->datas['items'][] = $tmp; } } } } $this->datas['##project.numberofitems##'] = count($this->datas['items']); $this->getTags(); foreach ($this->tag_descriptions[NotificationTarget::TAG_LANGUAGE] as $tag => $values) { if (!isset($this->datas[$tag])) { $this->datas[$tag] = $values['label']; } } }
function showWidgetFrame($id, $reduced_interface=false, $is_minemap=FALSE) { global $DB, $CFG_GLPI; $this->getFromDB($id); $data = $this->fields; $ret = $this->getInfoOfCatalog($id); $nb_ressources = $ret[0]; if ($nb_ressources == 0) { echo '<div class="ch-item"> <div> <h1>'.__('Nothing to display ...', 'monitoring').'</h1> </div> </div>'; return; } $stateg = $ret[1]; $hosts_ids = $ret[2]; $services_ids = $ret[3]; $hosts_ressources = $ret[4]; $hosts_states = $ret[5]; $colorclass = 'ok'; $count = 0; $link = ''; // Toolbox::logInFile("pm", "stateg $id - ".serialize($stateg)."\n"); if ($stateg['CRITICAL'] > 0) { $count = $stateg['CRITICAL']; $colorclass = 'crit'; $link = $CFG_GLPI['root_doc']. "/plugins/monitoring/front/service.php?hidesearch=1" // . "&reset=reset&" . "criteria[0][field]=3" . "&criteria[0][searchtype]=equals" . "&criteria[0][value]=CRITICAL" . "&criteria[1][link]=AND" . "&criteria[1][field]=9" . "&criteris[1][searchtype]=equals" . "&criteria[1][value]=".$id . "&itemtype=PluginMonitoringService" . "&start=0"; } else if ($stateg['WARNING'] > 0) { $count = $stateg['WARNING']; $colorclass = 'warn'; $link = $CFG_GLPI['root_doc']. "/plugins/monitoring/front/service.php?hidesearch=1" // . "&reset=reset" . "&criteria[0][field]=3" . "&criteria[0][searchtype]=equals" . "&criteria[0][value]=WARNING" . "&criteria[1][link]=AND" . "&criteria[1][field]=9" . "&criteria[1][searchtype]=equals" . "&criteria[1][value]=".$id . "&criteria[2][link]=OR" . "&criteria[2][field]=3" . "&criteria[2][searchtype]=equals" . "&criteria[2][value]=UNKNOWN" . "&criteria[3][link]=AND" . "&criteria[3][field]=9" . "&criteria[3][searchtype]=equals" . "&criteria[3][value]=".$id . "&criteria[4][link]=OR" . "&criteria[4][field]=3" . "&criteria[4][searchtype]=equals" . "&criteria[4][value]=RECOVERY" . "&criteria[5][link]=AND" . "&criteria[5][field]=9" . "&criteria[5][searchtype]=equals" . "&criteria[5][value]=".$id . "&criteria[6][link]=OR" . "&criteria[6][field]=3" . "&criteria[6][searchtype]=equals" . "&criteria[6][value]=FLAPPING" . "&criteria[7][link]=AND" . "&criteria[7][field]=9" . "&criteria[7][searchtype]=equals" . "&criteria[7][value]=".$id . "&itemtype=PluginMonitoringService" . "&start=0"; } else { $count = $stateg['OK']; $count += $stateg['ACKNOWLEDGE']; $count += $stateg['UNKNOWN']; $link = $CFG_GLPI['root_doc']. "/plugins/monitoring/front/service.php?hidesearch=1" // . "&reset=reset" . "&criteria[0][field]=3" . "&criteria[0][searchtype]=equals" . "&criteria[0][value]=OK" . "&criteria[1][link]=AND" . "&criteria[1][field]=9" . "&criteria[1][searchtype]=equals" . "&criteria[1][value]=".$id . "&criteria[2][link]=OR" . "&criteria[2][field]=3" . "&criteria[2][searchtype]=equals" . "&criteria[2][value]=UP" . "&itemtype=PluginMonitoringService" . "&start=0"; } if (Session::haveRight("plugin_monitoring_service", READ)) { $link_catalog = $CFG_GLPI['root_doc']. "/plugins/monitoring/front/service.php?hidesearch=1" // . "&reset=reset" . "&criteria[0][field]=9" . "&criteria[0][searchtype]=equals" . "&criteria[0][value]=".$id . "&itemtype=PluginMonitoringService" . "&start=0"; echo '<div class="ch-item"> <div class="ch-info-'.$colorclass.'"> <h1><a href="'.$link_catalog.'">'.ucfirst($data['name']); if ($data['comment'] != '') { echo ' '.$this->getComments(); } echo '</a></h1> <p><a href="'.$link.'">'.$count.'</a><font style="font-size: 14px;">/ '. ($stateg['CRITICAL'] + $stateg['WARNING'] + $stateg['OK'] + $stateg['ACKNOWLEDGE'] + $stateg['UNKNOWN']).'</font></p> </div> </div>'; } else { echo '<div class="ch-item"> <div class="ch-info-'.$colorclass.'"> <h1>'.ucfirst($data['name']); if ($data['comment'] != '') { echo ' '.$this->getComments(); } echo '</h1> <p>'.$count.'<font style="font-size: 14px;">/ '. ($stateg['CRITICAL'] + $stateg['WARNING'] + $stateg['OK'] + $stateg['ACKNOWLEDGE'] + $stateg['UNKNOWN']).'</font></p> </div> </div>'; } // Get services list ... $services = array(); $i = 0; foreach ($hosts_ressources as $resources) { foreach ($resources as $resource=>$status) { $services[$i++] = $resource; } break; } sort($services); echo "<div class='minemapdiv' align='center'>" ."<a onclick='$(\"#minemapCC-".$id."\").toggle();'>" .__('Minemap', 'monitoring')."</a></div>"; if (!$is_minemap) { echo '<div class="minemapdiv" id="minemapCC-'.$id.'" style="display: none; z-index: 1500">'; } else { echo '<div class="minemapdiv" id="minemapCC-'.$id.'">'; } echo '<table class="tab_cadrehov" >'; // Header with services name and link to services list ... echo "<tr>"; echo "<th colspan='2'>"; echo __('Hosts', 'monitoring'); echo "</th>"; for ($i = 0; $i < count($services); $i++) { // Do not display fake host service ... if ($services[$i] == '_fake_') continue; if (Session::haveRight("plugin_monitoring_service", READ)) { $link = $CFG_GLPI['root_doc']. "/plugins/monitoring/front/service.php?hidesearch=1" // . "&reset=reset" . "&criteria[0][field]=2" . "&criteria[0][searchtype]=equals" . "&criteria[0][value]=".$services_ids[$services[$i]] . "&itemtype=PluginMonitoringService" . "&start=0'"; echo '<th class="vertical">'; echo '<a href="'.$link.'"><div class="rotated-text"><span class="rotated-text__inner">'.$services[$i].'</span></div></a>'; echo '</th>'; } else { echo '<th class="vertical">'; echo '<div class="rotated-text"><span class="rotated-text__inner">'.$services[$i].'</span></div>'; echo '</th>'; } } echo '</tr>'; $pmHost = new PluginMonitoringHost(); $entityId = -1; $overallServicesState = 'OK'; foreach ($hosts_ressources as $hosts_id=>$resources) { // Reduced array or not ? if ($reduced_interface and $hosts_states[$hosts_id]) continue; $pmHost->getFromDB($hosts_ids[$hosts_id]['id']); if ($entityId != $pmHost->fields['entities_id']) { if ($entityId != -1) { echo "</table>"; if ($overallServicesState != 'OK') { echo "<script> Ext.onReady(function(){ toggleEntity('entity-$id-$entityId'); });</script>"; $overallServicesState = 'OK'; } } // A new sub-table for each entity ... $entityId = $pmHost->fields['entities_id']; $pmEntity = new Entity(); $pmEntity->getFromDB($entityId); echo "<tr class='tab_bg_1'>"; echo "<table class='tab_cadrehov' style='height: auto;' id='entity-$id-$entityId' onClick='javascript: toggleEntity(\"entity-$id-$entityId\");'>"; $overallServicesState = 'OK'; echo "<tr class='header'><th class='left' style='height:50px;' colspan='".(count($services))."'>".$pmEntity->fields['name']."</th></tr>"; } $field_id = 20; if ($hosts_ids[$hosts_id]['itemtype'] == 'Printer') { $field_id = 21; } else if ($hosts_ids[$hosts_id]['itemtype'] == 'NetworkEquipment') { $field_id = 22; } $link = $CFG_GLPI['root_doc']. "/plugins/monitoring/front/service.php?hidesearch=1" // . "&reset=reset" . "&criteria[0][field]=".$field_id."" . "&criteria[0][searchtype]=equals" . "&criteria[0][value]=".$hosts_ids[$hosts_id]['items_id'] . "&itemtype=PluginMonitoringService" . "&start=0'"; if ($hosts_states[$hosts_id]) { echo "<tr class='services tab_bg_2' style='display:none;'>"; } else { echo "<tr class='services tab_bg_3' style='display:none;'>"; } // echo "<td><div style='width: 5px !important;'> </div></td>"; if (Session::haveRight("plugin_monitoring_service", READ)) { $item = new $hosts_ids[$hosts_id]['itemtype']; $item->getFromDB($hosts_ids[$hosts_id]['items_id']); echo "<td class='left'><a href='".$link."'>".$hosts_ids[$hosts_id]['name']."</a> ".$item->getComments()."</td>"; } else { echo "<td class='left'>".$hosts_ids[$hosts_id]['name']."</td>"; } for ($i = 0; $i < count($services); $i++) { if ($services[$i] == '_fake_') continue; if ($resources[$services[$i]]['state'] != 'OK') { $overallServicesState = $resources[$services[$i]]['state']; } echo '<td class="serviceState">'; if (Session::haveRight("plugin_monitoring_service", READ)) { $link_service = $link; $link_service .= "&link[1]=AND&field[1]=2&searchtype[1]=equals&contains[1]=". $resources[$services[$i]]['plugin_monitoring_components_id']; echo '<a href="'.$link_service.'">'. '<div title="'.$resources[$services[$i]]['state']. " - ".$resources[$services[$i]]['last_check']." - ". $resources[$services[$i]]['event']. '" class="service service'.$resources[$services[$i]]['state_type'].' service'.$resources[$services[$i]]['state'].'"></div>'. '</a>'; } else { echo '<div title="'.$resources[$services[$i]]['state']. " - ".$resources[$services[$i]]['last_check']." - ". $resources[$services[$i]]['event']. '" class="service service'.$resources[$services[$i]]['state_type'].' service'.$resources[$services[$i]]['state'].'"></div>'; } echo '</td>'; } echo '</tr>'; } echo '</table>'; echo '</div>'; if ($overallServicesState != 'OK') { echo "<script> Ext.onReady(function(){ toggleEntity('entity-$id-$entityId'); });</script>"; } }
function showContacts($itemtype, $items_id) { global $DB,$CFG_GLPI; $this->addContact($itemtype, $items_id); $group = new Group(); $user = new User(); $rand = mt_rand(); echo "<form method='post' name='contact_item_form$rand' id='contact_item_form$rand' action=\"". $CFG_GLPI["root_doc"]."/plugins/monitoring/front/contact_item.form.php\">"; echo "<table class='tab_cadre_fixe'>"; echo "<tr>"; echo "<th>"; echo __('Contacts', 'monitoring'); echo "</th>"; echo "</tr>"; echo "</table>"; echo "<table class='tab_cadre_fixe'>"; echo "<tr>"; echo "<th width='10'> </th>"; echo "<th>".__('Group')." - ".__('Name')."</th>"; echo "<th colspan='3'></th>"; echo "</tr>"; $used = array(); // Display groups first $query = "SELECT * FROM `".$this->getTable()."` WHERE `items_id`='".$items_id."' AND `itemtype`='".$itemtype."' AND `groups_id` > 0"; $result = $DB->query($query); while ($data=$DB->fetch_array($result)) { $group->getFromDB($data['groups_id']); echo "<tr>"; echo "<td>"; echo "<input type='checkbox' name='item[".$data["id"]."]' value='1'>"; echo "</td>"; echo "<td class='center'>"; echo $group->getLink(1); echo "</td>"; echo "<td colspan='3'>"; echo "</td>"; echo "</tr>"; } echo "<tr>"; echo "<th width='10'> </th>"; echo "<th>".__('User')." - ".__('Name')."</th>"; echo "<th>".__('Entity')."</th>"; echo "<th>".__('Email address')."</th>"; echo "<th>".__('Phone')."</th>"; echo "</tr>"; $entity = new Entity(); $used = array(); // Display Users $query = "SELECT * FROM `".$this->getTable()."` WHERE `items_id`='".$items_id."' AND `itemtype`='".$itemtype."' AND `users_id` > 0"; $result = $DB->query($query); while ($data=$DB->fetch_array($result)) { $user->getFromDB($data['users_id']); echo "<tr>"; echo "<td>"; echo "<input type='checkbox' name='item[".$data["id"]."]' value='1'>"; echo "</td>"; echo "<td class='center'>"; echo $user->getLink(1); echo "</td>"; $entity->getFromDB($data['entities_id']); echo "<td class='center'>"; echo $entity->getName()." <strong>(R)</strong>"; echo "</td>"; echo "<td class='center'>"; $a_emails = UserEmail::getAllForUser($data['users_id']); $first = 0; foreach ($a_emails as $email) { if ($first == 0) { echo $email; } $first++; } echo "</td>"; echo "<td class='center'>"; echo $user->fields['phone']; echo "</td>"; echo "</tr>"; } Html::openArrowMassives("contact_item_form$rand", true); Html::closeArrowMassives(array('deleteitem' => _sx('button', 'Delete permanently'))); Html::closeForm(); echo "</table>"; }
/** * Recovery datas of current entity or parent entity * * @param $fieldref string name of the referent field to know if we look at parent entity * @param $entities_id * @param $fieldval string name of the field that we want value **/ static function getUsedConfig($fieldref, $entities_id, $fieldval = '') { // for calendar if (empty($fieldval)) { $fieldval = $fieldref; } $entdata = new EntityData(); // Search in entity data of the current entity if ($entdata->getFromDB($entities_id)) { // Value is defined : use it if (isset($entdata->fields[$fieldref]) && ($entdata->fields[$fieldref] > 0 || !is_numeric($entdata->fields[$fieldref]))) { return $entdata->fields[$fieldval]; } } // Entity data not found or not defined : search in parent one if ($entities_id > 0) { $current = new Entity(); if ($current->getFromDB($entities_id)) { return self::getUsedConfig($fieldref, $current->fields['entities_id'], $fieldval); } } switch ($fieldval) { case "tickettype": // Default is Incident if not set return Ticket::INCIDENT_TYPE; } return 0; }
static function displayLine($data, $displayhost = 1) { global $DB, $CFG_GLPI, $LANG; $pMonitoringService = new PluginMonitoringService(); $networkPort = new NetworkPort(); $pMonitoringComponent = new PluginMonitoringComponent(); $pmComponentscatalog_Host = new PluginMonitoringComponentscatalog_Host(); $pmServicegraph = new PluginMonitoringServicegraph(); $entity = new Entity(); $pMonitoringService->getFromDB($data['id']); echo "<td width='32' class='center'>"; $shortstate = self::getState($data['state'], $data['state_type']); echo "<img src='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/pics/box_" . $shortstate . "_32.png'/>"; echo "</td>"; echo "<td>"; $entity->getFromDB($data['entities_id']); echo $entity->fields['completename']; echo "</td>"; $pMonitoringComponent->getFromDB($data['plugin_monitoring_components_id']); echo "<td class='center'>"; $img = ''; $timezone = '0'; if (isset($_SESSION['plugin_monitoring_timezone'])) { $timezone = $_SESSION['plugin_monitoring_timezone']; } $timezone_file = str_replace("+", ".", $timezone); $img = "<img src='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/send.php?file=PluginMonitoringService-" . $data['id'] . "-2h" . $timezone_file . ".png'/>"; echo "<a href='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/display.form.php?itemtype=PluginMonitoringService&items_id=" . $data['id'] . "'>"; if (file_exists(GLPI_ROOT . "/files/_plugins/monitoring/PluginMonitoringService-" . $data['id'] . "-2h" . $timezone_file . ".png") or $pMonitoringComponent->fields['graph_template'] != '') { $img = "<img src='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/send.php?file=PluginMonitoringService-" . $data['id'] . "-2h" . $timezone_file . ".png'/>"; showToolTip($img, array('img' => $CFG_GLPI['root_doc'] . "/plugins/monitoring/pics/stats_32.png")); } else { } echo "</a>"; echo "</td>"; if ($displayhost == '1') { $pmComponentscatalog_Host->getFromDB($data["plugin_monitoring_componentscatalogs_hosts_id"]); if (isset($pmComponentscatalog_Host->fields['itemtype']) and $pmComponentscatalog_Host->fields['itemtype'] != '') { $itemtype = $pmComponentscatalog_Host->fields['itemtype']; $item = new $itemtype(); $item->getFromDB($pmComponentscatalog_Host->fields['items_id']); echo "<td>"; echo $item->getTypeName() . " : " . $item->getLink(); if (!is_null($pMonitoringService->fields['networkports_id']) and $pMonitoringService->fields['networkports_id'] > 0) { $networkPort->getFromDB($pMonitoringService->fields['networkports_id']); echo " [" . $networkPort->getLink() . "]"; } echo "</td>"; } else { echo "<td>" . $LANG['plugin_monitoring']['service'][0] . "</td>"; } } echo "<td>" . $pMonitoringComponent->getLink(); if (!is_null($pMonitoringService->fields['networkports_id']) and $pMonitoringService->fields['networkports_id'] > 0) { $networkPort->getFromDB($pMonitoringService->fields['networkports_id']); echo " [" . $networkPort->getLink() . "]"; } echo "</td>"; // $nameitem = ''; // if (isset($itemmat->fields['name'])) { // $nameitem = "[".$itemmat->getLink(1)."]"; // } //if ($pMonitoringService->fields['plugin_monitoring_services_id'] == '0') { //echo "<td>".$itemmat->getLink(1)."</td>"; // } else { // $pMonitoringServiceH->getFromDB($pMonitoringService->fields['plugin_monitoring_services_id']); // $itemtypemat = $pMonitoringServiceH->fields['itemtype']; // $itemmat = new $itemtypemat(); // $itemmat->getFromDB($pMonitoringServiceH->fields['items_id']); // echo "<td>".$pMonitoringService->getLink(1).$nameitem." ".$LANG['networking'][25]." ".$itemmat->getLink(1)."</td>"; // } // unset($itemmat); echo "<td class='center'>"; echo $data['state']; echo "</td>"; echo "<td>"; echo convDate($data['last_check']) . ' ' . substr($data['last_check'], 11, 8); echo "</td>"; echo "<td>"; echo $data['event']; echo "</td>"; echo "<td align='center'>"; $segments = CalendarSegment::getSegmentsBetween($pMonitoringComponent->fields['calendars_id'], date('w', date('U')), date('H:i:s'), date('w', date('U')), date('H:i:s')); if (count($segments) == '0') { echo "<img src='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/pics/service_pause.png' />"; } else { echo "<img src='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/pics/service_run.png' />"; } echo "</td>"; if ($displayhost == '0') { $pmUnavaibility = new PluginMonitoringUnavaibility(); $pmUnavaibility->displayValues($pMonitoringService->fields['id'], 'currentmonth', 1); $pmUnavaibility->displayValues($pMonitoringService->fields['id'], 'lastmonth', 1); $pmUnavaibility->displayValues($pMonitoringService->fields['id'], 'currentyear', 1); echo "<td>"; $a_arg = importArrayFromDB($pMonitoringService->fields['arguments']); $cnt = ''; if (count($a_arg) > 0) { $cnt = " (" . count($a_arg) . ")"; } echo "<a href='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/servicearg.form.php?id=" . $data['id'] . "'>" . $LANG['plugin_monitoring']['service'][25] . $cnt . "</a>"; echo "</td>"; } }
function doStat($table, $entity, $header, $level = 0) { global $DB; $Ent = new Entity(); $Ent->getFromDB($entity); // Count for this entity $sql = "SELECT `states_id`, count(*) AS cpt\n FROM `{$table}`\n WHERE `is_deleted` = '0'\n AND `is_template` = '0'\n AND `entities_id` = '{$entity}'\n GROUP BY `states_id`"; $result = $DB->query($sql); $count = array(); while ($data = $DB->fetch_array($result)) { $count[$data["states_id"]] = $data["cpt"]; } $count["tot"] = 0; foreach ($header as $id => $name) { if (isset($count[$id])) { $count["tot"] += $count[$id]; } else { $count[$id] = 0; } } // Display counters for this entity if ($count["tot"] > 0) { echo "<tr class='tab_bg_2'><td>"; for ($i = 0; $i < $level; $i++) { echo " "; } if ($entity) { echo $Ent->fields["name"]; } else { _e('Root entity'); } echo "</td>"; echo "<td class='right'>" . $count["tot"] . "</td>"; foreach ($header as $id => $name) { echo "<td class='right'>" . $count[$id] . "</td>"; } echo "</tr>\n"; } // Call for Childs $save = $count["tot"]; doStatChilds($table, $entity, $header, $count, $level + 1); // Display total (Current+Childs) if ($save != $count["tot"]) { echo "<tr class='tab_bg_1'><td>"; for ($i = 0; $i < $level; $i++) { echo " "; } _e('Total'); if ($entity) { echo $Ent->fields["name"]; } else { _e('Root entity'); } echo "</td>"; echo "<td class='right'>" . $count["tot"] . "</td>"; foreach ($header as $id => $name) { echo "<td class='right'>" . $count[$id] . "</td>"; } echo "</tr>\n"; } return $count; }
/** * @param $item CommonDBTM object * @param $options array * @param $simple (false by default) **/ function getDatasForObject(CommonDBTM $item, array $options, $simple = false) { global $CFG_GLPI, $DB; $objettype = strtolower($item->getType()); $datas["##{$objettype}.title##"] = $item->getField('name'); $datas["##{$objettype}.content##"] = $item->getField('content'); $datas["##{$objettype}.description##"] = $item->getField('content'); $datas["##{$objettype}.id##"] = sprintf("%07d", $item->getField("id")); if ($_SESSION['glpiticket_timeline'] == 1) { $datas["##{$objettype}.url##"] = $this->formatURL($options['additionnaloption']['usertype'], $objettype . "_" . $item->getField("id") . "_" . $item->getType() . '$1'); } else { $datas["##{$objettype}.url##"] = $this->formatURL($options['additionnaloption']['usertype'], $objettype . "_" . $item->getField("id")); } $tab = '$2'; if ($_SESSION['glpiticket_timeline'] == 1) { $tab = '$1'; } $datas["##{$objettype}.urlapprove##"] = $this->formatURL($options['additionnaloption']['usertype'], $objettype . "_" . $item->getField("id") . "_" . $item->getType() . $tab); $entity = new Entity(); if ($entity->getFromDB($this->getEntity())) { $datas["##{$objettype}.entity##"] = $entity->getField('completename'); $datas["##{$objettype}.shortentity##"] = $entity->getField('name'); } $datas["##{$objettype}.storestatus##"] = $item->getField('status'); $datas["##{$objettype}.status##"] = $item->getStatus($item->getField('status')); $datas["##{$objettype}.urgency##"] = $item->getUrgencyName($item->getField('urgency')); $datas["##{$objettype}.impact##"] = $item->getImpactName($item->getField('impact')); $datas["##{$objettype}.priority##"] = $item->getPriorityName($item->getField('priority')); $datas["##{$objettype}.time##"] = $item->getActionTime($item->getField('actiontime')); $datas["##{$objettype}.creationdate##"] = Html::convDateTime($item->getField('date')); $datas["##{$objettype}.closedate##"] = Html::convDateTime($item->getField('closedate')); $datas["##{$objettype}.solvedate##"] = Html::convDateTime($item->getField('solvedate')); $datas["##{$objettype}.duedate##"] = Html::convDateTime($item->getField('due_date')); $datas["##{$objettype}.category##"] = ''; if ($item->getField('itilcategories_id')) { $datas["##{$objettype}.category##"] = Dropdown::getDropdownName('glpi_itilcategories', $item->getField('itilcategories_id')); } $datas["##{$objettype}.authors##"] = ''; $datas['authors'] = array(); if ($item->countUsers(CommonITILActor::REQUESTER)) { $users = array(); foreach ($item->getUsers(CommonITILActor::REQUESTER) as $tmpusr) { $uid = $tmpusr['users_id']; $user_tmp = new User(); if ($uid && $user_tmp->getFromDB($uid)) { $users[] = $user_tmp->getName(); $tmp = array(); $tmp['##author.id##'] = $uid; $tmp['##author.name##'] = $user_tmp->getName(); if ($user_tmp->getField('locations_id')) { $tmp['##author.location##'] = Dropdown::getDropdownName('glpi_locations', $user_tmp->getField('locations_id')); } else { $tmp['##author.location##'] = ''; } if ($user_tmp->getField('usertitles_id')) { $tmp['##author.title##'] = Dropdown::getDropdownName('glpi_usertitles', $user_tmp->getField('usertitles_id')); } else { $tmp['##author.title##'] = ''; } if ($user_tmp->getField('usercategories_id')) { $tmp['##author.category##'] = Dropdown::getDropdownName('glpi_usercategories', $user_tmp->getField('usercategories_id')); } else { $tmp['##author.category##'] = ''; } $tmp['##author.email##'] = $user_tmp->getDefaultEmail(); $tmp['##author.mobile##'] = $user_tmp->getField('mobile'); $tmp['##author.phone##'] = $user_tmp->getField('phone'); $tmp['##author.phone2##'] = $user_tmp->getField('phone2'); $datas['authors'][] = $tmp; } else { // Anonymous users only in xxx.authors, not in authors $users[] = $tmpusr['alternative_email']; } } $datas["##{$objettype}.authors##"] = implode(', ', $users); } $datas["##{$objettype}.openbyuser##"] = ''; if ($item->getField('users_id_recipient')) { $user_tmp = new User(); $user_tmp->getFromDB($item->getField('users_id_recipient')); $datas["##{$objettype}.openbyuser##"] = $user_tmp->getName(); } $datas["##{$objettype}.lastupdater##"] = ''; if ($item->getField('users_id_lastupdater')) { $user_tmp = new User(); $user_tmp->getFromDB($item->getField('users_id_lastupdater')); $datas["##{$objettype}.lastupdater##"] = $user_tmp->getName(); } $datas["##{$objettype}.assigntousers##"] = ''; if ($item->countUsers(CommonITILActor::ASSIGN)) { $users = array(); foreach ($item->getUsers(CommonITILActor::ASSIGN) as $tmp) { $uid = $tmp['users_id']; $user_tmp = new User(); if ($user_tmp->getFromDB($uid)) { $users[$uid] = $user_tmp->getName(); } } $datas["##{$objettype}.assigntousers##"] = implode(', ', $users); } $datas["##{$objettype}.assigntosupplier##"] = ''; if ($item->countSuppliers(CommonITILActor::ASSIGN)) { $suppliers = array(); foreach ($item->getSuppliers(CommonITILActor::ASSIGN) as $tmp) { $uid = $tmp['suppliers_id']; $supplier_tmp = new Supplier(); if ($supplier_tmp->getFromDB($uid)) { $suppliers[$uid] = $supplier_tmp->getName(); } } $datas["##{$objettype}.assigntosupplier##"] = implode(', ', $suppliers); } $datas["##{$objettype}.groups##"] = ''; if ($item->countGroups(CommonITILActor::REQUESTER)) { $groups = array(); foreach ($item->getGroups(CommonITILActor::REQUESTER) as $tmp) { $gid = $tmp['groups_id']; $groups[$gid] = Dropdown::getDropdownName('glpi_groups', $gid); } $datas["##{$objettype}.groups##"] = implode(', ', $groups); } $datas["##{$objettype}.observergroups##"] = ''; if ($item->countGroups(CommonITILActor::OBSERVER)) { $groups = array(); foreach ($item->getGroups(CommonITILActor::OBSERVER) as $tmp) { $gid = $tmp['groups_id']; $groups[$gid] = Dropdown::getDropdownName('glpi_groups', $gid); } $datas["##{$objettype}.observergroups##"] = implode(', ', $groups); } $datas["##{$objettype}.observerusers##"] = ''; if ($item->countUsers(CommonITILActor::OBSERVER)) { $users = array(); foreach ($item->getUsers(CommonITILActor::OBSERVER) as $tmp) { $uid = $tmp['users_id']; $user_tmp = new User(); if ($uid && $user_tmp->getFromDB($uid)) { $users[] = $user_tmp->getName(); } else { $users[] = $tmp['alternative_email']; } } $datas["##{$objettype}.observerusers##"] = implode(', ', $users); } $datas["##{$objettype}.assigntogroups##"] = ''; if ($item->countGroups(CommonITILActor::ASSIGN)) { $groups = array(); foreach ($item->getGroups(CommonITILActor::ASSIGN) as $tmp) { $gid = $tmp['groups_id']; $groups[$gid] = Dropdown::getDropdownName('glpi_groups', $gid); } $datas["##{$objettype}.assigntogroups##"] = implode(', ', $groups); } $datas["##{$objettype}.solution.type##"] = ''; if ($item->getField('solutiontypes_id')) { $datas["##{$objettype}.solution.type##"] = Dropdown::getDropdownName('glpi_solutiontypes', $item->getField('solutiontypes_id')); } $datas["##{$objettype}.solution.description##"] = Toolbox::unclean_cross_side_scripting_deep($item->getField('solution')); // Complex mode if (!$simple) { $datas['log'] = array(); // Use list_limit_max or load the full history ? foreach (Log::getHistoryData($item, 0, $CFG_GLPI['list_limit_max']) as $data) { $tmp = array(); $tmp["##{$objettype}.log.date##"] = $data['date_mod']; $tmp["##{$objettype}.log.user##"] = $data['user_name']; $tmp["##{$objettype}.log.field##"] = $data['field']; $tmp["##{$objettype}.log.content##"] = $data['change']; $datas['log'][] = $tmp; } $datas["##{$objettype}.numberoflogs##"] = count($datas['log']); // Get unresolved items $restrict = "`" . $item->getTable() . "`.`status`\n NOT IN ('" . implode("', '", array_merge($item->getSolvedStatusArray(), $item->getClosedStatusArray())) . "'\n )"; if ($item->maybeDeleted()) { $restrict .= " AND `" . $item->getTable() . "`.`is_deleted` = '0' "; } $datas["##{$objettype}.numberofunresolved##"] = countElementsInTableForEntity($item->getTable(), $this->getEntity(), $restrict); // Document $query = "SELECT `glpi_documents`.*\n FROM `glpi_documents`\n LEFT JOIN `glpi_documents_items`\n ON (`glpi_documents`.`id` = `glpi_documents_items`.`documents_id`)\n WHERE `glpi_documents_items`.`itemtype` = '" . $item->getType() . "'\n AND `glpi_documents_items`.`items_id` = '" . $item->getField('id') . "'"; $datas["documents"] = array(); $addtodownloadurl = ''; if ($item->getType() == 'Ticket') { $addtodownloadurl = "%2526tickets_id=" . $item->fields['id']; } if ($result = $DB->query($query)) { while ($data = $DB->fetch_assoc($result)) { $tmp = array(); $tmp['##document.id##'] = $data['id']; $tmp['##document.name##'] = $data['name']; $tmp['##document.weblink##'] = $data['link']; $tmp['##document.url##'] = $this->formatURL($options['additionnaloption']['usertype'], "document_" . $data['id']); $downloadurl = "/front/document.send.php?docid=" . $data['id']; $tmp['##document.downloadurl##'] = $this->formatURL($options['additionnaloption']['usertype'], $downloadurl . $addtodownloadurl); $tmp['##document.heading##'] = Dropdown::getDropdownName('glpi_documentcategories', $data['documentcategories_id']); $tmp['##document.filename##'] = $data['filename']; $datas['documents'][] = $tmp; } } $datas["##{$objettype}.urldocument##"] = $this->formatURL($options['additionnaloption']['usertype'], $objettype . "_" . $item->getField("id") . '_Document_Item$1'); $datas["##{$objettype}.numberofdocuments##"] = count($datas['documents']); //costs infos $costtype = $item->getType() . 'Cost'; $costs = $costtype::getCostsSummary($costtype, $item->getField("id")); $datas["##{$objettype}.costfixed##"] = $costs['costfixed']; $datas["##{$objettype}.costmaterial##"] = $costs['costmaterial']; $datas["##{$objettype}.costtime##"] = $costs['costtime']; $datas["##{$objettype}.totalcost##"] = $costs['totalcost']; $restrict = "`" . $item->getForeignKeyField() . "`='" . $item->getField('id') . "'"; $restrict .= " ORDER BY `begin_date` DESC, `id` ASC"; $costs = getAllDatasFromTable(getTableForItemType($costtype), $restrict); $datas['costs'] = array(); foreach ($costs as $cost) { $tmp = array(); $tmp['##cost.name##'] = $cost['name']; $tmp['##cost.comment##'] = $cost['comment']; $tmp['##cost.datebegin##'] = Html::convDate($cost['begin_date']); $tmp['##cost.dateend##'] = Html::convDate($cost['end_date']); $tmp['##cost.time##'] = $item->getActionTime($cost['actiontime']); $tmp['##cost.costtime##'] = Html::formatNumber($cost['cost_time']); $tmp['##cost.costfixed##'] = Html::formatNumber($cost['cost_fixed']); $tmp['##cost.costmaterial##'] = Html::formatNumber($cost['cost_material']); $tmp['##cost.totalcost##'] = CommonITILCost::computeTotalCost($cost['actiontime'], $cost['cost_time'], $cost['cost_fixed'], $cost['cost_material']); $tmp['##cost.budget##'] = Dropdown::getDropdownName('glpi_budgets', $cost['budgets_id']); $datas['costs'][] = $tmp; } $datas["##{$objettype}.numberofcosts##"] = count($datas['costs']); //Task infos $tasktype = $item->getType() . 'Task'; $taskobj = new $tasktype(); $restrict = "`" . $item->getForeignKeyField() . "`='" . $item->getField('id') . "'"; if ($taskobj->maybePrivate() && (!isset($options['additionnaloption']['show_private']) || !$options['additionnaloption']['show_private'])) { $restrict .= " AND `is_private` = '0'"; } $restrict .= " ORDER BY `date` DESC, `id` ASC"; $tasks = getAllDatasFromTable($taskobj->getTable(), $restrict); $datas['tasks'] = array(); foreach ($tasks as $task) { $tmp = array(); $tmp['##task.id##'] = $task['id']; if ($taskobj->maybePrivate()) { $tmp['##task.isprivate##'] = Dropdown::getYesNo($task['is_private']); } $tmp['##task.author##'] = Html::clean(getUserName($task['users_id'])); $tmp_taskcatinfo = Dropdown::getDropdownName('glpi_taskcategories', $task['taskcategories_id'], true, true, false); $tmp['##task.categoryid##'] = $task['taskcategories_id']; $tmp['##task.category##'] = $tmp_taskcatinfo['name']; $tmp['##task.categorycomment##'] = $tmp_taskcatinfo['comment']; $tmp['##task.date##'] = Html::convDateTime($task['date']); $tmp['##task.description##'] = $task['content']; $tmp['##task.time##'] = Ticket::getActionTime($task['actiontime']); $tmp['##task.status##'] = Planning::getState($task['state']); $tmp['##task.user##'] = Html::clean(getUserName($task['users_id_tech'])); $tmp['##task.group##'] = Html::clean(Toolbox::clean_cross_side_scripting_deep(Dropdown::getDropdownName("glpi_groups", $task['groups_id_tech'])), true, 2, false); $tmp['##task.begin##'] = ""; $tmp['##task.end##'] = ""; if (!is_null($task['begin'])) { $tmp['##task.begin##'] = Html::convDateTime($task['begin']); $tmp['##task.end##'] = Html::convDateTime($task['end']); } $datas['tasks'][] = $tmp; } $datas["##{$objettype}.numberoftasks##"] = count($datas['tasks']); } return $datas; }
public function generateOrder($params) { global $DB; $ID = $params['id']; $template = $params['template']; $signature = $params['sign']; if ($template) { $config = array('PATH_TO_TMP' => GLPI_DOC_DIR . '/_tmp'); $odf = new Odtphp\Odf(PLUGIN_ORDER_TEMPLATE_DIR . "{$template}", $config); $this->getFromDB($ID); if (file_exists(PLUGIN_ORDER_TEMPLATE_CUSTOM_DIR . "custom.php")) { include_once PLUGIN_ORDER_TEMPLATE_CUSTOM_DIR . "custom.php"; } if (function_exists("plugin_order_getCustomFieldsForODT")) { plugin_order_getCustomFieldsForODT($ID, $template, $odf, $signature); } else { $PluginOrderOrder_Item = new PluginOrderOrder_Item(); $PluginOrderReference_Supplier = new PluginOrderReference_Supplier(); try { $odf->setImage('logo', PLUGIN_ORDER_TEMPLATE_LOGO_DIR . '/logo.jpg'); } catch (\Odtphp\Exceptions\OdfException $e) { } $values = array(); $values['title_order'] = __("Order number", "order"); $values['num_order'] = $this->fields["num_order"]; $values['title_invoice_address'] = __("Invoice address", "order"); $values['comment_order'] = $this->fields["comment"]; $entity = new Entity(); $entity->getFromDB($this->fields["entities_id"]); $town = ''; if ($this->fields["entities_id"] != 0) { $name_entity = $entity->fields["name"]; } else { $name_entity = __("Root entity"); } $values['entity_name'] = $name_entity; if ($entity->getFromDB($this->fields["entities_id"])) { $town = $entity->fields["town"]; $values['entity_address'] = $entity->fields["address"]; $values['entity_postcode'] = $entity->fields["postcode"]; $values['entity_town'] = $entity->fields["town"]; $values['entity_country'] = $entity->fields["country"]; } $supplier = new Supplier(); if ($supplier->getFromDB($this->fields["suppliers_id"])) { $values['supplier_name'] = $supplier->fields["name"]; $values['supplier_address'] = $supplier->fields["address"]; $values['supplier_postcode'] = $supplier->fields["postcode"]; $values['supplier_town'] = $supplier->fields["town"]; $values['supplier_country'] = $supplier->fields["country"]; } $location = new Location(); if ($location->getFromDB($this->fields["locations_id"])) { $values['title_delivery_address'] = __("Delivery address", "order"); $values['comment_delivery_address'] = $location->fields['comment']; } if ($town) { $town = $town . ", "; } $order_date = Html::convDate($this->fields["order_date"]); $username = Html::clean(getUserName(Session::getLoginUserID())); $values['title_date_order'] = $town . __("The", "order") . " "; $values['date_order'] = $order_date; $values['title_sender'] = __("Issuer order", "order"); $values['sender'] = $username; $values['title_budget'] = __("Budget"); $budget = new Budget(); if ($budget->getFromDB($this->fields["budgets_id"])) { $values['budget'] = $budget->fields['name']; } else { $values['budget'] = ''; } $output = ''; $contact = new Contact(); if ($contact->getFromDB($this->fields["contacts_id"])) { $output = formatUserName($contact->fields["id"], "", $contact->fields["name"], $contact->fields["firstname"]); } $values['title_recipient'] = __("Recipient", "order"); $values['recipient'] = Html::clean($output); $values['nb'] = __("Quantity", "order"); $values['title_item'] = __("Designation", "order"); $values['title_ref'] = __("Reference"); $values['HTPrice_item'] = __("Unit price", "order"); $values['TVA_item'] = __("VAT", "order"); $values['title_discount'] = __("Discount rate", "order"); $values['HTPriceTotal_item'] = __("Sum tax free", "order"); $values['ATIPriceTotal_item'] = __("Price ATI", "order"); $listeArticles = array(); $result = $PluginOrderOrder_Item->queryDetail($ID); $num = $DB->numrows($result); while ($data = $DB->fetch_array($result)) { $quantity = $PluginOrderOrder_Item->getTotalQuantityByRefAndDiscount($ID, $data["id"], $data["price_taxfree"], $data["discount"]); $listeArticles[] = array('quantity' => $quantity, 'ref' => utf8_decode($data["name"]), 'taxe' => Dropdown::getDropdownName(getTableForItemType("PluginOrderOrderTax"), $data["plugin_order_ordertaxes_id"]), 'refnumber' => $PluginOrderReference_Supplier->getReferenceCodeByReferenceAndSupplier($data["id"], $this->fields["suppliers_id"]), 'price_taxfree' => $data["price_taxfree"], 'discount' => $data["discount"], false, 0, 'price_discounted' => $data["price_discounted"] * $quantity, 'price_ati' => $data["price_ati"]); } $article = $odf->setSegment('articles'); foreach ($listeArticles as $element) { $article->nbA($element['quantity']); $article->titleArticle($element['ref']); $article->refArticle($element['refnumber']); $article->TVAArticle($element['taxe']); $article->HTPriceArticle(Html::clean(Html::formatNumber($element['price_taxfree']))); if ($element['discount'] != 0) { $article->discount(Html::clean(Html::formatNumber($element['discount'])) . " %"); } else { $article->discount(""); } $article->HTPriceTotalArticle(Html::clean(Html::formatNumber($element['price_discounted']))); $total_TTC_Article = $element['price_discounted'] * (1 + $element['taxe'] / 100); $article->ATIPriceTotalArticle(Html::clean(Html::formatNumber($total_TTC_Article))); $article->merge(); } $odf->mergeSegment($article); $prices = $PluginOrderOrder_Item->getAllPrices($ID); // total price (with postage) $postagewithTVA = $PluginOrderOrder_Item->getPricesATI($this->fields["port_price"], Dropdown::getDropdownName("glpi_plugin_order_ordertaxes", $this->fields["plugin_order_ordertaxes_id"])); $total_HT = $prices["priceHT"] + $this->fields["port_price"]; $total_TVA = $prices["priceTVA"] + $postagewithTVA - $this->fields["port_price"]; $total_TTC = $prices["priceTTC"] + $postagewithTVA; if ($signature) { try { $odf->setImage('sign', PLUGIN_ORDER_SIGNATURE_DIR . $signature); } catch (\Odtphp\Exceptions\OdfException $e) { } } else { try { $odf->setImage('sign', '../pics/nothing.gif'); } catch (\Odtphp\Exceptions\OdfException $e) { } } $name = Dropdown::getDropdownName("glpi_plugin_order_orderpayments", $this->fields["plugin_order_orderpayments_id"]); $values['title_totalht'] = __("Price tax free", "order"); $values['totalht'] = Html::clean(Html::formatNumber($prices['priceHT'])); $values['title_port'] = __("Price tax free with postage", "order"); $values['totalht_port_price'] = Html::clean(Html::formatNumber($total_HT)); $values['title_price_port'] = __("Postage", "order"); $values['price_port_tva'] = " (" . Html::clean(Dropdown::getDropdownName("glpi_plugin_order_ordertaxes", $this->fields["plugin_order_ordertaxes_id"])) . "%)"; $values['port_price'] = Html::clean(Html::formatNumber($postagewithTVA)); $values['title_tva'] = __("VAT", "order"); $values['totaltva'] = Html::clean(Html::formatNumber($total_TVA)); $values['title_totalttc'] = __("Price ATI", "order"); $values['totalttc'] = Html::clean(Html::formatNumber($total_TTC)); $values['title_money'] = __("€", "order"); $values['title_sign'] = __("Signature of issuing order", "order"); $values['title_conditions'] = __("Payment conditions", "order"); $values['payment_conditions'] = $name; // Set variables in odt template foreach ($values as $field => $val) { try { $odf->setVars($field, $val, true, 'UTF-8'); } catch (\Odtphp\Exceptions\OdfException $e) { } } } $message = "_"; if (Session::isMultiEntitiesMode()) { $entity = new Entity(); $entity->getFromDB($this->fields['entities_id']); $message .= $entity->getName(); } $message .= "_" . $this->fields['num_order'] . "_"; $message .= Html::convDateTime($_SESSION['glpi_currenttime']); $message = str_replace(" ", "_", $message); $outputfile = str_replace(".odt", $message . ".odt", $template); // We export the file $odf->exportAsAttachedFile($outputfile); } }
/** * @since version 0.84 **/ function getRootEntityName() { if (isset($_SESSION['glpirootentityname'])) { return $_SESSION['glpirootentityname']; } $entity = new Entity(); if ($entity->getFromDB(0)) { $_SESSION['glpirootentityname'] = $entity->fields['name']; } else { $_SESSION['glpirootentityname'] = 'No root entity / DB troubles'; } return $_SESSION['glpirootentityname']; }
/** * Update from 0.83.1 to 0.84 * * @return bool for success (will die for most error) **/ function update0831to084() { global $DB, $migration; $updateresult = true; $ADDTODISPLAYPREF = array(); //TRANS: %s is the number of new version $migration->displayTitle(sprintf(__('Update to %s'), '0.84')); $migration->setVersion('0.84'); // Add the internet field and copy rights from networking $migration->addField('glpi_profiles', 'internet', 'char', array('after' => 'networking', 'update' => '`networking`')); $backup_tables = false; $newtables = array('glpi_contractcosts', 'glpi_entities_rssfeeds', 'glpi_groups_rssfeeds', 'glpi_problems_suppliers', 'glpi_profiles_rssfeeds', 'glpi_rssfeeds_users', 'glpi_rssfeeds', 'glpi_suppliers_tickets', 'glpi_ticketcosts'); foreach ($newtables as $new_table) { // rename new tables if exists ? if (TableExists($new_table)) { $migration->dropTable("backup_{$new_table}"); $migration->displayWarning("{$new_table} table already exists. " . "A backup have been done to backup_{$new_table}."); $backup_tables = true; $query = $migration->renameTable("{$new_table}", "backup_{$new_table}"); } } if ($backup_tables) { $migration->displayWarning("You can delete backup tables if you have no need of them.", true); } updateNetworkFramework($ADDTODISPLAYPREF); $migration->addField('glpi_mailcollectors', 'accepted', 'string'); $migration->addField('glpi_mailcollectors', 'refused', 'string'); $migration->addField('glpi_mailcollectors', 'use_kerberos', 'bool', array('value' => 0)); $migration->addField("glpi_mailcollectors", 'errors', "integer"); $migration->addField("glpi_mailcollectors", 'use_mail_date', "bool", array('value' => 0)); // Password security $migration->addField('glpi_configs', 'use_password_security', 'bool'); $migration->addField('glpi_configs', 'password_min_length', 'integer', array('value' => 8)); $migration->addField('glpi_configs', 'password_need_number', 'bool', array('value' => 1)); $migration->addField('glpi_configs', 'password_need_letter', 'bool', array('value' => 1)); $migration->addField('glpi_configs', 'password_need_caps', 'bool', array('value' => 1)); $migration->addField('glpi_configs', 'password_need_symbol', 'bool', array('value' => 1)); $migration->addField('glpi_configs', 'use_check_pref', 'bool'); // Ajax buffer time $migration->addField('glpi_configs', 'ajax_buffertime_load', 'integer', array('value' => 0, 'after' => 'ajax_min_textsearch_load')); // Clean display prefs $query = "UPDATE `glpi_displaypreferences`\n SET `num` = 160\n WHERE `itemtype` = 'Software'\n AND `num` = 7"; $DB->query($query); // Update bookmarks from States to AllAssets foreach ($DB->request("glpi_bookmarks", "`itemtype` = 'States'") as $data) { $query = str_replace('itemtype=States', 'itemtype=AllAssets', $data['query']); $query = "UPDATE `glpi_bookmarks`\n SET query = '" . addslashes($query) . "'\n WHERE `id` = '" . $data['id'] . "'"; $DB->query($query); } $query = "UPDATE `glpi_bookmarks`\n SET `itemtype` = 'AllAssets', `path` = 'front/allassets.php'\n WHERE `itemtype` = 'States'"; $DB->query($query); $query = "UPDATE `glpi_displaypreferences`\n SET `itemtype` = 'AllAssets'\n WHERE `itemtype` = 'States'"; $DB->query($query); if (TableExists('glpi_networkportmigrations')) { $migration->displayWarning("You should have a look at the \"migration cleaner\" tool !", true); $migration->displayWarning("With it, you should re-create the networks topologies and the links between the networks and the addresses", true); } $lang_to_update = array('ca_CA' => 'ca_ES', 'dk_DK' => 'da_DK', 'ee_ET' => 'et_EE', 'el_EL' => 'el_GR', 'he_HE' => 'he_IL', 'no_NB' => 'nb_NO', 'no_NN' => 'nn_NO', 'ua_UA' => 'uk_UA'); foreach ($lang_to_update as $old => $new) { $query = "UPDATE `glpi_configs`\n SET `language` = '{$new}'\n WHERE `language` = '{$old}';"; $DB->queryOrDie($query, "0.84 language in config {$old} to {$new}"); $query = "UPDATE `glpi_users`\n SET `language` = '{$new}'\n WHERE `language` = '{$old}';"; $DB->queryOrDie($query, "0.84 language in users {$old} to {$new}"); } $migration->displayMessage(sprintf(__('Data migration - %s'), 'tickets and problems status')); $status = array('new' => CommonITILObject::INCOMING, 'assign' => CommonITILObject::ASSIGNED, 'plan' => CommonITILObject::PLANNED, 'waiting' => CommonITILObject::WAITING, 'solved' => CommonITILObject::SOLVED, 'closed' => CommonITILObject::CLOSED, 'accepted' => CommonITILObject::ACCEPTED, 'observe' => CommonITILObject::OBSERVED, 'evaluation' => CommonITILObject::EVALUATION, 'approbation' => CommonITILObject::APPROVAL, 'test' => CommonITILObject::TEST, 'qualification' => CommonITILObject::QUALIFICATION); foreach (array('glpi_tickets', 'glpi_problems') as $table) { // Migrate datas foreach ($status as $old => $new) { $query = "UPDATE `{$table}`\n SET `status` = '{$new}'\n WHERE `status` = '{$old}'"; $DB->queryOrDie($query, "0.84 status in {$table} {$old} to {$new}"); } $migration->changeField($table, 'status', 'status', 'integer', array('value' => CommonITILObject::INCOMING)); } // Migrate templates $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_notificationtemplatetranslations`.`content_text` LIKE '%storestatus=%'\n OR `glpi_notificationtemplatetranslations`.`content_html` LIKE '%storestatus=%'\n OR `glpi_notificationtemplatetranslations`.`subject` LIKE '%storestatus=%'"; if ($result = $DB->query($query)) { if ($DB->numrows($result)) { while ($data = $DB->fetch_assoc($result)) { $subject = $data['subject']; $text = $data['content_text']; $html = $data['content_html']; foreach ($status as $old => $new) { $subject = str_replace("ticket.storestatus={$old}", "ticket.storestatus={$new}", $subject); $text = str_replace("ticket.storestatus={$old}", "ticket.storestatus={$new}", $text); $html = str_replace("ticket.storestatus={$old}", "ticket.storestatus={$new}", $html); $subject = str_replace("problem.storestatus={$old}", "problem.storestatus={$new}", $subject); $text = str_replace("problem.storestatus={$old}", "problem.storestatus={$new}", $text); $html = str_replace("problem.storestatus={$old}", "problem.storestatus={$new}", $html); } $query = "UPDATE `glpi_notificationtemplatetranslations`\n SET `subject` = '" . addslashes($subject) . "',\n `content_text` = '" . addslashes($text) . "',\n `content_html` = '" . addslashes($html) . "'\n WHERE `id` = " . $data['id'] . ""; $DB->queryOrDie($query, "0.84 fix tags usage for storestatus"); } } } // Update Rules $changes = array(); $changes['RuleTicket'] = 'status'; $DB->query("SET SESSION group_concat_max_len = 4194304;"); foreach ($changes as $ruletype => $field) { // 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 ($status as $old => $new) { $query = "UPDATE `glpi_ruleactions`\n SET `value` = '{$new}'\n WHERE `field` = '{$field}'\n AND `value` = '{$old}'\n AND `rules_id` IN ({$rules})"; $DB->queryOrDie($query, "0.84 update datas for rules actions"); } } } } // Update glpi_profiles : ticket_status foreach ($DB->request('glpi_profiles') as $data) { $fields_to_decode = array('ticket_status', 'problem_status'); foreach ($fields_to_decode as $field) { $tab = importArrayFromDB($data[$field]); if (is_array($tab)) { $newtab = array(); foreach ($tab as $key => $values) { foreach ($values as $key2 => $val2) { $newtab[$status[$key]][$status[$key2]] = $val2; } } $query = "UPDATE `glpi_profiles`\n SET `{$field}` = '" . addslashes(exportArrayToDB($newtab)) . "'\n WHERE `id` = '" . $data['id'] . "'"; $DB->queryOrDie($query, "0.84 migrate {$field} of glpi_profiles"); } } } $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Merge entity and entitydatas')); if (TableExists('glpi_entitydatas')) { $migration->changeField('glpi_entities', 'id', 'id', 'integer'); $migration->migrationOneTable('glpi_entities'); // pour que la procedure soit re-entrante if (countElementsInTable("glpi_entities", "id=0") < 1) { // Create root entity $query = "INSERT INTO `glpi_entities`\n (`id`, `name`, `completename`, `entities_id`, `level`)\n VALUES (0,'" . addslashes(__('Root entity')) . "',\n '" . addslashes(__('Root entity')) . "', '-1', '1');"; $DB->queryOrDie($query, '0.84 insert root entity into glpi_entities'); } // $newID = $DB->insert_id(); // $query = "UPDATE `glpi_entities` // SET `id` = '0' // WHERE `id` = '$newID'"; // $DB->queryOrDie($query, '0.84 be sure that id of the root entity if 0 in glpi_entities'); $migration->addField("glpi_entities", 'address', "text"); $migration->addField("glpi_entities", 'postcode', "string"); $migration->addField("glpi_entities", 'town', "string"); $migration->addField("glpi_entities", 'state', "string"); $migration->addField("glpi_entities", 'country', "string"); $migration->addField("glpi_entities", 'website', "string"); $migration->addField("glpi_entities", 'phonenumber', "string"); $migration->addField("glpi_entities", 'fax', "string"); $migration->addField("glpi_entities", 'email', "string"); $migration->addField("glpi_entities", 'admin_email', "string"); $migration->addField("glpi_entities", 'admin_email_name', "string"); $migration->addField("glpi_entities", 'admin_reply', "string"); $migration->addField("glpi_entities", 'admin_reply_name', "string"); $migration->addField("glpi_entities", 'notification_subject_tag', "string"); $migration->addField("glpi_entities", 'notepad', "longtext"); $migration->addField("glpi_entities", 'ldap_dn', "string"); $migration->addField("glpi_entities", 'tag', "string"); $migration->addField("glpi_entities", 'authldaps_id', "integer"); $migration->addField("glpi_entities", 'mail_domain', "string"); $migration->addField("glpi_entities", 'entity_ldapfilter', "text"); $migration->addField("glpi_entities", 'mailing_signature', "text"); $migration->addField("glpi_entities", 'cartridges_alert_repeat', "integer", array('value' => -2)); $migration->addField("glpi_entities", 'consumables_alert_repeat', "integer", array('value' => -2)); $migration->addField("glpi_entities", 'use_licenses_alert', "integer", array('value' => -2)); $migration->addField("glpi_entities", 'use_contracts_alert', "integer", array('value' => -2)); $migration->addField("glpi_entities", 'use_infocoms_alert', "integer", array('value' => -2)); $migration->addField("glpi_entities", 'use_reservations_alert', "integer", array('value' => -2)); $migration->addField("glpi_entities", 'autoclose_delay', "integer", array('value' => -2)); $migration->addField("glpi_entities", 'notclosed_delay', "integer", array('value' => -2)); $migration->addField("glpi_entities", 'calendars_id', "integer", array('value' => -2)); $migration->addField("glpi_entities", 'auto_assign_mode', "integer", array('value' => -2)); $migration->addField("glpi_entities", 'tickettype', "integer", array('value' => -2)); $migration->addField("glpi_entities", 'max_closedate', "datetime"); $migration->addField("glpi_entities", 'inquest_config', "integer", array('value' => -2)); $migration->addField("glpi_entities", 'inquest_rate', "integer"); $migration->addField("glpi_entities", 'inquest_delay', "integer", array('value' => -10)); $migration->addField("glpi_entities", 'inquest_URL', "string"); $migration->addField("glpi_entities", 'autofill_warranty_date', "string", array('value' => -2)); $migration->addField("glpi_entities", 'autofill_use_date', "string", array('value' => -2)); $migration->addField("glpi_entities", 'autofill_buy_date', "string", array('value' => -2)); $migration->addField("glpi_entities", 'autofill_delivery_date', "string", array('value' => -2)); $migration->addField("glpi_entities", 'autofill_order_date', "string", array('value' => -2)); $migration->addField("glpi_entities", 'tickettemplates_id', "integer", array('value' => -2)); $migration->addField("glpi_entities", 'entities_id_software', "integer", array('value' => -2)); $migration->addField("glpi_entities", 'default_contract_alert', "integer", array('value' => -2)); $migration->addField("glpi_entities", 'default_infocom_alert', "integer", array('value' => -2)); $migration->addField("glpi_entities", 'default_alarm_threshold', "integer", array('value' => -2)); $migration->migrationOneTable('glpi_entities'); $fields = array('address', 'postcode', 'town', 'state', 'country', 'website', 'phonenumber', 'fax', 'email', 'admin_email', 'admin_email_name', 'admin_reply', 'admin_reply_name', 'notification_subject_tag', 'notepad', 'ldap_dn', 'tag', 'authldaps_id', 'mail_domain', 'entity_ldapfilter', 'mailing_signature', 'cartridges_alert_repeat', 'consumables_alert_repeat', 'use_licenses_alert', 'use_contracts_alert', 'use_infocoms_alert', 'use_reservations_alert', 'autoclose_delay', 'notclosed_delay', 'calendars_id', 'auto_assign_mode', 'tickettype', 'max_closedate', 'inquest_config', 'inquest_rate', 'inquest_delay', 'inquest_URL', 'autofill_warranty_date', 'autofill_use_date', 'autofill_buy_date', 'autofill_delivery_date', 'autofill_order_date', 'tickettemplates_id', 'entities_id_software', 'default_contract_alert', 'default_infocom_alert', 'default_alarm_threshold'); $entity = new Entity(); foreach ($DB->request('glpi_entitydatas') as $data) { if ($entity->getFromDB($data['entities_id'])) { $update_fields = array(); foreach ($fields as $field) { if (is_null($data[$field])) { $update_fields[] = "`{$field}` = NULL"; } else { $update_fields[] = "`{$field}` = '" . addslashes($data[$field]) . "'"; } } $query = "UPDATE `glpi_entities`\n SET " . implode(',', $update_fields) . "\n WHERE `id` = '" . $data['entities_id'] . "'"; $DB->queryOrDie($query, "0.84 transfer datas from glpi_entitydatas to glpi_entities"); } else { $migration->displayMessage('Entity ID ' . $data['entities_id'] . ' does not exist'); } } $migration->dropTable('glpi_entitydatas'); } regenerateTreeCompleteName("glpi_entities"); $migration->displayMessage(sprintf(__('Data migration - %s'), 'copy entity information to computers_softwareversions')); if ($migration->addField("glpi_computers_softwareversions", "entities_id", "integer")) { $migration->migrationOneTable('glpi_computers_softwareversions'); $query3 = "UPDATE `glpi_computers_softwareversions`\n LEFT JOIN `glpi_computers`\n ON `computers_id`=`glpi_computers`.`id`\n SET `glpi_computers_softwareversions`.`entities_id` = `glpi_computers`.`entities_id`"; $DB->queryOrDie($query3, "0.84 update entities_id in glpi_computers_softwareversions"); /// create index for search count on tab $migration->addKey("glpi_computers_softwareversions", array('entities_id', 'is_template', 'is_deleted'), 'computers_info'); $migration->addKey("glpi_computers_softwareversions", 'is_template'); $migration->addKey("glpi_computers_softwareversions", 'is_deleted'); } /// create new index for search $migration->addKey("glpi_softwarelicenses", array('softwares_id', 'expire'), 'softwares_id_expire'); $migration->dropKey("glpi_softwarelicenses", 'softwares_id'); $migration->displayMessage(sprintf(__('Data migration - %s'), 'create validation_answer notification')); // Check if notifications already exists if (countElementsInTable('glpi_notifications', "`itemtype` = 'Ticket'\n AND `event` = 'validation_answer'") == 0) { // No notifications duplicate all $query = "SELECT *\n FROM `glpi_notifications`\n WHERE `itemtype` = 'Ticket'\n AND `event` = 'validation'"; foreach ($DB->request($query) as $notif) { $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 ('" . addslashes($notif['name']) . " Answer',\n '" . $notif['entities_id'] . "', 'Ticket',\n 'validation_answer', '" . $notif['mode'] . "',\n '" . $notif['notificationtemplates_id'] . "',\n '" . addslashes($notif['comment']) . "', '" . $notif['is_recursive'] . "',\n '" . $notif['is_active'] . "', NOW());"; $DB->queryOrDie($query, "0.84 insert validation_answer notification"); $newID = $DB->insert_id(); $query2 = "SELECT *\n FROM `glpi_notificationtargets`\n WHERE `notifications_id` = '" . $notif['id'] . "'"; foreach ($DB->request($query2) as $target) { $query = "INSERT INTO `glpi_notificationtargets`\n (`notifications_id`, `type`, `items_id`)\n VALUES ({$newID}, '" . $target['type'] . "', '" . $target['items_id'] . "')"; $DB->queryOrDie($query, "0.84 insert targets for validation_answer notification"); } } } $migration->displayMessage(sprintf(__('Data migration - %s'), 'create contracts notification')); $from_to = array('end' => 'periodicity', 'notice' => 'periodicitynotice'); foreach ($from_to as $from => $to) { // Check if notifications already exists if (countElementsInTable('glpi_notifications', "`itemtype` = 'Contract' AND `event` = '{$to}'") == 0) { // No notifications duplicate all $query = "SELECT *\n FROM `glpi_notifications`\n WHERE `itemtype` = 'Contract'\n AND `event` = '{$from}'"; foreach ($DB->request($query) as $notif) { $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 ('" . addslashes($notif['name']) . " Periodicity',\n '" . $notif['entities_id'] . "', 'Contract', '{$to}', '" . $notif['mode'] . "',\n '" . $notif['notificationtemplates_id'] . "',\n '" . addslashes($notif['comment']) . "', '" . $notif['is_recursive'] . "',\n '" . $notif['is_active'] . "', NOW());"; $DB->queryOrDie($query, "0.84 insert contract " . $to . " notification"); $newID = $DB->insert_id(); $query2 = "SELECT *\n FROM `glpi_notificationtargets`\n WHERE `notifications_id` = '" . $notif['id'] . "'"; foreach ($DB->request($query2) as $target) { $query = "INSERT INTO `glpi_notificationtargets`\n (`notifications_id`, `type`, `items_id`)\n VALUES ('" . $newID . "', '" . $target['type'] . "', '" . $target['items_id'] . "')"; $DB->queryOrDie($query, "0.84 insert targets for ĉontract " . $to . " notification"); } } } } $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'contract and ticket costs')); if (!TableExists('glpi_contractcosts')) { $query = "CREATE TABLE `glpi_contractcosts` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `contracts_id` int(11) NOT NULL DEFAULT '0',\n `name` varchar(255) DEFAULT NULL,\n `comment` text COLLATE utf8_unicode_ci,\n `begin_date` date DEFAULT NULL,\n `end_date` date DEFAULT NULL,\n `cost` decimal(20,4) NOT NULL DEFAULT '0.0000',\n `budgets_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 PRIMARY KEY (`id`),\n KEY `name` (`name`),\n KEY `contracts_id` (`contracts_id`),\n KEY `begin_date` (`begin_date`),\n KEY `end_date` (`end_date`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`),\n KEY `budgets_id` (`budgets_id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.84 add table glpi_contractcosts"); $migration->migrationOneTable('glpi_contractcosts'); foreach ($DB->request('glpi_contracts', "`cost` > 0") as $data) { $begin_to_add = "NULL"; $end_to_add = "NULL"; if (!is_null($data['begin_date'])) { $begin_to_add = "'" . $data['begin_date'] . "'"; if ($data['duration']) { $end_to_add = "'" . date("Y-m-d", strtotime($data['begin_date'] . "+" . $data['duration'] . " month")) . "'"; } else { $end_to_add = "'" . $data['begin_date'] . "'"; } } $query = "INSERT INTO `glpi_contractcosts`\n (`contracts_id`, `name`, `begin_date`, `end_date`,\n `cost`, `entities_id`,\n `is_recursive`)\n VALUES ('" . $data['id'] . "', 'Cost', {$begin_to_add}, {$end_to_add},\n '" . $data['cost'] . "', '" . $data['entities_id'] . "',\n '" . $data['is_recursive'] . "')"; $DB->queryOrDie($query, '0.84 move contracts costs'); } $migration->dropField('glpi_contracts', 'cost'); } if (!TableExists('glpi_ticketcosts')) { $query = "CREATE TABLE `glpi_ticketcosts` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `tickets_id` int(11) NOT NULL DEFAULT '0',\n `name` varchar(255) DEFAULT NULL,\n `comment` text COLLATE utf8_unicode_ci,\n `begin_date` date DEFAULT NULL,\n `end_date` date DEFAULT NULL,\n `actiontime` int(11) NOT NULL DEFAULT '0',\n `cost_time` decimal(20,4) NOT NULL DEFAULT '0.0000',\n `cost_fixed` decimal(20,4) NOT NULL DEFAULT '0.0000',\n `cost_material` decimal(20,4) NOT NULL DEFAULT '0.0000',\n `budgets_id` int(11) NOT NULL DEFAULT '0',\n `entities_id` int(11) NOT NULL DEFAULT '0',\n PRIMARY KEY (`id`),\n KEY `name` (`name`),\n KEY `tickets_id` (`tickets_id`),\n KEY `begin_date` (`begin_date`),\n KEY `end_date` (`end_date`),\n KEY `entities_id` (`entities_id`),\n KEY `budgets_id` (`budgets_id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.84 add table glpi_ticketcosts"); $migration->migrationOneTable('glpi_ticketcosts'); foreach ($DB->request('glpi_tickets', "`cost_time` > 0\n OR `cost_fixed` > 0\n OR `cost_material` > 0") as $data) { $begin_to_add = "NULL"; $end_to_add = "NULL"; if (!is_null($data['date'])) { $begin_to_add = "'" . $data['date'] . "'"; if (!is_null($data['solvedate'])) { $end_to_add = "'" . $data['solvedate'] . "'"; } else { $end_to_add = "'" . $data['date'] . "'"; } } $query = "INSERT INTO `glpi_ticketcosts`\n (`tickets_id`, `name`, `begin_date`, `end_date`,\n `cost_time`,`cost_fixed`,\n `cost_material`, `entities_id`,\n `actiontime`)\n VALUES ('" . $data['id'] . "', 'Cost', {$begin_to_add}, {$end_to_add},\n '" . $data['cost_time'] . "','" . $data['cost_fixed'] . "',\n '" . $data['cost_material'] . "', '" . $data['entities_id'] . "',\n '" . $data['actiontime'] . "')"; $DB->queryOrDie($query, '0.84 move tickets costs'); } $migration->dropField('glpi_tickets', 'cost_time'); $migration->dropField('glpi_tickets', 'cost_fixed'); $migration->dropField('glpi_tickets', 'cost_material'); } $migration->addField("glpi_profiles", "ticketcost", "char", array('update' => "'w'", 'condition' => " WHERE `update_ticket` = 1")); // Set default to r as before $query = "UPDATE `glpi_profiles`\n SET `ticketcost` = 'r'\n WHERE `ticketcost` IS NULL"; $DB->queryOrDie($query, "0.84 set ticketcost in glpi_profiles"); $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'rss flows')); if (!TableExists('glpi_rssfeeds')) { $query = "CREATE TABLE `glpi_rssfeeds` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `name` varchar(255) DEFAULT NULL,\n `users_id` int(11) NOT NULL DEFAULT '0',\n `comment` text COLLATE utf8_unicode_ci,\n `url` text COLLATE utf8_unicode_ci,\n `refresh_rate` int(11) NOT NULL DEFAULT '86400',\n `max_items` int(11) NOT NULL DEFAULT '20',\n `have_error` TINYINT( 1 ) NOT NULL DEFAULT 0,\n `is_active` TINYINT( 1 ) NOT NULL DEFAULT 0,\n `date_mod` DATETIME DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `name` (`name`),\n KEY `users_id` (`users_id`),\n KEY `date_mod` (`date_mod`),\n KEY `have_error` (`have_error`),\n KEY `is_active` (`is_active`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.84 add table glpi_rssfeeds"); $ADDTODISPLAYPREF['RSSFeed'] = array(2, 4, 5, 19, 6, 7); } if (!TableExists('glpi_rssfeeds_users')) { $query = "CREATE TABLE `glpi_rssfeeds_users` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `rssfeeds_id` int(11) NOT NULL DEFAULT '0',\n `users_id` int(11) NOT NULL DEFAULT '0',\n PRIMARY KEY (`id`),\n KEY `rssfeeds_id` (`rssfeeds_id`),\n KEY `users_id` (`users_id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.84 add table glpi_rssfeeds_users"); } if (!TableExists('glpi_groups_rssfeeds')) { $query = "CREATE TABLE `glpi_groups_rssfeeds` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `rssfeeds_id` int(11) NOT NULL DEFAULT '0',\n `groups_id` int(11) NOT NULL DEFAULT '0',\n `entities_id` int(11) NOT NULL DEFAULT '-1',\n `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n PRIMARY KEY (`id`),\n KEY `rssfeeds_id` (`rssfeeds_id`),\n KEY `groups_id` (`groups_id`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`)\n\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.84 add table glpi_groups_rssfeeds"); } if (!TableExists('glpi_profiles_rssfeeds')) { $query = "CREATE TABLE `glpi_profiles_rssfeeds` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `rssfeeds_id` int(11) NOT NULL DEFAULT '0',\n `profiles_id` int(11) NOT NULL DEFAULT '0',\n `entities_id` int(11) NOT NULL DEFAULT '-1',\n `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n PRIMARY KEY (`id`),\n KEY `rssfeeds_id` (`rssfeeds_id`),\n KEY `profiles_id` (`profiles_id`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.84 add table glpi_profiles_rssfeeds"); } if (!TableExists('glpi_entities_rssfeeds')) { $query = "CREATE TABLE `glpi_entities_rssfeeds` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `rssfeeds_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 PRIMARY KEY (`id`),\n KEY `rssfeeds_id` (`rssfeeds_id`),\n KEY `entities_id` (`entities_id`),\n KEY `is_recursive` (`is_recursive`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.84 add table glpi_entities_rssfeeds"); } $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'planning recalls')); if (!TableExists('glpi_planningrecalls')) { $query = "CREATE TABLE `glpi_planningrecalls` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `items_id` int(11) NOT NULL DEFAULT '0',\n `itemtype` varchar(100) COLLATE utf8_unicode_ci NOT NULL,\n `users_id` int(11) NOT NULL DEFAULT '0',\n `before_time` int(11) NOT NULL DEFAULT '-10',\n `when` datetime DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `users_id` (`users_id`),\n KEY `before_time` (`before_time`),\n KEY `when` (`when`),\n UNIQUE KEY `unicity` (`itemtype`,`items_id`, `users_id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.84 add table glpi_planningrecalls"); } $query = "SELECT *\n FROM `glpi_notificationtemplates`\n WHERE `itemtype` = 'PlanningRecall'"; if ($result = $DB->query($query)) { if ($DB->numrows($result) == 0) { $query = "INSERT INTO `glpi_notificationtemplates`\n (`name`, `itemtype`, `date_mod`)\n VALUES ('Planning recall', 'PlanningRecall', NOW())"; $DB->queryOrDie($query, "0.84 add planning recall notification"); $notid = $DB->insert_id(); $query = "INSERT INTO `glpi_notificationtemplatetranslations`\n (`notificationtemplates_id`, `language`, `subject`,\n `content_text`,\n `content_html`)\n VALUES ({$notid}, '', '##recall.action##: ##recall.item.name##',\n '##recall.action##: ##recall.item.name##\n\n##recall.item.content##\n\n##lang.recall.planning.begin##: ##recall.planning.begin##\n##lang.recall.planning.end##: ##recall.planning.end##\n##lang.recall.planning.state##: ##recall.planning.state##\n##lang.recall.item.private##: ##recall.item.private##',\n'<p>##recall.action##: <a href=\"##recall.item.url##\">##recall.item.name##</a></p>\n<p>##recall.item.content##</p>\n<p>##lang.recall.planning.begin##: ##recall.planning.begin##<br />##lang.recall.planning.end##: ##recall.planning.end##<br />##lang.recall.planning.state##: ##recall.planning.state##<br />##lang.recall.item.private##: ##recall.item.private##<br /><br /></p>\n<p><br /><br /></p>')"; $DB->queryOrDie($query, "0.84 add planning recall 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 ('Planning recall', 0, 'PlanningRecall', 'planningrecall', 'mail',\n {$notid}, '', 1, 1, NOW())"; $DB->queryOrDie($query, "0.84 add planning recall notification"); $notifid = $DB->insert_id(); $query = "INSERT INTO `glpi_notificationtargets`\n (`id`, `notifications_id`, `type`, `items_id`)\n VALUES (NULL, {$notifid}, " . Notification::USER_TYPE . ", " . Notification::AUTHOR . ");"; $DB->queryOrDie($query, "0.84 add planning recall notification target"); } } if (!countElementsInTable('glpi_crontasks', "`itemtype`='PlanningRecall' AND `name`='planningrecall'")) { $query = "INSERT INTO `glpi_crontasks`\n (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n VALUES ('PlanningRecall', 'planningrecall', 300, NULL, 1, 1, 3,\n 0, 24, 30, NULL, NULL, NULL)"; $DB->queryOrDie($query, "0.84 populate glpi_crontasks for planningrecall"); } $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'various fields')); $migration->changeField('glpi_entities', 'default_alarm_threshold', 'default_cartridges_alarm_threshold', 'integer', array('value' => -2)); $migration->migrationOneTable('glpi_entities'); $migration->addField("glpi_entities", 'default_consumables_alarm_threshold', "integer", array('value' => -2, 'update' => 'default_cartridges_alarm_threshold')); $migration->migrationOneTable('glpi_entities'); // move -1 to Entity::CONFIG_NEVER $query = 'UPDATE `glpi_entities` SET `default_consumables_alarm_threshold` = -10 WHERE `default_consumables_alarm_threshold` = -1'; $DB->query($query); $query = 'UPDATE `glpi_entities` SET `default_cartridges_alarm_threshold` = -10 WHERE `default_cartridges_alarm_threshold` = -1'; $DB->query($query); $migration->addField("glpi_entities", 'send_contracts_alert_before_delay', "integer", array('value' => -2, 'after' => 'use_contracts_alert', 'update' => '0', 'condition' => 'WHERE `id`=0')); $migration->addField("glpi_entities", 'send_infocoms_alert_before_delay', "integer", array('value' => -2, 'after' => 'use_infocoms_alert', 'update' => '0', 'condition' => 'WHERE `id`=0')); $migration->addField("glpi_entities", 'send_licenses_alert_before_delay', "integer", array('value' => -2, 'after' => 'use_licenses_alert', 'update' => '0', 'condition' => 'WHERE `id`=0')); $migration->addField("glpi_configs", "notification_to_myself", "bool", array('value' => 1)); $migration->addField("glpi_configs", 'duedateok_color', "string", array('value' => '#06ff00')); $migration->addField("glpi_configs", 'duedatewarning_color', "string", array('value' => '#ffb800')); $migration->addField("glpi_configs", 'duedatecritical_color', "string", array('value' => '#ff0000')); $migration->addField("glpi_configs", 'duedatewarning_less', "integer", array('value' => 20)); $migration->addField("glpi_configs", 'duedatecritical_less', "integer", array('value' => 5)); $migration->addField("glpi_configs", 'duedatewarning_unit', "string", array('value' => '%')); $migration->addField("glpi_configs", 'duedatecritical_unit', "string", array('value' => '%')); $migration->addField("glpi_configs", "realname_ssofield", "string"); $migration->addField("glpi_configs", "firstname_ssofield", "string"); $migration->addField("glpi_configs", "email1_ssofield", "string"); $migration->addField("glpi_configs", "email2_ssofield", "string"); $migration->addField("glpi_configs", "email3_ssofield", "string"); $migration->addField("glpi_configs", "email4_ssofield", "string"); $migration->addField("glpi_configs", "phone_ssofield", "string"); $migration->addField("glpi_configs", "phone2_ssofield", "string"); $migration->addField("glpi_configs", "mobile_ssofield", "string"); $migration->addField("glpi_configs", "comment_ssofield", "string"); $migration->addField("glpi_configs", "title_ssofield", "string"); $migration->addField("glpi_configs", "category_ssofield", "string"); $migration->addField("glpi_configs", "language_ssofield", "string"); $migration->addField("glpi_configs", "entity_ssofield", "string"); $migration->addField("glpi_configs", "registration_number_ssofield", "string"); $migration->addField("glpi_users", "notification_to_myself", "tinyint(1) DEFAULT NULL"); $migration->addField("glpi_users", 'duedateok_color', "string"); $migration->addField("glpi_users", 'duedatewarning_color', "string"); $migration->addField("glpi_users", 'duedatecritical_color', "string"); $migration->addField("glpi_users", 'duedatewarning_less', "int(11) DEFAULT NULL"); $migration->addField("glpi_users", 'duedatecritical_less', "int(11) DEFAULT NULL"); $migration->addField("glpi_users", 'duedatewarning_unit', "string"); $migration->addField("glpi_users", 'duedatecritical_unit', "string"); $migration->addField("glpi_users", 'display_options', "text"); $migration->addField("glpi_reservationitems", "is_deleted", "bool"); $migration->addKey("glpi_reservationitems", "is_deleted"); $migration->addField("glpi_documentcategories", 'documentcategories_id', "integer"); $migration->addField("glpi_documentcategories", 'completename', "text"); $migration->addField("glpi_documentcategories", 'level', "integer"); $migration->addField("glpi_documentcategories", 'ancestors_cache', "longtext"); $migration->addField("glpi_documentcategories", 'sons_cache', "longtext"); $migration->migrationOneTable('glpi_documentcategories'); $migration->addKey("glpi_documentcategories", array('documentcategories_id', 'name'), 'unicity'); regenerateTreeCompleteName("glpi_documentcategories"); $migration->addField("glpi_contacts", 'usertitles_id', "integer"); $migration->addKey("glpi_contacts", 'usertitles_id'); $migration->addField("glpi_contacts", 'address', "text"); $migration->addField("glpi_contacts", 'postcode', "string"); $migration->addField("glpi_contacts", 'town', "string"); $migration->addField("glpi_contacts", 'state', "string"); $migration->addField("glpi_contacts", 'country', "string"); $migration->addField("glpi_configs", 'x509_ou_restrict', "string", array('after' => 'x509_email_field')); $migration->addField("glpi_configs", 'x509_o_restrict', "string", array('after' => 'x509_email_field')); $migration->addField("glpi_configs", 'x509_cn_restrict', "string", array('after' => 'x509_email_field')); if (!TableExists('glpi_slalevelcriterias')) { $query = "CREATE TABLE `glpi_slalevelcriterias` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `slalevels_id` int(11) NOT NULL DEFAULT '0',\n `criteria` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `condition` int(11) NOT NULL DEFAULT '0'\n COMMENT 'see define.php PATTERN_* and REGEX_* constant',\n `pattern` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `slalevels_id` (`slalevels_id`),\n KEY `condition` (`condition`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.84 create glpi_slalevelcriterias"); } $migration->addField("glpi_slalevels", 'match', "CHAR(10) DEFAULT NULL COMMENT 'see define.php *_MATCHING constant'"); $query = "UPDATE `glpi_slalevelactions`\n SET `action_type` = 'append'\n WHERE `action_type` = 'assign'\n AND `field` IN ('_users_id_requester', '_groups_id_requester',\n '_users_id_assign', '_groups_id_assign',\n '_suppliers_id_assign', '_users_id_observer',\n '_groups_id_observer');"; $DB->queryOrDie($query, "0.84 update data for SLA actors add"); // Clean observer as recipient of satisfaction survey $query = "DELETE FROM `glpi_notificationtargets`\n WHERE `glpi_notificationtargets`.`type` = '" . Notification::USER_TYPE . "'\n AND `glpi_notificationtargets`.`items_id` = '" . Notification::OBSERVER . "'\n AND `notifications_id` IN (SELECT `glpi_notifications`.`id`\n FROM `glpi_notifications`\n WHERE `glpi_notifications`.`itemtype` = 'Ticket'\n AND `glpi_notifications`.`event` = 'satisfaction')"; $DB->queryOrDie($query, "0.84 clean targets for satisfaction notification"); // Clean user as recipient of item not unique $query = "DELETE FROM `glpi_notificationtargets`\n WHERE `glpi_notificationtargets`.`type` = '" . Notification::USER_TYPE . "'\n AND `glpi_notificationtargets`.`items_id` = '" . Notification::USER . "'\n AND `notifications_id` IN (SELECT `glpi_notifications`.`id`\n FROM `glpi_notifications`\n WHERE `glpi_notifications`.`itemtype` = 'FieldUnicity'\n AND `glpi_notifications`.`event` = 'refuse')"; $DB->queryOrDie($query, "0.84 clean targets for fieldunicity notification"); if (!TableExists('glpi_blacklists')) { $query = "CREATE TABLE `glpi_blacklists` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `type` int(11) NOT NULL DEFAULT '0',\n `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `value` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `comment` text COLLATE utf8_unicode_ci,\n PRIMARY KEY (`id`),\n KEY `type` (`type`),\n KEY `name` (`name`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.84 create glpi_blacklists"); $ADDTODISPLAYPREF['Blacklist'] = array(12, 11); $toinsert = array(Blacklist::IP => array('empty IP' => '', 'localhost' => '127.0.0.1', 'zero IP' => '0.0.0.0'), Blacklist::MAC => array('empty MAC' => '')); foreach ($toinsert as $type => $datas) { if (count($datas)) { foreach ($datas as $name => $value) { $query = "INSERT INTO `glpi_blacklists`\n (`type`,`name`,`value`)\n VALUES ('{$type}','" . addslashes($name) . "','" . addslashes($value) . "')"; $DB->queryOrDie($query, "0.84 insert datas to glpi_blacklists"); } } } } $query = "SELECT `id`\n FROM `glpi_rulerightparameters`\n WHERE `name` = '(LDAP) MemberOf'"; $result = $DB->query($query); if (!$DB->numrows($result)) { $query = "INSERT INTO `glpi_rulerightparameters`\n VALUES (NULL, '(LDAP) MemberOf', 'memberof', '')"; $DB->queryOrDie($query, "0.84 insert (LDAP) MemberOf in glpi_rulerightparameters"); } if (!TableExists('glpi_ssovariables')) { $query = "CREATE TABLE `glpi_ssovariables` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n `comment` text COLLATE utf8_unicode_ci NOT NULL,\n PRIMARY KEY (`id`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.84 create glpi_ssovariables"); $query = "INSERT INTO `glpi_ssovariables`\n (`id`, `name`, `comment`)\n VALUES (1, 'HTTP_AUTH_USER', ''),\n (2, 'REMOTE_USER', ''),\n (3, 'PHP_AUTH_USER', ''),\n (4, 'USERNAME', ''),\n (5, 'REDIRECT_REMOTE_USER', ''),\n (6, 'HTTP_REMOTE_USER', '')"; $DB->queryOrDie($query, "0.84 add values from glpi_ssovariables"); } if ($migration->addField('glpi_configs', 'ssovariables_id', 'integer')) { $migration->migrationOneTable('glpi_configs'); //Get configuration $query = "SELECT `existing_auth_server_field`\n FROM `glpi_configs`"; $result = $DB->query($query); $existing_auth_server_field = $DB->result($result, 0, "existing_auth_server_field"); if ($existing_auth_server_field) { //Get dropdown value for existing_auth_server_field $query = "SELECT `id`\n FROM `glpi_ssovariables`\n WHERE `name` = '{$existing_auth_server_field}'"; $result = $DB->query($query); //Update config if ($DB->numrows($result) > 0) { $query = "UPDATE `glpi_configs`\n SET `ssovariables_id` = '" . $DB->result($result, 0, "id") . "'"; $DB->queryOrDie($query, "0.84 update glpi_configs"); } //Drop old field } } $migration->dropField('glpi_configs', 'existing_auth_server_field'); //Remove field to specify an ldap server for SSO users : don't need it anymore $migration->dropField('glpi_configs', 'authldaps_id_extra'); // Clean uneeded logs $cleancondition = array(); $cleancondition['reminder_kb'] = "`itemtype` IN ('Entity', 'User', 'Profile', 'Group')\n AND `itemtype_link` IN ('Reminder', 'Knowbase')"; foreach ($cleancondition as $name => $condition) { $query = "DELETE\n FROM `glpi_logs`\n WHERE {$condition}"; $DB->queryOrDie($query, "0.84 clean logs for {$name}"); } //Remove OCS tables from GLPI's core $migration->renameTable('glpi_ocsadmininfoslinks', 'ocs_glpi_ocsadmininfoslinks'); $migration->renameTable('glpi_ocslinks', 'ocs_glpi_ocslinks'); $migration->renameTable('glpi_ocsservers', 'ocs_glpi_ocsservers'); $migration->renameTable('glpi_registrykeys', 'ocs_glpi_registrykeys'); // Migrate RuleOcs to RuleImportEntity $query = "UPDATE `glpi_rules`\n SET `sub_type` = 'RuleImportEntity'\n WHERE `sub_type` = 'RuleOcs'"; $DB->queryOrDie($query, "0.84 update datas for old OCS rules"); $migration->copyTable('glpi_rules', 'ocs_glpi_rules'); $migration->copyTable('glpi_ruleactions', 'ocs_glpi_ruleactions'); $migration->copyTable('glpi_rulecriterias', 'ocs_glpi_rulecriterias'); // Delete OCS rules $DB->query("SET SESSION group_concat_max_len = 4194304;"); $query = "SELECT GROUP_CONCAT(`id`)\n FROM `glpi_rules`\n WHERE `sub_type` = 'RuleImportEntity'\n GROUP BY `sub_type`"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { // Get rule string $rules = $DB->result($result, 0, 0); $query = "DELETE\n FROM `glpi_ruleactions`\n WHERE `rules_id` IN ({$rules})"; $DB->queryOrDie($query, "0.84 clean RuleImportEntity datas"); $query = "DELETE\n FROM `glpi_rulecriterias`\n WHERE `rules_id` IN ({$rules})"; $DB->queryOrDie($query, "0.84 clean RuleImportEntity datas"); $query = "DELETE\n FROM `glpi_rules`\n WHERE `id` IN ({$rules})"; $DB->queryOrDie($query, "0.84 clean RuleImportEntity datas"); } } // copy table to keep value of fields deleted after $migration->copyTable('glpi_profiles', 'ocs_glpi_profiles'); $migration->dropField('glpi_profiles', 'ocsng'); $migration->dropField('glpi_profiles', 'sync_ocsng'); $migration->dropField('glpi_profiles', 'view_ocsng'); $migration->dropField('glpi_profiles', 'clean_ocsng'); $migration->changeField('glpi_profiles', 'rule_ocs', 'rule_import', 'char'); $migration->changeField('glpi_rulecacheprinters', 'ignore_ocs_import', 'ignore_import', 'char'); $migration->changeField('glpi_rulecachesoftwares', 'ignore_ocs_import', 'ignore_import', 'char'); $migration->dropField('glpi_configs', 'use_ocs_mode'); // clean crontask $migration->copyTable('glpi_crontasks', 'ocs_glpi_crontasks'); $query = "DELETE\n FROM `glpi_crontasks`\n WHERE `itemtype` = 'OcsServer'"; $DB->queryOrDie($query, "0.84 delete OcsServer in crontasks"); // clean displaypreferences $migration->copyTable('glpi_displaypreferences', 'ocs_glpi_displaypreferences'); $query = "DELETE\n FROM `glpi_displaypreferences`\n WHERE `itemtype` = 'OcsServer'"; $DB->queryOrDie($query, "0.84 delete OcsServer in displaypreferences"); // Give history entries to plugin $query = "UPDATE `glpi_logs`\n SET `linked_action` = `linked_action`+1000,\n `itemtype_link` = 'PluginOcsinventoryngOcslink'\n WHERE `linked_action` IN (8,9,10,11)"; $DB->queryOrDie($query, "0.84 update OCS links in history"); $migration->displayWarning("You can delete ocs_* tables if you use OCS mode ONLY AFTER ocsinventoryng plugin installation.", true); $migration->displayWarning("You can delete ocs_* tables if you do not use OCS synchronisation.", true); $migration->addField('glpi_authldaps', 'pagesize', 'integer'); $migration->addField('glpi_authldaps', 'ldap_maxlimit', 'integer'); $migration->addField('glpi_authldaps', 'can_support_pagesize', 'bool'); // Add delete ticket notification if (countElementsInTable("glpi_notifications", "`itemtype` = 'Ticket' AND `event` = 'delete'") == 0) { // Get first template for tickets : $notid = 0; $query = "SELECT MIN(id) AS id\n FROM `glpi_notificationtemplates`\n WHERE `itemtype` = 'Ticket'"; if ($result = $DB->query($query)) { if ($DB->numrows($result) == 1) { $notid = $DB->result($result, 0, 0); } } if ($notid > 0) { $notifications = array('delete' => array(Notification::GLOBAL_ADMINISTRATOR)); $notif_names = array('delete' => 'Delete Ticket'); foreach ($notifications as $type => $targets) { $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 ('" . $notif_names[$type] . "', 0, 'Ticket', '{$type}', 'mail',\n {$notid}, '', 1, 1, NOW())"; $DB->queryOrDie($query, "0.83 add problem {$type} notification"); $notifid = $DB->insert_id(); foreach ($targets as $target) { $query = "INSERT INTO `glpi_notificationtargets`\n (`id`, `notifications_id`, `type`, `items_id`)\n VALUES (NULL, {$notifid}, " . Notification::USER_TYPE . ", {$target});"; $DB->queryOrDie($query, "0.83 add problem {$type} notification target"); } } } } // Add multiple suppliers for itil objects if (!TableExists('glpi_problems_suppliers')) { $query = "CREATE TABLE `glpi_problems_suppliers` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `problems_id` int(11) NOT NULL DEFAULT '0',\n `suppliers_id` int(11) NOT NULL DEFAULT '0',\n `type` int(11) NOT NULL DEFAULT '1',\n PRIMARY KEY (`id`),\n UNIQUE KEY `unicity` (`problems_id`,`type`,`suppliers_id`),\n KEY `group` (`suppliers_id`,`type`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.84 add table glpi_problems_suppliers"); $migration->migrationOneTable('glpi_problems_suppliers'); foreach ($DB->request('glpi_problems', "`suppliers_id_assign` > 0") as $data) { $query = "INSERT INTO `glpi_problems_suppliers`\n (`suppliers_id`, `type`, `problems_id`)\n VALUES ('" . $data['suppliers_id_assign'] . "', '" . CommonITILActor::ASSIGN . "',\n '" . $data['id'] . "')"; $DB->query($query); } $migration->dropField('glpi_problems', 'suppliers_id_assign'); } if (!TableExists('glpi_suppliers_tickets')) { $query = "CREATE TABLE `glpi_suppliers_tickets` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `tickets_id` int(11) NOT NULL DEFAULT '0',\n `suppliers_id` int(11) NOT NULL DEFAULT '0',\n `type` int(11) NOT NULL DEFAULT '1',\n PRIMARY KEY (`id`),\n UNIQUE KEY `unicity` (`tickets_id`,`type`,`suppliers_id`),\n KEY `group` (`suppliers_id`,`type`)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->queryOrDie($query, "0.84 add table glpi_suppliers_tickets"); $migration->migrationOneTable('glpi_suppliers_tickets'); foreach ($DB->request('glpi_tickets', "`suppliers_id_assign` > 0") as $data) { $query = "INSERT INTO `glpi_suppliers_tickets`\n (`suppliers_id`, `type`, `tickets_id`)\n VALUES ('" . $data['suppliers_id_assign'] . "', '" . CommonITILActor::ASSIGN . "',\n '" . $data['id'] . "')"; $DB->query($query); } $migration->dropField('glpi_tickets', 'suppliers_id_assign'); } $migration->addField('glpi_tickets', 'locations_id', 'integer'); $migration->addKey('glpi_tickets', 'locations_id'); $migration->displayMessage(sprintf(__('Data migration - %s'), 'RuleTicket')); $changes = array(); $changes['RuleTicket'] = array('suppliers_id_assign' => '_suppliers_id_assign'); $changes['RuleDictionnarySoftware'] = array('_ignore_ocs_import' => '_ignore_import'); $changes['RuleImportEntity'] = array('_ignore_ocs_import' => '_ignore_import'); $changes['RuleDictionnaryPrinter'] = array('_ignore_ocs_import' => '_ignore_import'); $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.84 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.84 update datas for rules criterias"); } } } } // change ruleaction for manufacturer (id to name) $query = "SELECT `glpi_ruleactions` .`id` AS id,\n `sub_type`,\n `glpi_manufacturers`.`name` AS newvalue\n FROM `glpi_rules`\n INNER JOIN `glpi_ruleactions`\n ON (`glpi_rules`.`id` = `glpi_ruleactions`.`rules_id`\n AND `field` = 'Manufacturer')\n LEFT JOIN `glpi_manufacturers`\n ON `glpi_manufacturers`.`id` = `glpi_ruleactions`.`value`\n WHERE `sub_type` = 'RuleDictionnarySoftware'"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { while ($data = $DB->fetch_assoc($result)) { // Update manufacturer $query = "UPDATE `glpi_ruleactions`\n SET `value` = '" . $data['newvalue'] . "'\n WHERE `id` = " . $data['id']; $DB->queryOrDie($query, "0.84 update value of manufacturer for rules actions"); } } } // Move ticketrecurrent values to correct ones $migration->changeField('glpi_ticketrecurrents', 'periodicity', 'periodicity', 'string'); $migration->addField('glpi_ticketrecurrents', 'calendars_id', 'integer'); $migration->addField('glpi_ticketrecurrents', 'end_date', 'datetime'); $migration->migrationOneTable('glpi_ticketrecurrents'); foreach ($DB->request('glpi_ticketrecurrents', "`periodicity` >= " . MONTH_TIMESTAMP) as $data) { $periodicity = $data['periodicity']; if (is_numeric($periodicity)) { if ($periodicity >= 365 * DAY_TIMESTAMP) { $periodicity = round($periodicity / (365 * DAY_TIMESTAMP)) . 'YEAR'; } else { $periodicity = round($periodicity / MONTH_TIMESTAMP) . 'MONTH'; } $query = "UPDATE `glpi_ticketrecurrents`\n SET `periodicity` = '{$periodicity}'\n WHERE `id` = '" . $data['id'] . "'"; $DB->query($query); } } $query = "UPDATE `glpi_notifications`\n SET `itemtype` = 'CartridgeItem'\n WHERE `itemtype` = 'Cartridge'"; $DB->queryOrDie($query, "0.83 update glpi_notifications for Cartridge"); $query = "UPDATE `glpi_notificationtemplates`\n SET `itemtype` = 'CartridgeItem'\n WHERE `itemtype` = 'Cartridge'"; $DB->queryOrDie($query, "0.83 update glpi_notificationtemplates for Cartridge"); $query = "UPDATE `glpi_notifications`\n SET `itemtype` = 'ConsumableItem'\n WHERE `itemtype` = 'Consumable'"; $DB->queryOrDie($query, "0.83 update glpi_notifications for Consumable"); $query = "UPDATE `glpi_notificationtemplates`\n SET `itemtype` = 'ConsumableItem'\n WHERE `itemtype` = 'Consumable'"; $DB->queryOrDie($query, "0.83 update glpi_notificationtemplates for Consumable"); $migration->createRule(array('sub_type' => 'RuleTicket', 'entities_id' => 0, 'is_recursive' => 1, 'is_active' => 0, 'match' => 'AND', 'name' => 'Ticket location from item'), array(array('criteria' => 'locations_id', 'condition' => Rule::PATTERN_DOES_NOT_EXISTS, 'pattern' => 1), array('criteria' => 'items_locations', 'condition' => Rule::PATTERN_EXISTS, 'pattern' => 1)), array(array('field' => 'locations_id', 'action_type' => 'fromitem', 'value' => 1))); $migration->createRule(array('sub_type' => 'RuleTicket', 'entities_id' => 0, 'is_recursive' => 1, 'is_active' => 0, 'match' => 'AND', 'name' => 'Ticket location from user'), array(array('criteria' => 'locations_id', 'condition' => Rule::PATTERN_DOES_NOT_EXISTS, 'pattern' => 1), array('criteria' => 'users_locations', 'condition' => Rule::PATTERN_EXISTS, 'pattern' => 1)), array(array('field' => 'locations_id', 'action_type' => 'fromuser', 'value' => 1))); // Change begin_date id for budget $query = "UPDATE `glpi_displaypreferences`\n SET `num` = '5'\n WHERE `itemtype` = 'Budget'\n AND `num` = '2'"; $DB->query($query); migrateComputerDevice('DeviceProcessor', 'frequency', 'integer', array('serial' => 'string')); migrateComputerDevice('DeviceMemory', 'size', 'integer', array('serial' => 'string')); migrateComputerDevice('DeviceHardDrive', 'capacity', 'integer', array('serial' => 'string')); migrateComputerDevice('DeviceGraphicCard', 'memory', 'integer'); migrateComputerDevice('DeviceNetworkCard', 'mac', 'string'); migrateComputerDevice('DeviceSoundCard'); migrateComputerDevice('DeviceMotherBoard'); migrateComputerDevice('DeviceDrive'); migrateComputerDevice('DeviceControl'); migrateComputerDevice('DevicePci'); migrateComputerDevice('DeviceCase'); migrateComputerDevice('DevicePowerSupply'); $migration->migrationOneTable('glpi_computers_softwareversions'); //Rename fields in glpi_computers_softwareversions with inaproprious signification $migration->changeField('glpi_computers_softwareversions', 'is_deleted', 'is_deleted_computer', 'bool'); $migration->changeField('glpi_computers_softwareversions', 'is_template', 'is_template_computer', 'bool'); $migration->migrationOneTable('glpi_computers_softwareversions'); $types = array('glpi_computers_items', 'glpi_computervirtualmachines', 'glpi_computers_softwareversions', 'glpi_computerdisks', 'glpi_networkports', 'glpi_computers_softwarelicenses', 'glpi_networknames', 'glpi_ipaddresses'); foreach (Item_Devices::getDeviceTypes() as $id => $type) { $types[] = getTableForItemType($type); } //Add is_deleted for relations foreach ($types as $table) { if ($migration->addField($table, 'is_deleted', 'bool', array('value' => 0))) { $migration->migrationOneTable($table); $migration->addKey($table, 'is_deleted'); } } ///For computers, rename is is_ocs_import to is_dynamic $migration->changeField('glpi_computers', 'is_ocs_import', 'is_dynamic', 'bool'); $migration->migrationOneTable('glpi_computers'); $migration->dropKey("glpi_computers", 'is_ocs_import'); $migration->addKey("glpi_computers", 'is_dynamic'); //Add field is_dynamic $types = array_merge($types, array('glpi_printers', 'glpi_phones', 'glpi_peripherals', 'glpi_networkequipments', 'glpi_networkports', 'glpi_monitors', 'glpi_networknames', 'glpi_ipaddresses')); foreach ($types as $table) { if ($migration->addField($table, 'is_dynamic', 'bool')) { $migration->migrationOneTable($table); $migration->addKey($table, 'is_dynamic'); } } $ADDTODISPLAYPREF['ReservationItem'] = array(5); // split validation rights in both $migration->changeField('glpi_profiles', 'validate_ticket', 'validate_request', 'char'); $migration->changeField('glpi_profiles', 'create_validation', 'create_request_validation', 'char'); $migration->migrationOneTable('glpi_profiles'); $migration->addField('glpi_profiles', 'validate_incident', 'char', array('update' => 'validate_request')); $migration->addField('glpi_profiles', 'create_incident_validation', 'char', array('update' => 'create_request_validation')); // add rights to delete all validation $migration->addField('glpi_profiles', 'delete_validations', 'char', array('update' => 'delete_ticket')); // add rights to manage public rssfeed $migration->addField('glpi_profiles', 'rssfeed_public', 'char', array('update' => 'reminder_public', 'after' => 'reminder_public')); // add ticket templates $migration->addField('glpi_profiles', 'tickettemplates_id', 'integer'); // Drop not needed fields $migration->dropField('glpi_tickettemplatepredefinedfields', 'entities_id'); $migration->dropField('glpi_tickettemplatepredefinedfields', 'is_recursive'); $migration->dropField('glpi_tickettemplatemandatoryfields', 'entities_id'); $migration->dropField('glpi_tickettemplatemandatoryfields', 'is_recursive'); $migration->dropField('glpi_tickettemplatehiddenfields', 'entities_id'); $migration->dropField('glpi_tickettemplatehiddenfields', 'is_recursive'); // Clean unlinked calendar segments and holidays $query = "DELETE\n FROM `glpi_calendars_holidays`\n WHERE `glpi_calendars_holidays`.`calendars_id`\n NOT IN (SELECT `glpi_calendars`.`id`\n FROM `glpi_calendars`)"; $DB->queryOrDie($query, "0.84 clean glpi_calendars_holidays"); $query = "DELETE\n FROM `glpi_calendarsegments`\n WHERE `glpi_calendarsegments`.`calendars_id`\n NOT IN (SELECT `glpi_calendars`.`id`\n FROM `glpi_calendars`)"; $DB->queryOrDie($query, "0.84 clean glpi_calendarsegments"); // Add keys for serial, otherserial and uuid $newindexes = array('serial' => array('glpi_computers', 'glpi_items_deviceharddrives', 'glpi_items_devicememories', 'glpi_items_deviceprocessors', 'glpi_monitors', 'glpi_networkequipments', 'glpi_peripherals', 'glpi_phones', 'glpi_printers'), 'otherserial' => array('glpi_computers', 'glpi_monitors', 'glpi_networkequipments', 'glpi_peripherals', 'glpi_phones', 'glpi_printers'), 'uuid' => array('glpi_computers', 'glpi_computervirtualmachines')); foreach ($newindexes as $field => $tables) { foreach ($tables as $table) { $migration->addKey($table, $field); } } // Clean unlinked ticket_problem $query = "DELETE\n FROM `glpi_problems_tickets`\n WHERE `glpi_problems_tickets`.`tickets_id`\n NOT IN (SELECT `glpi_tickets`.`id`\n FROM `glpi_tickets`)"; $DB->queryOrDie($query, "0.84 clean glpi_problems_tickets"); $query = "DELETE\n FROM `glpi_problems_tickets`\n WHERE `glpi_problems_tickets`.`problems_id`\n NOT IN (SELECT `glpi_problems`.`id`\n FROM `glpi_problems`)"; $DB->queryOrDie($query, "0.84 clean glpi_problems_tickets"); // Clean unlinked softwarelicense_computer $query = "DELETE\n FROM `glpi_computers_softwarelicenses`\n WHERE `glpi_computers_softwarelicenses`.`softwarelicenses_id`\n NOT IN (SELECT `glpi_softwarelicenses`.`id`\n FROM `glpi_softwarelicenses`)"; $DB->queryOrDie($query, "0.84 clean glpi_computers_softwarelicenses"); $query = "DELETE\n FROM `glpi_computers_softwarelicenses`\n WHERE `glpi_computers_softwarelicenses`.`computers_id`\n NOT IN (SELECT `glpi_computers`.`id`\n FROM `glpi_computers`)"; $DB->queryOrDie($query, "0.84 clean glpi_computers_softwarelicenses"); // Clean unlinked items_problems $query = "DELETE\n FROM `glpi_items_problems`\n WHERE `glpi_items_problems`.`problems_id`\n NOT IN (SELECT `glpi_problems`.`id`\n FROM `glpi_problems`)"; $DB->queryOrDie($query, "0.84 clean glpi_items_problems"); $toclean = array('Computer', 'Monitor', 'NetworkEquipment', 'Peripheral', 'Phone', 'Printer', 'Software'); foreach ($toclean as $type) { $query = "DELETE\n FROM `glpi_items_problems`\n WHERE `glpi_items_problems`.`itemtype` = '{$type}'\n AND `glpi_items_problems`.`items_id`\n NOT IN (SELECT `" . getTableForItemType($type) . "`.`id`\n FROM `" . getTableForItemType($type) . "`)"; $DB->queryOrDie($query, "0.84 clean glpi_items_problems"); } // ************ Keep it at the end ************** //TRANS: %s is the table or item to migrate $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_displaypreferences')); foreach ($ADDTODISPLAYPREF as $type => $tab) { $query = "SELECT DISTINCT `users_id`\n FROM `glpi_displaypreferences`\n WHERE `itemtype` = '{$type}'"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { while ($data = $DB->fetch_assoc($result)) { $query = "SELECT MAX(`rank`)\n FROM `glpi_displaypreferences`\n WHERE `users_id` = '" . $data['users_id'] . "'\n AND `itemtype` = '{$type}'"; $result = $DB->query($query); $rank = $DB->result($result, 0, 0); $rank++; foreach ($tab as $newval) { $query = "SELECT *\n FROM `glpi_displaypreferences`\n WHERE `users_id` = '" . $data['users_id'] . "'\n AND `num` = '{$newval}'\n AND `itemtype` = '{$type}'"; if ($result2 = $DB->query($query)) { if ($DB->numrows($result2) == 0) { $query = "INSERT INTO `glpi_displaypreferences`\n (`itemtype` ,`num` ,`rank` ,`users_id`)\n VALUES ('{$type}', '{$newval}', '" . $rank++ . "',\n '" . $data['users_id'] . "')"; $DB->query($query); } } } } } else { // Add for default user $rank = 1; foreach ($tab as $newval) { $query = "INSERT INTO `glpi_displaypreferences`\n (`itemtype` ,`num` ,`rank` ,`users_id`)\n VALUES ('{$type}', '{$newval}', '" . $rank++ . "', '0')"; $DB->query($query); } } } } // must always be at the end $migration->executeMigration(); return $updateresult; }
function showContacts($itemtype, $items_id) { global $DB, $LANG, $CFG_GLPI; $this->addContact($itemtype, $items_id); $group = new Group(); $user = new User(); $rand = mt_rand(); echo "<form method='post' name='contact_item_form{$rand}' id='contact_item_form{$rand}' action=\"" . $CFG_GLPI["root_doc"] . "/plugins/monitoring/front/contact_item.form.php\">"; echo "<table class='tab_cadre_fixe'>"; echo "<tr>"; echo "<th>"; echo $LANG['plugin_monitoring']['contact'][20]; echo "</th>"; echo "</tr>"; echo "</table>"; echo "<table class='tab_cadre_fixe'>"; echo "<tr>"; echo "<th width='10'> </th>"; echo "<th>" . $LANG['common'][35] . " - " . $LANG['common'][16] . "</th>"; echo "<th colspan='3'></th>"; echo "</tr>"; $used = array(); // Display groups first $query = "SELECT * FROM `" . $this->getTable() . "`\n WHERE `items_id`='" . $items_id . "'\n AND `itemtype`='" . $itemtype . "'\n AND `groups_id` > 0"; $result = $DB->query($query); while ($data = $DB->fetch_array($result)) { $group->getFromDB($data['groups_id']); echo "<tr>"; echo "<td>"; echo "<input type='checkbox' name='item[" . $data["id"] . "]' value='1'>"; echo "</td>"; echo "<td class='center'>"; echo $group->getLink(1); echo "</td>"; echo "<td colspan='3'>"; echo "</td>"; echo "</tr>"; } echo "<tr>"; echo "<th width='10'> </th>"; echo "<th>" . $LANG['common'][34] . " - " . $LANG['common'][16] . "</th>"; echo "<th>" . $LANG['entity'][0] . "</th>"; echo "<th>" . $LANG['setup'][14] . "</th>"; echo "<th>" . $LANG['help'][35] . "</th>"; echo "</tr>"; $entity = new Entity(); $used = array(); // Display Users $query = "SELECT * FROM `" . $this->getTable() . "`\n WHERE `items_id`='" . $items_id . "'\n AND `itemtype`='" . $itemtype . "'\n AND `users_id` > 0"; $result = $DB->query($query); while ($data = $DB->fetch_array($result)) { $user->getFromDB($data['users_id']); echo "<tr>"; echo "<td>"; echo "<input type='checkbox' name='item[" . $data["id"] . "]' value='1'>"; echo "</td>"; echo "<td class='center'>"; echo $user->getLink(1); echo "</td>"; $entity->getFromDB($data['entities_id']); echo "<td class='center'>"; echo $entity->getName() . " <strong>(R)</strong>"; echo "</td>"; echo "<td class='center'>"; echo $user->fields['email']; echo "</td>"; echo "<td class='center'>"; echo $user->fields['phone']; echo "</td>"; echo "</tr>"; } openArrowMassive("contact_item_form{$rand}", true); closeArrowMassive('deleteitem', $LANG['buttons'][6]); echo "</table>"; }
/** * @param $pid * @param $data * @param $server * @param $prof * @param $verb * @param $mail **/ function syncEntity($pid, $data, $server, $prof, $verb, $mail) { global $DB, $LANG, $CFG_GLPI; // Re-establish DB connexion - mandatory in each forked process if (!DBConnection::switchToMaster()) { echo " {$pid}: lost DB connection\n"; return 0; } // Server from entity (if not given from option) if ($data['authldaps_id'] > 0) { $server = $data['authldaps_id']; } $entity = new Entity(); if ($entity->getFromDB($id = $data['id'])) { $tps = microtime(true); if ($verb) { echo " {$pid}: Synchonizing entity '" . $entity->getField('completename') . "' ({$id}, mail={$mail})\n"; } $sql = "SELECT DISTINCT glpi_users.*\n FROM glpi_users\n INNER JOIN glpi_profiles_users\n ON (glpi_profiles_users.users_id = glpi_users.id\n AND glpi_profiles_users.entities_id = {$id}"; if ($prof > 0) { $sql .= " AND glpi_profiles_users.profiles_id = {$prof}"; } $sql .= ")\n WHERE glpi_users.authtype = " . Auth::LDAP; if ($server > 0) { $sql .= " AND glpi_users.auths_id = {$server}"; } $users = array(); $results = array(AuthLDAP::USER_IMPORTED => 0, AuthLDAP::USER_SYNCHRONIZED => 0, AuthLDAP::USER_DELETED_LDAP => 0); $req = $DB->request($sql); $i = 0; $nb = $req->numrows(); foreach ($req as $row) { $i++; $result = AuthLdap::ldapImportUserByServerId(array('method' => AuthLDAP::IDENTIFIER_LOGIN, 'value' => $row['name']), AuthLDAP::ACTION_SYNCHRONIZE, $row['auths_id']); if ($result) { $results[$result['action']] += 1; $users[$row['id']] = $row['name']; if ($result['action'] == AuthLDAP::USER_SYNCHRONIZED) { if ($verb) { echo " {$pid}: User '" . $row['name'] . "' synchronized ({$i}/{$nb})\n"; } } else { if ($verb) { echo " {$pid}: User '" . $row['name'] . "' deleted\n"; } } } else { if ($verb) { echo " {$pid}: Problem with LDAP for user '" . $row['name'] . "'\n"; } } } $tps = microtime(true) - $tps; printf(" %d: Entity '%s' - Synchronized: %d, Deleted from LDAP: %d, Time: %.2f\"\n", $pid, $entity->getField('completename'), $results[AuthLDAP::USER_SYNCHRONIZED], $results[AuthLDAP::USER_DELETED_LDAP], $tps); if ($mail) { $report = ''; $user = new User(); foreach ($users as $id => $name) { if ($user->getFromDB($id)) { $logs = Log::getHistoryData($user, 0, $_SESSION['glpilist_limit'], "`date_mod`='" . $_SESSION['glpi_currenttime'] . "'"); if (count($logs)) { $report .= "\n{$name} (" . $user->getName() . ")\n"; foreach ($logs as $log) { $report .= "\t"; if ($log['field']) { $report .= $log['field'] . ": "; } $report .= Html::clean($log['change']) . "\n"; } } } else { $report .= "\n" . $name . "\n\t deleted\n"; } } if ($report) { $report = "Synchronization of already imported users\n " . "Entité: " . $entity->getField('completename') . "\n " . "Date: " . Html::convDateTime($_SESSION['glpi_currenttime']) . "\n " . $report; $entdata = new Entity(); $mmail = new NotificationMail(); $mmail->AddCustomHeader("Auto-Submitted: auto-generated"); $mmail->From = $CFG_GLPI["admin_email"]; $mmail->FromName = "GLPI"; $mmail->Subject = "[GLPI] LDAP directory link"; $mmail->Body = $report . "\n--\n" . $CFG_GLPI["mailing_signature"]; if ($mail & 1 && $entdata->getFromDB($entity->getField('id')) && $entdata->fields['admin_email']) { $mmail->AddAddress($entdata->fields['admin_email']); } else { if ($mail & 1 && $verb) { echo " {$pid}: No address found for email entity\n"; } $mail = $mail & 2; } if ($mail & 2 && $CFG_GLPI['admin_email']) { $mmail->AddAddress($CFG_GLPI['admin_email']); } else { if ($mail & 2 && $verb) { echo " {$pid}: No address found for email admin\n"; } $mail = $mail & 1; } if ($mail) { if ($mmail->Send() && $verb) { echo " {$pid}: Report sent by email\n"; } } else { echo " {$pid}: Cannot send report (" . $entity->getField('completename') . ") " . "invalid address\n"; } } } return $results[AuthLDAP::USER_DELETED_LDAP] + $results[AuthLDAP::USER_SYNCHRONIZED]; } return 0; }
/** * @see NotificationTarget::getDatasForTemplate() **/ function getDatasForTemplate($event, $options = array()) { global $CFG_GLPI, $DB; //----------- Reservation infos -------------- // $events = $this->getAllEvents(); $item = $this->obj; $this->datas['##projecttask.action##'] = $events[$event]; $this->datas['##projecttask.url##'] = $this->formatURL($options['additionnaloption']['usertype'], "ProjectTask_" . $item->getField("id")); $this->datas["##projecttask.name##"] = $item->getField('name'); $this->datas["##projecttask.project##"] = Dropdown::getDropdownName('glpi_projects', $item->getField('projects_id')); $this->datas["##projecttask.projecturl##"] = $this->formatURL($options['additionnaloption']['usertype'], "Project_" . $item->getField("projects_id")); $this->datas["##projecttask.description##"] = $item->getField('content'); $this->datas["##projecttask.comments##"] = $item->getField('comment'); $this->datas["##projecttask.creationdate##"] = Html::convDateTime($item->getField('date')); $this->datas["##projecttask.lastupdatedate##"] = Html::convDateTime($item->getField('date_mod')); $this->datas["##projecttask.percent##"] = Dropdown::getValueWithUnit($item->getField('percent_done'), "%"); $this->datas["##projecttask.planstartdate##"] = Html::convDateTime($item->getField('plan_start_date')); $this->datas["##projecttask.planenddate##"] = Html::convDateTime($item->getField('plan_end_date')); $this->datas["##projecttask.realstartdate##"] = Html::convDateTime($item->getField('real_start_date')); $this->datas["##projecttask.realenddate##"] = Html::convDateTime($item->getField('real_end_date')); $this->datas["##projecttask.plannedduration##"] = Html::timestampToString($item->getField('planned_duration'), false); $this->datas["##projecttask.effectiveduration##"] = Html::timestampToString($item->getField('effective_duration'), false); $ticket_duration = ProjectTask_Ticket::getTicketsTotalActionTime($item->getID()); $this->datas["##projecttask.ticketsduration##"] = Html::timestampToString($ticket_duration, false); $this->datas["##projecttask.totalduration##"] = Html::timestampToString($ticket_duration + $item->getField('effective_duration'), false); $entity = new Entity(); $this->datas["##projecttask.entity##"] = ''; $this->datas["##projecttask.shortentity##"] = ''; if ($entity->getFromDB($this->getEntity())) { $this->datas["##projecttask.entity##"] = $entity->getField('completename'); $this->datas["##projecttask.shortentity##"] = $entity->getField('name'); } $this->datas["##projecttask.father##"] = ''; if ($item->getField('projecttasks_id')) { $this->datas["##projecttask.father##"] = Dropdown::getDropdownName('glpi_projecttasks', $item->getField('projecttasks_id')); } $this->datas["##projecttask.state##"] = ''; if ($item->getField('projectstates_id')) { $this->datas["##projecttask.state##"] = Dropdown::getDropdownName('glpi_projectstates', $item->getField('projectstates_id')); } $this->datas["##projecttask.type##"] = ''; if ($item->getField('projecttasktypes_id')) { $this->datas["##projecttask.type##"] = Dropdown::getDropdownName('glpi_projecttasktypes', $item->getField('projecttasktypes_id')); } $this->datas["##projecttask.createbyuser##"] = ''; if ($item->getField('users_id')) { $user_tmp = new User(); $user_tmp->getFromDB($item->getField('users_id')); $this->datas["##projecttask.createbyuser##"] = $user_tmp->getName(); } // Team infos $restrict = "`projecttasks_id` = '" . $item->getField('id') . "'"; $items = getAllDatasFromTable('glpi_projecttaskteams', $restrict); $this->datas['teammembers'] = array(); if (count($items)) { foreach ($items as $data) { if ($item2 = getItemForItemtype($data['itemtype'])) { if ($item2->getFromDB($data['items_id'])) { $tmp = array(); $tmp['##teammember.itemtype##'] = $item2->getTypeName(); $tmp['##teammember.name##'] = $item2->getName(); $this->datas['teammembers'][] = $tmp; } } } } $this->datas['##projecttask.numberofteammembers##'] = count($this->datas['teammembers']); // Task infos $restrict = "`projecttasks_id`='" . $item->getField('id') . "'"; $restrict .= " ORDER BY `date` DESC, `id` ASC"; $tasks = getAllDatasFromTable('glpi_projecttasks', $restrict); $this->datas['tasks'] = array(); foreach ($tasks as $task) { $tmp = array(); $tmp['##task.creationdate##'] = Html::convDateTime($task['date']); $tmp['##task.lastupdatedate##'] = Html::convDateTime($task['date_mod']); $tmp['##task.name##'] = $task['name']; $tmp['##task.description##'] = $task['content']; $tmp['##task.comments##'] = $task['comment']; $tmp['##task.state##'] = Dropdown::getDropdownName('glpi_projectstates', $task['projectstates_id']); $tmp['##task.type##'] = Dropdown::getDropdownName('glpi_projecttasktypes', $task['projecttasktypes_id']); $tmp['##task.percent##'] = Dropdown::getValueWithUnit($task['percent_done'], "%"); $this->datas["##task.planstartdate##"] = ''; $this->datas["##task.planenddate##"] = ''; $this->datas["##task.realstartdate##"] = ''; $this->datas["##task.realenddate##"] = ''; if (!is_null($task['plan_start_date'])) { $tmp['##task.planstartdate##'] = Html::convDateTime($task['plan_start_date']); } if (!is_null($task['plan_end_date'])) { $tmp['##task.planenddate##'] = Html::convDateTime($task['plan_end_date']); } if (!is_null($task['real_start_date'])) { $tmp['##task.realstartdate##'] = Html::convDateTime($task['real_start_date']); } if (!is_null($task['real_end_date'])) { $tmp['##task.realenddate##'] = Html::convDateTime($task['real_end_date']); } $this->datas['tasks'][] = $tmp; } $this->datas["##projecttask.numberoftasks##"] = count($this->datas['tasks']); // History infos $this->datas['log'] = array(); // Use list_limit_max or load the full history ? foreach (Log::getHistoryData($item, 0, $CFG_GLPI['list_limit_max']) as $data) { $tmp = array(); $tmp["##projecttask.log.date##"] = $data['date_mod']; $tmp["##projecttask.log.user##"] = $data['user_name']; $tmp["##projecttask.log.field##"] = $data['field']; $tmp["##projecttask.log.content##"] = $data['change']; $this->datas['log'][] = $tmp; } $this->datas["##projecttask.numberoflogs##"] = count($this->datas['log']); // Tickets infos $restrict = "`projecttasks_id`='" . $item->getField('id') . "'"; $tickets = getAllDatasFromTable('glpi_projecttasks_tickets', $restrict); $this->datas['tickets'] = array(); if (count($tickets)) { $ticket = new Ticket(); foreach ($tickets as $data) { if ($ticket->getFromDB($data['tickets_id'])) { $tmp = array(); $tmp['##ticket.id##'] = $data['tickets_id']; $tmp['##ticket.date##'] = $ticket->getField('date'); $tmp['##ticket.title##'] = $ticket->getField('name'); $tmp['##ticket.url##'] = $this->formatURL($options['additionnaloption']['usertype'], "Ticket_" . $data['tickets_id']); $tmp['##ticket.content##'] = $ticket->getField('content'); $this->datas['tickets'][] = $tmp; } } } $this->datas['##projecttask.numberoftickets##'] = count($this->datas['tickets']); // Document $query = "SELECT `glpi_documents`.*\n FROM `glpi_documents`\n LEFT JOIN `glpi_documents_items`\n ON (`glpi_documents`.`id` = `glpi_documents_items`.`documents_id`)\n WHERE `glpi_documents_items`.`itemtype` = 'ProjectTask'\n AND `glpi_documents_items`.`items_id` = '" . $item->getField('id') . "'"; $this->datas["documents"] = array(); if ($result = $DB->query($query)) { while ($data = $DB->fetch_assoc($result)) { $tmp = array(); $tmp['##document.id##'] = $data['id']; $tmp['##document.name##'] = $data['name']; $tmp['##document.weblink##'] = $data['link']; $tmp['##document.url##'] = $this->formatURL($options['additionnaloption']['usertype'], "document_" . $data['id']); $downloadurl = "/front/document.send.php?docid=" . $data['id']; $tmp['##document.downloadurl##'] = $this->formatURL($options['additionnaloption']['usertype'], $downloadurl); $tmp['##document.heading##'] = Dropdown::getDropdownName('glpi_documentcategories', $data['documentcategories_id']); $tmp['##document.filename##'] = $data['filename']; $this->datas['documents'][] = $tmp; } } $this->datas["##projecttask.urldocument##"] = $this->formatURL($options['additionnaloption']['usertype'], "ProjectTask_" . $item->getField("id") . '_Document_Item$1'); $this->datas["##projecttask.numberofdocuments##"] = count($this->datas['documents']); // Items infos $restrict = "`projects_id` = '" . $item->getField('id') . "'"; $items = getAllDatasFromTable('glpi_items_projects', $restrict); $this->getTags(); foreach ($this->tag_descriptions[NotificationTarget::TAG_LANGUAGE] as $tag => $values) { if (!isset($this->datas[$tag])) { $this->datas[$tag] = $values['label']; } } }
function generateHostgroupsCfg($file=0, $tag='') { global $DB; PluginMonitoringToolbox::logIfExtradebug( 'pm-shinken', "Starting generateHostgroupsCfg ($tag) ...\n" ); $pmEntity = new PluginMonitoringEntity(); $a_hostgroups = array(); $i=0; $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); } $query = "SELECT `glpi_entities`.`id` AS entityId, `glpi_entities`.`name` AS entityName, `glpi_entities`.`level` AS entityLevel FROM `glpi_entities` $where"; $result = $DB->query($query); while ($data=$DB->fetch_array($result)) { /* Nagios configuration file : define hostgroup{ hostgroup_name hostgroup_name alias alias members hosts hostgroup_members hostgroups notes note_string notes_url url action_url url } */ // Hostgroup name $hostgroup_name = strtolower(preg_replace("/[^A-Za-z0-9\-_ ]/","",$data['entityName'])); $hostgroup_name = preg_replace("/[ ]/","_",$hostgroup_name); PluginMonitoringToolbox::logIfExtradebug( 'pm-shinken', " - add group $hostgroup_name ...\n" ); $a_hostgroups[$i]['hostgroup_name'] = $hostgroup_name; $a_hostgroups[$i]['alias'] = $data['entityName']; // Custom variable are ignored for hostgroups ... simple information for debug purpose ! $a_hostgroups[$i]['_GROUP_LEVEL'] = $data['entityLevel']; $a_sons_list = getSonsOf("glpi_entities", $data['entityId']); if (count($a_sons_list) > 1) { $a_hostgroups[$i]['hostgroup_members'] = ''; $first_member = true; foreach ($a_sons_list as $son_entity) { if ($son_entity == $data['entityId']) continue; if (! in_array ($son_entity, $a_entities_list)) continue; $pmEntity = new Entity(); $pmEntity->getFromDB($son_entity); // Only immediate sub level are considered as hostgroup members if ($data['entityLevel']+1 != $pmEntity->fields['level']) continue; $hostgroup_name = strtolower(preg_replace("/[^A-Za-z0-9\-_ ]/","",$pmEntity->getField('name'))); $hostgroup_name = preg_replace("/[ ]/","_",$hostgroup_name); $a_hostgroups[$i]['hostgroup_members'] .= (! $first_member) ? ", $hostgroup_name" : "$hostgroup_name"; if ($first_member) $first_member = false; } } $i++; } // Add an hostgroup for fake hosts if (self::$shinkenParameters['shinken']['fake_hosts']['build']) { $a_hostgroups[$i]['hostgroup_name'] = self::$shinkenParameters['shinken']['fake_hosts']['hostgroup_name']; $a_hostgroups[$i]['alias'] = self::$shinkenParameters['shinken']['fake_hosts']['hostgroup_alias']; } PluginMonitoringToolbox::logIfExtradebug( 'pm-shinken', "End generateHostgroupsCfg\n" ); if ($file == "1") { $config = "# Generated by plugin monitoring for GLPI\n# on ".date("Y-m-d H:i:s")."\n\n"; foreach ($a_hostgroups as $data) { $config .= $this->writeFile("hostgroup", $data); } return array('hostgroups.cfg', $config); } else { return $a_hostgroups; } }
static function methodInject($params, $protocol) { if (isset($params['help'])) { return array('uri' => 'string,mandatory', 'base64' => 'string,optional', 'additional' => 'array,optional', 'models_id' => 'integer, mandatory', 'entities_id' => 'integer,mandatory', 'mandatory' => 'array,optional', 'uri' => 'uri,mandatory', 'help' => 'bool,optional'); } $model = new PluginDatainjectionModel(); //----------------------------------------------------------------- //-------------------------- Check parameters --------------------- //----------------------------------------------------------------- if (!isset($_SESSION['glpiID'])) { return PluginWebservicesMethodCommon::Error($protocol, WEBSERVICES_ERROR_NOTAUTHENTICATED); } if (!isset($params['uri']) && !isset($params['base64'])) { return PluginWebservicesMethodCommon::Error($protocol, WEBSERVICES_ERROR_MISSINGPARAMETER, '', 'uri or base64'); } if (!isset($params['models_id'])) { return PluginWebservicesMethodCommon::Error($protocol, WEBSERVICES_ERROR_MISSINGPARAMETER, 'models_id'); } if (!$model->getFromDB($params['models_id'])) { return PluginWebservicesMethodCommon::Error($protocol, WEBSERVICES_ERROR_NOTFOUND, __('Model unknown', 'datainjection')); } if (!$model->can($params['models_id'], 'r')) { return PluginWebservicesMethodCommon::Error($protocol, WEBSERVICES_ERROR_NOTALLOWED, __('You cannot access this model', 'datainjection')); } if ($model->fields['step'] < PluginDatainjectionModel::READY_TO_USE_STEP) { return PluginWebservicesMethodCommon::Error($protocol, WEBSERVICES_ERROR_NOTALLOWED, __('You cannot access this model', 'datainjection')); } //Check entity if (!isset($params['entities_id'])) { return PluginWebservicesMethodCommon::Error($protocol, WEBSERVICES_ERROR_MISSINGPARAMETER, 'entities_id'); } $entities_id = $params['entities_id']; if ($entities_id > 0) { $entity = new Entity(); if (!$entity->getFromDB($entities_id)) { return PluginWebservicesMethodCommon::Error($protocol, WEBSERVICES_ERROR_NOTFOUND, __('Entity unknown', 'datainjection')); } if (!Session::haveAccessToEntity($entities_id)) { return PluginWebservicesMethodCommon::Error($protocol, WEBSERVICES_ERROR_NOTALLOWED, __('You cannot access this entity', 'datainjection')); } } //Mandatory fields $additional_infos = array(); if (isset($params['additional']) && is_array($params['additional'])) { $additional_infos = $params['additional']; } //Upload CSV file $document_name = basename($params['uri']); $filename = tempnam(PLUGIN_DATAINJECTION_UPLOAD_DIR, 'PWS'); $response = PluginWebservicesMethodCommon::uploadDocument($params, $protocol, $filename, $document_name); if (PluginWebservicesMethodCommon::isError($protocol, $response)) { return $response; } //Uploade successful : now perform import ! $options = array('file_encoding' => PluginDatainjectionBackend::ENCODING_AUTO, 'webservice' => true, 'original_filename' => $params['uri'], 'unique_filename' => $filename, 'mode' => PluginDatainjectionModel::PROCESS, 'delete_file' => false, 'protocol' => $protocol); //The Webservice protocol used $results = array(); $response = $model->processUploadedFile($options); if (!PluginWebservicesMethodCommon::isError($protocol, $response)) { $engine = new PluginDatainjectionEngine($model, $additional_infos, $params['entities_id']); //Remove first line if header is present $first = true; foreach ($model->injectionData->getDatas() as $id => $data) { if ($first && $model->getSpecificModel()->isHeaderPresent()) { $first = false; } else { $results[] = $engine->injectLine($data[0], $id); } } $model->cleanData(); return $results; } return $response; }