/** * Transfer cartridges of a printer * * @param $ID original ID of the printer * @param $newID new ID of the printer **/ function transferPrinterCartridges($ID, $newID) { global $DB; // Get cartrdiges linked $query = "SELECT *\n FROM `glpi_cartridges`\n WHERE `glpi_cartridges`.`printers_id` = '{$ID}'"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { $cart = new Cartridge(); $carttype = new CartridgeItem(); while ($data = $DB->fetch_array($result)) { $need_clean_process = false; // Foreach cartridges // if keep if ($this->options['keep_cartridgeitem']) { $newcartID = -1; $newcarttypeID = -1; // 1 - Search carttype destination ? // Already transfer carttype : if (isset($this->already_transfer['CartridgeItem'][$data['cartridgeitems_id']])) { $newcarttypeID = $this->already_transfer['CartridgeItem'][$data['cartridgeitems_id']]; } else { // Not already transfer cartype $query = "SELECT count(*) AS CPT\n FROM `glpi_cartridges`\n WHERE `glpi_cartridges`.`cartridgeitems_id`\n = '" . $data['cartridgeitems_id'] . "'\n AND `glpi_cartridges`.`printers_id` > '0'\n AND `glpi_cartridges`.`printers_id`\n NOT IN " . $this->item_search['Printer']; $result_search = $DB->query($query); // Is the carttype will be completly transfer ? if ($DB->result($result_search, 0, 'CPT') == 0) { // Yes : transfer $need_clean_process = false; $this->transferItem('CartridgeItem', $data['cartridgeitems_id'], $data['cartridgeitems_id']); $newcarttypeID = $data['cartridgeitems_id']; } else { // No : copy carttype $need_clean_process = true; $carttype->getFromDB($data['cartridgeitems_id']); // Is existing carttype in the destination entity ? $query = "SELECT *\n FROM `glpi_cartridgeitems`\n WHERE `entities_id` = '" . $this->to . "'\n AND `name` = '" . addslashes($carttype->fields['name']) . "'"; if ($result_search = $DB->query($query)) { if ($DB->numrows($result_search) > 0) { $newcarttypeID = $DB->result($result_search, 0, 'id'); } } // Not found -> transfer copy if ($newcarttypeID < 0) { // 1 - create new item unset($carttype->fields['id']); $input = $carttype->fields; $input['entities_id'] = $this->to; unset($carttype->fields); $newcarttypeID = $carttype->add($input); // 2 - transfer as copy $this->transferItem('CartridgeItem', $data['cartridgeitems_id'], $newcarttypeID); } // Founded -> use to link : nothing to do } } // Update cartridge if needed if ($newcarttypeID > 0 && $newcarttypeID != $data['cartridgeitems_id']) { $cart->update(array('id' => $data['id'], 'cartridgeitems_id' => $newcarttypeID)); } } else { // Do not keep // If same printer : delete cartridges if ($ID == $newID) { $del_query = "DELETE\n FROM `glpi_cartridges`\n WHERE `printers_id` = '{$ID}'"; $DB->query($del_query); } $need_clean_process = true; } // CLean process if ($need_clean_process && $this->options['clean_cartridgeitem']) { // Clean carttype $query2 = "SELECT COUNT(*) AS CPT\n FROM `glpi_cartridges`\n WHERE `cartridgeitems_id` = '" . $data['cartridgeitems_id'] . "'"; $result2 = $DB->query($query2); if ($DB->result($result2, 0, 'CPT') == 0) { if ($this->options['clean_cartridgeitem'] == 1) { // delete $carttype->delete(array('id' => $data['cartridgeitems_id'])); } if ($this->options['clean_cartridgeitem'] == 2) { // purge $carttype->delete(array('id' => $data['cartridgeitems_id']), 1); } } } } } } }
/** * @param $pdf PluginPdfSimplePDF object * @param $p Printer object * @param $old **/ static function pdfForPrinter(PluginPdfSimplePDF $pdf, Printer $p, $old = false) { global $DB, $CFG_GLPI; $instID = $p->getField('id'); if (!Session::haveRight("cartridge", "r")) { return false; } $dateout = "IS NULL "; if ($old) { $dateout = " IS NOT NULL "; } $query = "SELECT `glpi_cartridgeitems`.`id` AS tid,\n `glpi_cartridgeitems`.`ref`,\n `glpi_cartridgeitems`.`name`,\n `glpi_cartridges`.`id`,\n `glpi_cartridges`.`pages`,\n `glpi_cartridges`.`date_use`,\n `glpi_cartridges`.`date_out`,\n `glpi_cartridges`.`date_in`\n FROM `glpi_cartridges`, `glpi_cartridgeitems`\n WHERE `glpi_cartridges`.`date_out` " . $dateout . "\n AND `glpi_cartridges`.`printers_id` = '" . $instID . "'\n AND `glpi_cartridges`.`cartridgeitems_id` = `glpi_cartridgeitems`.`id`\n ORDER BY `glpi_cartridges`.`date_out` ASC,\n `glpi_cartridges`.`date_use` DESC,\n `glpi_cartridges`.`date_in`"; $result = $DB->query($query); $number = $DB->numrows($result); $i = 0; $pages = $p->fields['init_pages_counter']; $pdf->setColumnsSize(100); $pdf->displayTitle("<b>" . ($old ? __('Worn cartridges') : __('Used cartridges')) . "</b>"); if (!$number) { $pdf->displayLine(__('No item found')); } else { $pdf->setColumnsSize(25, 13, 12, 12, 12, 26); $pdf->displayTitle('<b><i>' . __('Cartridge type'), __('State'), __('Add date'), __('Use date'), __('End date'), __('Printer counter') . '</b></i>'); $stock_time = 0; $use_time = 0; $pages_printed = 0; $nb_pages_printed = 0; while ($data = $DB->fetch_array($result)) { $date_in = Html::convDate($data["date_in"]); $date_use = Html::convDate($data["date_use"]); $date_out = Html::convDate($data["date_out"]); $col1 = sprintf(__('%1$s - %2$s'), $data["name"], $data["ref"]); $col2 = Cartridge::getStatus($data["date_use"], $data["date_out"]); $col6 = ''; $tmp_dbeg = explode("-", $data["date_in"]); $tmp_dend = explode("-", $data["date_use"]); $stock_time_tmp = mktime(0, 0, 0, $tmp_dend[1], $tmp_dend[2], $tmp_dend[0]) - mktime(0, 0, 0, $tmp_dbeg[1], $tmp_dbeg[2], $tmp_dbeg[0]); $stock_time += $stock_time_tmp; if ($old) { $tmp_dbeg = explode("-", $data["date_use"]); $tmp_dend = explode("-", $data["date_out"]); $use_time_tmp = mktime(0, 0, 0, $tmp_dend[1], $tmp_dend[2], $tmp_dend[0]) - mktime(0, 0, 0, $tmp_dbeg[1], $tmp_dbeg[2], $tmp_dbeg[0]); $use_time += $use_time_tmp; $col6 = $data['pages']; if ($pages < $data['pages']) { $pages_printed += $data['pages'] - $pages; $nb_pages_printed++; $col6 = sprintf(__('%1$s (%2$s)'), $col6, __('%d printed pages'), $data['pages'] - $pages); $pages = $data['pages']; } } $pdf->displayLine($col1, $col2, $date_in, $date_use, $date_out, $col6); } // Each cartridge } if ($old) { if ($number > 0) { if ($nb_pages_printed == 0) { $nb_pages_printed = 1; } $nbstock = round($stock_time / $number / 60 / 60 / 24 / 30.5, 1); $nbuse = round($use_time / $number / 60 / 60 / 24 / 30.5, 1); $pdf->setColumnsSize(33, 33, 34); $pdf->displayTitle("<b><i>" . sprintf(__('%1$s: %2$s'), __('Average time in stock') . "</i></b>", _n('%d month', '%d months', $nbstock), $nbstock), "<b><i>" . sprintf(__('%1$s: %2$s'), __('Average time in use') . "</i></b>", _n('%d month', '%d months', $nbuse), $nbuse), "<b><i>" . sprintf(__('%1$s: %2$s'), __('Average number of printed pages') . "</i></b>", round($pages_printed / $nb_pages_printed))); } $pdf->displaySpace(); } }
/** * Generic Function to display Items * * @param $itemtype item type * @param $ID ID of the SEARCH_OPTION item * @param $data array containing data results * @param $num item num in the request * @param $meta is a meta item ? (default 0) * @param $addobjectparams array added parameters for union search * * @return string to print **/ static function giveItem($itemtype, $ID, array $data, $num, $meta = 0, array $addobjectparams = array()) { global $CFG_GLPI, $DB; $searchopt =& self::getOptions($itemtype); if (isset($CFG_GLPI["union_search_type"][$itemtype]) && $CFG_GLPI["union_search_type"][$itemtype] == $searchopt[$ID]["table"]) { if (isset($searchopt[$ID]['addobjectparams']) && $searchopt[$ID]['addobjectparams']) { return self::giveItem($data["TYPE"], $ID, $data, $num, $meta, $searchopt[$ID]['addobjectparams']); } return self::giveItem($data["TYPE"], $ID, $data, $num, $meta); } if (count($addobjectparams)) { $searchopt[$ID] = array_merge($searchopt[$ID], $addobjectparams); } // Plugin can override core definition for its type if ($plug = isPluginItemType($itemtype)) { $function = 'plugin_' . $plug['plugin'] . '_giveItem'; if (function_exists($function)) { $out = $function($itemtype, $ID, $data, $num); if (!empty($out)) { return $out; } } } $NAME = "ITEM_"; // if ($meta) { // $NAME = "META_"; // } if (isset($searchopt[$ID]["table"])) { $table = $searchopt[$ID]["table"]; $field = $searchopt[$ID]["field"]; $linkfield = $searchopt[$ID]["linkfield"]; /// TODO try to clean all specific cases using SpecificToDisplay switch ($table . '.' . $field) { case "glpi_users.name": // USER search case if ($itemtype != 'User' && isset($searchopt[$ID]["forcegroupby"]) && $searchopt[$ID]["forcegroupby"]) { $out = ""; $count_display = 0; $added = array(); $showuserlink = 0; if (Session::haveRight('user', READ)) { $showuserlink = 1; } for ($k = 0; $k < $data[$num]['count']; $k++) { if (isset($data[$num][$k]['name']) && $data[$num][$k]['name'] > 0 || isset($data[$num][$k][2]) && $data[$num][$k][2] != '') { if ($count_display) { $out .= self::LBBR; } if ($itemtype == 'Ticket') { if (isset($data[$num][$k]['name']) && $data[$num][$k]['name'] > 0) { $userdata = getUserName($data[$num][$k]['name'], 2); $tooltip = ""; if (Session::haveRight('user', READ)) { $tooltip = Html::showToolTip($userdata["comment"], array('link' => $userdata["link"], 'display' => false)); } $out .= sprintf(__('%1$s %2$s'), $userdata['name'], $tooltip); $count_display++; } } else { $out .= getUserName($data[$num][$k]['name'], $showuserlink); $count_display++; } // Manage alternative_email for tickets_users if ($itemtype == 'Ticket' && isset($data[$num][$k][2])) { $split = explode(self::LONGSEP, $data[$num][$k][2]); for ($l = 0; $l < count($split); $l++) { $split2 = explode(" ", $split[$l]); if (count($split2) == 2 && $split2[0] == 0 && !empty($split2[1])) { if ($count_display) { $out .= self::LBBR; } $count_display++; $out .= "<a href='mailto:" . $split2[1] . "'>" . $split2[1] . "</a>"; } } } } } return $out; } if ($itemtype != 'User') { $toadd = ''; if ($itemtype == 'Ticket' && $data[$num][0]['id'] > 0) { $userdata = getUserName($data[$num][0]['id'], 2); $toadd = Html::showToolTip($userdata["comment"], array('link' => $userdata["link"], 'display' => false)); } $usernameformat = formatUserName($data[$num][0]['id'], $data[$num][0]['name'], $data[$num][0]['realname'], $data[$num][0]['firstname'], 1); return sprintf(__('%1$s %2$s'), $usernameformat, $toadd); } break; case "glpi_profiles.name": if ($itemtype == 'User' && $ID == 20) { $out = ""; $count_display = 0; $added = array(); for ($k = 0; $k < $data[$num]['count']; $k++) { if (strlen(trim($data[$num][$k]['name'])) > 0) { $text = sprintf(__('%1$s - %2$s'), $data[$num][$k]['name'], Dropdown::getDropdownName('glpi_entities', $data[$num][$k]['entities_id'])); $comp = ''; if ($data[$num][$k]['is_recursive']) { $comp = __('R'); if ($data[$num][$k]['is_dynamic']) { $comp = sprintf(__('%1$s%2$s'), $comp, ", "); } } if ($data[$num][$k]['is_dynamic']) { $comp = sprintf(__('%1$s%2$s'), $comp, __('D')); } if (!empty($comp)) { $text = sprintf(__('%1$s %2$s'), $text, "(" . $comp . ")"); } if (!in_array($text, $added)) { if ($count_display) { $out .= self::LBBR; } $count_display++; $out .= $text; $added[] = $text; } } } return $out; } break; case "glpi_entities.completename": if ($itemtype == 'User') { $out = ""; $added = array(); $count_display = 0; for ($k = 0; $k < $data[$num]['count']; $k++) { if (strlen(trim($data[$num][$k]['name'])) > 0) { $text = sprintf(__('%1$s - %2$s'), $data[$num][$k]['name'], Dropdown::getDropdownName('glpi_profiles', $data[$num][$k]['profiles_id'])); $comp = ''; if ($data[$num][$k]['is_recursive']) { $comp = __('R'); if ($data[$num][$k]['is_dynamic']) { $comp = sprintf(__('%1$s%2$s'), $comp, ", "); } } if ($data[$num][$k]['is_dynamic']) { $comp = sprintf(__('%1$s%2$s'), $comp, __('D')); } if (!empty($comp)) { $text = sprintf(__('%1$s %2$s'), $text, "(" . $comp . ")"); } if (!in_array($text, $added)) { if ($count_display) { $out .= self::LBBR; } $count_display++; $out .= $text; $added[] = $text; } } } return $out; } break; case "glpi_documenttypes.icon": if (!empty($data[$num][0]['name'])) { return "<img class='middle' alt='' src='" . $CFG_GLPI["typedoc_icon_dir"] . "/" . $data[$num][0]['name'] . "'>"; } return " "; case "glpi_documents.filename": $doc = new Document(); if ($doc->getFromDB($data['id'])) { return $doc->getDownloadLink(); } return NOT_AVAILABLE; case "glpi_tickets_tickets.tickets_id_1": $out = ""; $displayed = array(); for ($k = 0; $k < $data[$num]['count']; $k++) { $linkid = $data[$num][$k]['tickets_id_2'] == $data['id'] ? $data[$num][$k]['name'] : $data[$num][$k]['tickets_id_2']; if ($linkid > 0 && !isset($displayed[$linkid])) { $text = "<a "; $text .= "href=\"" . $CFG_GLPI["root_doc"] . "/front/ticket.form.php?id={$linkid}\">"; $text .= Dropdown::getDropdownName('glpi_tickets', $linkid) . "</a>"; if (count($displayed)) { $out .= self::LBBR; } $displayed[$linkid] = $linkid; $out .= $text; } } return $out; case "glpi_problems.id": if ($searchopt[$ID]["datatype"] == 'count') { if ($data[$num][0]['name'] > 0 && Session::haveRight("problem", Problem::READALL)) { if ($itemtype == 'ITILCategory') { $options['criteria'][0]['field'] = 7; $options['criteria'][0]['searchtype'] = 'equals'; $options['criteria'][0]['value'] = $data['id']; $options['criteria'][0]['link'] = 'AND'; } else { $options['criteria'][0]['field'] = 12; $options['criteria'][0]['searchtype'] = 'equals'; $options['criteria'][0]['value'] = 'all'; $options['criteria'][0]['link'] = 'AND'; $options['metacriteria'][0]['itemtype'] = $itemtype; $options['metacriteria'][0]['field'] = self::getOptionNumber($itemtype, 'name'); $options['metacriteria'][0]['searchtype'] = 'equals'; $options['metacriteria'][0]['value'] = $data['id']; $options['metacriteria'][0]['link'] = 'AND'; } $options['reset'] = 'reset'; $out = "<a id='problem{$itemtype}" . $data['id'] . "' "; $out .= "href=\"" . $CFG_GLPI["root_doc"] . "/front/problem.php?" . Toolbox::append_params($options, '&') . "\">"; $out .= $data[$num][0]['name'] . "</a>"; return $out; } } break; case "glpi_tickets.id": if ($searchopt[$ID]["datatype"] == 'count') { if ($data[$num][0]['name'] > 0 && Session::haveRight("ticket", Ticket::READALL)) { if ($itemtype == 'User') { // Requester if ($ID == 60) { $options['criteria'][0]['field'] = 4; $options['criteria'][0]['searchtype'] = 'equals'; $options['criteria'][0]['value'] = $data['id']; $options['criteria'][0]['link'] = 'AND'; } // Writer if ($ID == 61) { $options['criteria'][0]['field'] = 22; $options['criteria'][0]['searchtype'] = 'equals'; $options['criteria'][0]['value'] = $data['id']; $options['criteria'][0]['link'] = 'AND'; } // Assign if ($ID == 64) { $options['criteria'][0]['field'] = 5; $options['criteria'][0]['searchtype'] = 'equals'; $options['criteria'][0]['value'] = $data['id']; $options['criteria'][0]['link'] = 'AND'; } } else { if ($itemtype == 'ITILCategory') { $options['criteria'][0]['field'] = 7; $options['criteria'][0]['searchtype'] = 'equals'; $options['criteria'][0]['value'] = $data['id']; $options['criteria'][0]['link'] = 'AND'; } else { $options['criteria'][0]['field'] = 12; $options['criteria'][0]['searchtype'] = 'equals'; $options['criteria'][0]['value'] = 'all'; $options['criteria'][0]['link'] = 'AND'; $options['metacriteria'][0]['itemtype'] = $itemtype; $options['metacriteria'][0]['field'] = self::getOptionNumber($itemtype, 'name'); $options['metacriteria'][0]['searchtype'] = 'equals'; $options['metacriteria'][0]['value'] = $data['id']; $options['metacriteria'][0]['link'] = 'AND'; } } $options['reset'] = 'reset'; $out = "<a id='ticket{$itemtype}" . $data['id'] . "' "; $out .= "href=\"" . $CFG_GLPI["root_doc"] . "/front/ticket.php?" . Toolbox::append_params($options, '&') . "\">"; $out .= $data[$num][0]['name'] . "</a>"; return $out; } } break; case "glpi_tickets.due_date": case "glpi_problems.due_date": case "glpi_changes.due_date": // Due date + progress if ($ID == 151) { $out = Html::convDate($data[$num][0]['name']); // No due date in waiting status if ($data[$num][0]['status'] == CommonITILObject::WAITING) { return ''; } if (empty($data[$num][0]['name'])) { return ''; } if ($data[$num][0]['status'] == Ticket::SOLVED || $data[$num][0]['status'] == Ticket::CLOSED) { return $out; } $itemtype = getItemTypeForTable($table); $item = new $itemtype(); $item->getFromDB($data['id']); $percentage = 0; $totaltime = 0; $currenttime = 0; if ($item->isField('slas_id') && $item->fields['slas_id'] != 0) { // Have SLA $sla = new SLA(); $sla->getFromDB($item->fields['slas_id']); $currenttime = $sla->getActiveTimeBetween($item->fields['date'], date('Y-m-d H:i:s')); $totaltime = $sla->getActiveTimeBetween($item->fields['date'], $data[$num][0]['name']); } else { $calendars_id = Entity::getUsedConfig('calendars_id', $item->fields['entities_id']); if ($calendars_id != 0) { // Ticket entity have calendar $calendar = new Calendar(); $calendar->getFromDB($calendars_id); $currenttime = $calendar->getActiveTimeBetween($item->fields['date'], date('Y-m-d H:i:s')); $totaltime = $calendar->getActiveTimeBetween($item->fields['date'], $data[$num][0]['name']); } else { // No calendar $currenttime = strtotime(date('Y-m-d H:i:s')) - strtotime($item->fields['date']); $totaltime = strtotime($data[$num][0]['name']) - strtotime($item->fields['date']); } } if ($totaltime != 0) { $percentage = round(100 * $currenttime / $totaltime); } else { // Total time is null : no active time $percentage = 100; } if ($percentage > 100) { $percentage = 100; } $percentage_text = $percentage; if ($_SESSION['glpiduedatewarning_unit'] == '%') { $less_warn_limit = $_SESSION['glpiduedatewarning_less']; $less_warn = 100 - $percentage; } else { if ($_SESSION['glpiduedatewarning_unit'] == 'hour') { $less_warn_limit = $_SESSION['glpiduedatewarning_less'] * HOUR_TIMESTAMP; $less_warn = $totaltime - $currenttime; } else { if ($_SESSION['glpiduedatewarning_unit'] == 'day') { $less_warn_limit = $_SESSION['glpiduedatewarning_less'] * DAY_TIMESTAMP; $less_warn = $totaltime - $currenttime; } } } if ($_SESSION['glpiduedatecritical_unit'] == '%') { $less_crit_limit = $_SESSION['glpiduedatecritical_less']; $less_crit = 100 - $percentage; } else { if ($_SESSION['glpiduedatecritical_unit'] == 'hour') { $less_crit_limit = $_SESSION['glpiduedatecritical_less'] * HOUR_TIMESTAMP; $less_crit = $totaltime - $currenttime; } else { if ($_SESSION['glpiduedatecritical_unit'] == 'day') { $less_crit_limit = $_SESSION['glpiduedatecritical_less'] * DAY_TIMESTAMP; $less_crit = $totaltime - $currenttime; } } } $color = $_SESSION['glpiduedateok_color']; if ($less_crit < $less_crit_limit) { $color = $_SESSION['glpiduedatecritical_color']; } else { if ($less_warn < $less_warn_limit) { $color = $_SESSION['glpiduedatewarning_color']; } } //Calculate bar progress $out .= "<div class='center' style='background-color: #ffffff; width: 100%;\n border: 1px solid #9BA563; position: relative;' >"; $out .= "<div style='position:absolute;'> " . $percentage_text . "%</div>"; $out .= "<div class='center' style='background-color: " . $color . ";\n width: " . $percentage . "%; height: 12px' ></div>"; $out .= "</div>"; return $out; } break; case "glpi_softwarelicenses.number": if ($data[$num][0]['min'] == -1) { return __('Unlimited'); } if (empty($data[$num][0]['name'])) { return 0; } return $data[$num][0]['name']; case "glpi_auth_tables.name": return Auth::getMethodName($data[$num][0]['name'], $data[$num][0]['auths_id'], 1, $data[$num][0]['ldapname'] . $data[$num][0]['mailname']); case "glpi_reservationitems.comment": if (empty($data[$num][0]['name'])) { return "<a title=\"" . __s('Modify the comment') . "\"\n href='" . $CFG_GLPI["root_doc"] . "/front/reservationitem.form.php?id=" . $data["refID"] . "' >" . __('None') . "</a>"; } return "<a title=\"" . __s('Modify the comment') . "\"\n href='" . $CFG_GLPI["root_doc"] . "/front/reservationitem.form.php?id=" . $data['refID'] . "' >" . Html::resume_text($data[$num][0]['name']) . "</a>"; case 'glpi_crontasks.description': $tmp = new CronTask(); return $tmp->getDescription($data[$num][0]['name']); case 'glpi_changes.status': $status = Change::getStatus($data[$num][0]['name']); return "<img src=\"" . Change::getStatusIconURL($data[$num][0]['name']) . "\"\n alt=\"{$status}\" title=\"{$status}\"> {$status}"; case 'glpi_problems.status': $status = Problem::getStatus($data[$num][0]['name']); return "<img src=\"" . Problem::getStatusIconURL($data[$num][0]['name']) . "\"\n alt=\"{$status}\" title=\"{$status}\"> {$status}"; case 'glpi_tickets.status': $status = Ticket::getStatus($data[$num][0]['name']); return "<img src=\"" . Ticket::getStatusIconURL($data[$num][0]['name']) . "\"\n alt=\"{$status}\" title=\"{$status}\"> {$status}"; case 'glpi_projectstates.name': $out = ''; $query = "SELECT `color`\n FROM `glpi_projectstates`\n WHERE `name` = '" . $data[$num][0]['name'] . "'"; foreach ($DB->request($query) as $color) { $color = $color['color']; $out = "<div style=\"background-color:" . $color . ";\">"; $name = $data[$num][0]['name']; if (isset($data[$num][0]['trans'])) { $name = $data[$num][0]['trans']; } if ($itemtype == 'ProjectState') { $out .= "<a href='" . $CFG_GLPI["root_doc"] . "/front/projectstate.form.php?id=" . $data[$num][0]["id"] . "'>" . $name . "</a></div>"; } else { $out .= $name . "</div>"; } } return $out; case 'glpi_items_tickets.items_id': case 'glpi_items_problems.items_id': if (!empty($data[$num])) { $items = array(); foreach ($data[$num] as $key => $val) { if (is_numeric($key)) { if (!empty($val['itemtype']) && ($item = getItemForItemtype($val['itemtype']))) { if ($item->getFromDB($val['name'])) { $items[] = $item->getLink(array('comments' => true)); } } } } if (!empty($items)) { return implode("<br>", $items); } } return ' '; case 'glpi_items_tickets.itemtype': case 'glpi_items_problems.itemtype': if (!empty($data[$num])) { $itemtypes = array(); foreach ($data[$num] as $key => $val) { if (is_numeric($key)) { if (!empty($val['name'])) { if (substr($val['name'], 0, 6) == 'Plugin') { $plug = new $val['name'](); $name = $plug->getTypeName(); $itemtypes[] = __($name); } else { $itemtypes[] = __($val['name']); } } } } if (!empty($itemtypes)) { return implode("<br>", $itemtypes); } } return ' '; case 'glpi_tickets.name': case 'glpi_problems.name': case 'glpi_changes.name': if (isset($data[$num][0]['content']) && isset($data[$num][0]['id']) && isset($data[$num][0]['status'])) { $link = Toolbox::getItemTypeFormURL($itemtype); $out = "<a id='{$itemtype}" . $data[$num][0]['id'] . "' href=\"" . $link; $out .= strstr($link, '?') ? '&' : '?'; $out .= 'id=' . $data[$num][0]['id']; // Force solution tab if solved if ($item = getItemForItemtype($itemtype)) { if (in_array($data[$num][0]['status'], $item->getSolvedStatusArray())) { $out .= "&forcetab={$itemtype}\$2"; } } $out .= "\">"; $name = $data[$num][0]['name']; if ($_SESSION["glpiis_ids_visible"] || empty($data[$num][0]['name'])) { $name = sprintf(__('%1$s (%2$s)'), $name, $data[$num][0]['id']); } $out .= $name . "</a>"; $hdecode = Html::entity_decode_deep($data[$num][0]['content']); $content = Toolbox::unclean_cross_side_scripting_deep($hdecode); $out = sprintf(__('%1$s %2$s'), $out, Html::showToolTip(nl2br(Html::Clean($content)), array('applyto' => $itemtype . $data[$num][0]['id'], 'display' => false))); return $out; } case 'glpi_ticketvalidations.status': $out = ''; for ($k = 0; $k < $data[$num]['count']; $k++) { if ($data[$num][$k]['name']) { $status = TicketValidation::getStatus($data[$num][$k]['name']); $bgcolor = TicketValidation::getStatusColor($data[$num][$k]['name']); $out .= (empty($out) ? '' : self::LBBR) . "<div style=\"background-color:" . $bgcolor . ";\">" . $status . '</div>'; } } return $out; case 'glpi_ticketsatisfactions.satisfaction': if (self::$output_type == self::HTML_OUTPUT) { return TicketSatisfaction::displaySatisfaction($data[$num][0]['name']); } break; case 'glpi_projects._virtual_planned_duration': return Html::timestampToString(ProjectTask::getTotalPlannedDurationForProject($data["id"]), false); case 'glpi_projects._virtual_effective_duration': return Html::timestampToString(ProjectTask::getTotalEffectiveDurationForProject($data["id"]), false); case 'glpi_cartridgeitems._virtual': return Cartridge::getCount($data["id"], $data[$num][0]['alarm_threshold'], self::$output_type != self::HTML_OUTPUT); case 'glpi_printers._virtual': return Cartridge::getCountForPrinter($data["id"], self::$output_type != self::HTML_OUTPUT); case 'glpi_consumableitems._virtual': return Consumable::getCount($data["id"], $data[$num][0]['alarm_threshold'], self::$output_type != self::HTML_OUTPUT); case 'glpi_links._virtual': $out = ''; $link = new Link(); if (($item = getItemForItemtype($itemtype)) && $item->getFromDB($data['id']) && $link->getfromDB($data[$num][0]['id']) && $item->fields['entities_id'] == $link->fields['entities_id']) { if (count($data[$num])) { $count_display = 0; foreach ($data[$num] as $val) { if (is_array($val)) { $links = Link::getAllLinksFor($item, $val); foreach ($links as $link) { if ($count_display) { $out .= self::LBBR; } $out .= $link; $count_display++; } } } } } return $out; case 'glpi_reservationitems._virtual': if ($data[$num][0]['is_active']) { return "<a href='reservation.php?reservationitems_id=" . $data["refID"] . "' title=\"" . __s('See planning') . "\">" . "<img src=\"" . $CFG_GLPI["root_doc"] . "/pics/reservation-3.png\" alt='' title=''></a>"; } else { return " "; } } } //// Default case // Link with plugin tables : need to know left join structure if (isset($table)) { if (preg_match("/^glpi_plugin_([a-z0-9]+)/", $table . '.' . $field, $matches)) { if (count($matches) == 2) { $plug = $matches[1]; $function = 'plugin_' . $plug . '_giveItem'; if (function_exists($function)) { $out = $function($itemtype, $ID, $data, $num); if (!empty($out)) { return $out; } } } } } $unit = ''; if (isset($searchopt[$ID]['unit'])) { $unit = $searchopt[$ID]['unit']; } // Preformat items if (isset($searchopt[$ID]["datatype"])) { switch ($searchopt[$ID]["datatype"]) { case "itemlink": $linkitemtype = getItemTypeForTable($searchopt[$ID]["table"]); $out = ""; $count_display = 0; $separate = self::LBBR; if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) { $separate = self::LBHR; } for ($k = 0; $k < $data[$num]['count']; $k++) { if (isset($data[$num][$k]['id'])) { if ($count_display) { $out .= $separate; } $count_display++; $page = $linkitemtype::getFormUrl(); $page .= strpos($page, '?') ? '&id' : '?id'; $name = Dropdown::getValueWithUnit($data[$num][$k]['name'], $unit); if ($_SESSION["glpiis_ids_visible"] || empty($data[$num][$k]['name'])) { $name = sprintf(__('%1$s (%2$s)'), $name, $data[$num][$k]['id']); } $out .= "<a id='" . $linkitemtype . "_" . $data['id'] . "_" . $data[$num][$k]['id'] . "' href='{$page}=" . $data[$num][$k]['id'] . "'>" . $name . "</a>"; } } return $out; case "text": $separate = self::LBBR; if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) { $separate = self::LBHR; } $out = ''; $count_display = 0; for ($k = 0; $k < $data[$num]['count']; $k++) { if (strlen(trim($data[$num][$k]['name'])) > 0) { if ($count_display) { $out .= $separate; } $count_display++; $text = ""; if (isset($searchopt[$ID]['htmltext']) && $searchopt[$ID]['htmltext']) { $text = Html::clean(Toolbox::unclean_cross_side_scripting_deep(nl2br($data[$num][$k]['name']))); } else { $text = nl2br($data[$num][$k]['name']); } if (self::$output_type == self::HTML_OUTPUT && Toolbox::strlen($text) > $CFG_GLPI['cut']) { $rand = mt_rand(); $out .= sprintf(__('%1$s %2$s'), "<span id='text{$rand}'>" . Html::resume_text($text, $CFG_GLPI['cut']) . '</span>', Html::showToolTip($text, array('applyto' => "text{$rand}", 'display' => false))); } else { $out .= $text; } } } return $out; case "date": case "date_delay": $out = ''; for ($k = 0; $k < $data[$num]['count']; $k++) { if (is_null($data[$num][$k]['name']) && isset($searchopt[$ID]['emptylabel']) && $searchopt[$ID]['emptylabel']) { $out .= (empty($out) ? '' : self::LBBR) . $searchopt[$ID]['emptylabel']; } else { $out .= (empty($out) ? '' : self::LBBR) . Html::convDate($data[$num][$k]['name']); } } return $out; case "datetime": $out = ''; for ($k = 0; $k < $data[$num]['count']; $k++) { if (is_null($data[$num][$k]['name']) && isset($searchopt[$ID]['emptylabel']) && $searchopt[$ID]['emptylabel']) { $out .= (empty($out) ? '' : self::LBBR) . $searchopt[$ID]['emptylabel']; } else { $out .= (empty($out) ? '' : self::LBBR) . Html::convDateTime($data[$num][$k]['name']); } } return $out; case "timestamp": $withseconds = false; if (isset($searchopt[$ID]['withseconds'])) { $withseconds = $searchopt[$ID]['withseconds']; } $withdays = true; if (isset($searchopt[$ID]['withdays'])) { $withdays = $searchopt[$ID]['withdays']; } $out = ''; for ($k = 0; $k < $data[$num]['count']; $k++) { $out .= (empty($out) ? '' : '<br>') . Html::timestampToString($data[$num][$k]['name'], $withseconds, $withdays); } return $out; case "email": $out = ''; $count_display = 0; for ($k = 0; $k < $data[$num]['count']; $k++) { if ($count_display) { $out .= self::LBBR; } $count_display++; if (!empty($data[$num][$k]['name'])) { $out .= empty($out) ? '' : self::LBBR; $out .= "<a href='mailto:" . $data[$num][$k]['name'] . "'>" . $data[$num][$k]['name']; $out .= "</a>"; } } return empty($out) ? " " : $out; case "weblink": $orig_link = trim($data[$num][0]['name']); if (!empty($orig_link)) { // strip begin of link $link = preg_replace('/https?:\\/\\/(www[^\\.]*\\.)?/', '', $orig_link); $link = preg_replace('/\\/$/', '', $link); if (Toolbox::strlen($link) > $CFG_GLPI["url_maxlength"]) { $link = Toolbox::substr($link, 0, $CFG_GLPI["url_maxlength"]) . "..."; } return "<a href=\"" . formatOutputWebLink($orig_link) . "\" target='_blank'>{$link}</a>"; } return " "; case "count": case "number": $out = ""; $count_display = 0; for ($k = 0; $k < $data[$num]['count']; $k++) { if (strlen(trim($data[$num][$k]['name'])) > 0) { if ($count_display) { $out .= self::LBBR; } $count_display++; if (isset($searchopt[$ID]['toadd']) && isset($searchopt[$ID]['toadd'][$data[$num][$k]['name']])) { $out .= $searchopt[$ID]['toadd'][$data[$num][$k]['name']]; } else { $number = str_replace(' ', ' ', Html::formatNumber($data[$num][$k]['name'], false, 0)); $out .= Dropdown::getValueWithUnit($number, $unit); } } } return $out; case "decimal": $out = ""; $count_display = 0; for ($k = 0; $k < $data[$num]['count']; $k++) { if (strlen(trim($data[$num][$k]['name'])) > 0) { if ($count_display) { $out .= self::LBBR; } $count_display++; if (isset($searchopt[$ID]['toadd']) && isset($searchopt[$ID]['toadd'][$data[$num][$k]['name']])) { $out .= $searchopt[$ID]['toadd'][$data[$num][$k]['name']]; } else { $number = str_replace(' ', ' ', Html::formatNumber($data[$num][$k]['name'])); $out .= Dropdown::getValueWithUnit($number, $unit); } } } return $out; case "bool": $out = ""; $count_display = 0; for ($k = 0; $k < $data[$num]['count']; $k++) { if (strlen(trim($data[$num][$k]['name'])) > 0) { if ($count_display) { $out .= self::LBBR; } $count_display++; $out .= Dropdown::getValueWithUnit(Dropdown::getYesNo($data[$num][$k]['name']), $unit); } } return $out; case "itemtypename": if ($obj = getItemForItemtype($data[$num][0]['name'])) { return $obj->getTypeName(); } return ""; case "language": if (isset($CFG_GLPI['languages'][$data[$num][0]['name']])) { return $CFG_GLPI['languages'][$data[$num][0]['name']][0]; } return __('Default value'); } } // Manage items with need group by / group_concat $out = ""; $count_display = 0; $separate = self::LBBR; if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) { $separate = self::LBHR; } for ($k = 0; $k < $data[$num]['count']; $k++) { if (strlen(trim($data[$num][$k]['name'])) > 0) { if ($count_display) { $out .= $separate; } $count_display++; // Get specific display if available $itemtype = getItemTypeForTable($table); if ($item = getItemForItemtype($itemtype)) { $tmpdata = $data[$num][$k]; // Copy name to real field $tmpdata[$field] = $data[$num][$k]['name']; $specific = $item->getSpecificValueToDisplay($field, $tmpdata, array('html' => true, 'searchopt' => $searchopt[$ID])); } if (!empty($specific)) { $out .= $specific; } else { if (isset($searchopt[$ID]['toadd']) && isset($searchopt[$ID]['toadd'][$data[$num][$k]['name']])) { $out .= $searchopt[$ID]['toadd'][$data[$num][$k]['name']]; } else { // Empty is 0 or empty if (empty($split[0]) && isset($searchopt[$ID]['emptylabel'])) { $out .= $searchopt[$ID]['emptylabel']; } else { // Trans field exists if (isset($data[$num][$k]['trans']) && !empty($data[$num][$k]['trans'])) { $out .= Dropdown::getValueWithUnit($data[$num][$k]['trans'], $unit); } else { $out .= Dropdown::getValueWithUnit($data[$num][$k]['name'], $unit); } } } } } } return $out; // Trans in group concat if (count($split) == 3 && !empty($split[1])) { return Dropdown::getValueWithUnit($split[1], $unit); } return Dropdown::getValueWithUnit($split[0], $unit); }
public function actionGeneratePdf() { $this->layout = 'pdf'; $model = new Cartridge('search'); if (isset($_GET['Cartridge'])) { $model->attributes = $_GET['Cartridge']; } // to execute the filters (if is the case) $dataProvider = $model->search(); $dataProvider->pagination = false; $mPDF1 = Yii::app()->ePdf->mpdf(); # You can easily override default constructor's params $mPDF1 = Yii::app()->ePdf->mpdf('', 'A5'); # renderPartial (only 'view' of current controller) $mPDF1->WriteHTML($this->renderPartial('admin', array('model' => $model), true)); # Outputs ready PDF $mPDF1->Output(); }
/** Generate bigdump : generate items for an entity * * @param $ID_entity entity ID **/ function generate_entity($ID_entity) { global $MAX, $DB, $percent, $FIRST, $LAST, $MAX_KBITEMS_BY_CAT, $MAX_DISK, $DOCUMENTS, $NET_PORT, $NET_LOC; regenerateTreeCompleteName("glpi_entities"); $current_year = date("Y"); // DOMAIN $items = array("SP2MI", "CAMPUS"," IUT86", "PRESIDENCE", "CEAT", "D'omaine"); $dp = new Domain(); $FIRST["domain"] = getMaxItem("glpi_domains")+1; for ($i=0 ; $i<$MAX['domain'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "domain $ID_entity '$i"; } $dp->add(toolbox::addslashes_deep(array('name' => $val, 'entities_id' => $ID_entity, 'is_recursive' => 1, 'comment' => "comment $val"))); } $LAST["domain"] = getMaxItem("glpi_domains"); // STATUS $items = array("Reparation", "En stock", "En fonction", "Retour SAV", "En attente d'"); $dp = new State(); $FIRST["state"] = getMaxItem("glpi_states")+1; for ($i=0 ; $i<$MAX['state'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "State $ID_entity '$i"; } $state_id = $dp->add(toolbox::addslashes_deep(array('name' => $val, 'entities_id' => $ID_entity, 'is_recursive' => 1, 'comment' => "comment $val"))); // generate sub status for ($j=0 ; $j<$MAX['state'] ; $j++) { $val2 = "Sub $val $j"; $dp->add(toolbox::addslashes_deep(array('name' => $val2, 'entities_id' => $ID_entity, 'is_recursive' => 1, 'states_id' => $state_id, 'comment' => "comment $val"))); } } $LAST["state"] = getMaxItem("glpi_states"); // glpi_groups $FIRST["groups"] = getMaxItem("glpi_groups")+1; $group = new Group(); for ($i=0 ; $i<$MAX['groups'] ; $i++) { $gID = $group->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'name' => "group d'$i", 'comment' => "comment group d'$i", 'is_assign' => 0))); // Generate sub group for ($j=0 ; $j<$MAX['groups'] ; $j++) { $group->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'name' => "subgroup d'$j", 'comment' => "comment subgroup d'$j of group $i", 'groups_id' => $gID, 'is_assign' => 0))); } } $LAST["groups"] = getMaxItem("glpi_groups"); $FIRST["techgroups"] = $LAST["groups"]+1; for ($i=0 ; $i<$MAX['groups'] ; $i++) { $group->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'name' => "tech group d'$i", 'comment' => "comment tech group d'$i"))); } $LAST["techgroups"] = getMaxItem("glpi_groups"); regenerateTreeCompleteName("glpi_groups"); // glpi_users $FIRST["users_sadmin"] = getMaxItem("glpi_users")+1; $user = new User(); $gu = new Group_User(); for ($i=0 ; $i<$MAX['users_sadmin'] ; $i++) { $users_id = $user->add(toolbox::addslashes_deep( array('name' => "sadmin$i-$ID_entity", 'password' => "sadmin'$i", 'password2' => "sadmin'$i", 'phone' => "tel $i", 'phone2' => "tel2 $i", 'mobile' => "mobile $i", 'realname' => "sadmin '$i name", 'firstname' => "sadmin '$i firstname", 'comment' => "comment' $i", 'usertitles_id' => mt_rand(0,$MAX['user_title']), 'usercategories_id' => mt_rand(0,$MAX['user_type']), '_profiles_id' => 4, '_entities_id' => $ID_entity, '_is_recursive' => 1 ))); $gu->add(array('users_id' => $users_id, 'groups_id' => mt_rand($FIRST['groups'], $LAST['groups']))); $gu->add(array('users_id' => $users_id, 'groups_id' => mt_rand($FIRST['techgroups'], $LAST['techgroups']))); } $LAST["users_sadmin"] = getMaxItem("glpi_users"); $FIRST["users_admin"] = getMaxItem("glpi_users")+1; for ($i=0 ; $i<$MAX['users_admin'] ; $i++) { $users_id = $user->add(toolbox::addslashes_deep( array('name' => "admin$i-$ID_entity", 'password' => "admin'$i", 'password2' => "admin'$i", 'phone' => "tel $i", 'phone2' => "tel2 $i", 'mobile' => "mobile $i", 'realname' => "admin$i 'name", 'firstname' => "admin$i 'firstname", 'comment' => "comment '$i", 'usertitles_id' => mt_rand(0,$MAX['user_title']), 'usercategories_id' => mt_rand(0,$MAX['user_type']), '_profiles_id' => 3, '_entities_id' => $ID_entity, '_is_recursive' => 1))); $gu->add(array('users_id' => $users_id, 'groups_id' => mt_rand($FIRST['groups'], $LAST['groups']), 'is_manager' => 1, 'is_delegate' => 1)); $gu->add(array('users_id' => $users_id, 'groups_id' => mt_rand($FIRST['techgroups'], $LAST['techgroups']), 'is_manager' => 1, 'is_delegate' => 1)); } $LAST["users_admin"] = getMaxItem("glpi_users"); $FIRST["users_normal"] = getMaxItem("glpi_users")+1; for ($i=0 ; $i<$MAX['users_normal'] ; $i++) { $users_id = $user->add(toolbox::addslashes_deep( array('name' => "normal$i-$ID_entity", 'password' => "normal'$i", 'password2' => "normal'$i", 'phone' => "tel $i", 'phone2' => "tel2 $i", 'mobile' => "mobile $i", 'realname' => "normal$i 'name", 'firstname' => "normal$i 'firstname", 'comment' => "comment '$i", 'usertitles_id' => mt_rand(0,$MAX['user_title']), 'usercategories_id' => mt_rand(0,$MAX['user_type']), '_profiles_id' => 2, '_entities_id' => $ID_entity, '_is_recursive' => 1))); $gu->add(array('users_id' => $users_id, 'groups_id' => mt_rand($FIRST['groups'], $LAST['groups']))); $gu->add(array('users_id' => $users_id, 'groups_id' => mt_rand($FIRST['techgroups'], $LAST['techgroups']))); } $LAST["users_normal"] = getMaxItem("glpi_users"); $FIRST["users_postonly"] = getMaxItem("glpi_users")+1; for ($i=0 ; $i<$MAX['users_postonly'] ; $i++) { $users_id = $user->add(toolbox::addslashes_deep( array('name' => "postonly$i-$ID_entity", 'password' => "postonly'$i", 'password2' => "postonly'$i", 'phone' => "tel $i", 'phone2' => "tel2 $i", 'mobile' => "mobile $i", 'realname' => "postonly$i 'name", 'firstname' => "postonly$i 'firstname", 'comment' => "comment' $i", 'usertitles_id' => mt_rand(0,$MAX['user_title']), 'usercategories_id' => mt_rand(0,$MAX['user_type']), '_profiles_id' => 1, '_entities_id' => $ID_entity, '_is_recursive' => 1))); $gu->add(array('users_id' => $users_id, 'groups_id' => mt_rand($FIRST['groups'], $LAST['groups']))); } $LAST["users_postonly"] = getMaxItem("glpi_users"); $FIRST["kbcategories"] = getMaxItem("glpi_knowbaseitemcategories")+1; $kbc = new KnowbaseItemCategory(); for ($i=0 ; $i<max(1,pow($MAX['kbcategories'],1/3)) ; $i++) { $newID = $kbc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "entity ' categorie $i", 'comment' => "comment ' categorie $i"))); for ($j=0 ; $j<mt_rand(0,pow($MAX['kbcategories'],1/2)) ; $j++) { $newID2 = $kbc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "entity s-categorie '$j", 'comment' => "comment s-categorie '$j", 'knowbaseitemcategories_id' => $newID))); for ($k=0 ; $k<mt_rand(0,pow($MAX['kbcategories'],1/2)) ; $k++) { $newID2 = $kbc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "entity ss-categorie' $k", 'comment' => "comment ss-categorie' $k", 'knowbaseitemcategories_id' => $newID2))); } } } $query = "OPTIMIZE TABLE `glpi_knowbaseitemcategories`"; $DB->query($query) or die("PB REQUETE ".$query); regenerateTreeCompleteName("glpi_knowbaseitemcategories"); $LAST["kbcategories"] = getMaxItem("glpi_knowbaseitemcategories"); // LOCATIONS $added = 0; $FIRST["locations"] = getMaxItem("glpi_locations")+1; $loc = new Location(); for ($i=0 ; $i<pow($MAX['locations'],1/5)&&$added<$MAX['locations'] ; $i++) { $added++; $newID = $loc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "location' $i", 'comment' => "comment 'location $i", 'building' => "building $i"))); for ($j=0 ; $j<mt_rand(0,pow($MAX['locations'],1/4))&&$added<$MAX['locations'] ; $j++) { $added++; $newID2 = $loc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "s-location '$j", 'comment' => "comment s-location '$j", 'building' => "building $i", 'room' => "stage '$j", 'locations_id' => $newID))); for ($k=0 ; $k<mt_rand(0,pow($MAX['locations'],1/4))&&$added<$MAX['locations'] ; $k++) { $added++; $newID3 = $loc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "ss-location '$k", 'comment' => "comment ss-location' $k", 'building' => "building $i", 'room' => "part' $k", 'locations_id' => $newID2))); for ($l=0 ; $l<mt_rand(0,pow($MAX['locations'],1/4))&&$added<$MAX['locations'] ; $l++) { $added++; $newID4 = $loc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "sss-location' $l", 'comment' => "comment sss-location' $l", 'building' => "building $i", 'room' => "room' $l", 'locations_id' => $newID3))); for ($m=0 ; $m<mt_rand(0,pow($MAX['locations'],1/4))&&$added<$MAX['locations'] ; $m++) { $added++; $newID5 = $loc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "ssss-location' $m", 'comment' => "comment ssss-location' $m", 'building' => "building $i", 'room' => "room' $l-$m", 'locations_id' => $newID4))); } } } } } $query = "OPTIMIZE TABLE `glpi_locations`"; $DB->query($query) or die("PB REQUETE ".$query); regenerateTreeCompleteName("glpi_locations"); $LAST["locations"]=getMaxItem("glpi_locations"); // Task categories $added = 0; $FIRST["taskcategory"] = getMaxItem("glpi_taskcategories")+1; $tc = new TaskCategory(); for ($i=0 ; $i<pow($MAX['taskcategory'],1/5)&&$added<$MAX['taskcategory'] ; $i++) { $added++; $newID = $tc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "ent$ID_entity taskcategory' $i", 'comment' => "comment ent$ID_entity taskcategory' $i"))); for ($j=0 ; $j<mt_rand(0,pow($MAX['locations'],1/4))&&$added<$MAX['locations'] ; $j++) { $newID2 = $tc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "ent$ID_entity taskcategory' $i", 'comment' => "comment ent$ID_entity taskcategory' $i", 'taskcategories_id' => $newID))); $added++; } } $query = "OPTIMIZE TABLE `glpi_taskcategories`"; $DB->query($query) or die("PB REQUETE ".$query); regenerateTreeCompleteName("glpi_taskcategories"); $LAST["taskcategory"] = getMaxItem("glpi_taskcategories"); $ic = new ItilCategory(); // Specific ticket categories $newID = $ic->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "category for entity' $ID_entity", 'comment' => "comment category for entity' $ID_entity", 'users_id' => mt_rand($FIRST['users_sadmin'],$LAST['users_admin']), 'groups_id' => mt_rand($FIRST['techgroups'],$LAST['techgroups']), 'tickettemplates_id_incident' => 1, 'tickettemplates_id_demand' => 1))); for ($i=0 ; $i<max(1,pow($MAX['tracking_category'],1/3)) ; $i++) { $ic->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "scategory for entity' $ID_entity", 'comment' => "comment scategory for entity' $ID_entity", 'users_id' => mt_rand($FIRST['users_sadmin'], $LAST['users_admin']), 'groups_id' => mt_rand($FIRST['techgroups'], $LAST['techgroups']), 'tickettemplates_id_incident' => 1, 'tickettemplates_id_demand' => 1, 'itilcategories_id' => $newID))); } regenerateTreeCompleteName("glpi_itilcategories"); $FIRST["solutiontypes"] = getMaxItem("glpi_solutiontypes")+1; $items = array("d'après KB"); $st = new SolutionType(); for ($i=0 ; $i<$MAX['solutiontypes'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "type de solution ' $i"; } $st->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment $val", 'entities_id' => $ID_entity, 'is_recursive' => 1))); } $LAST["solutiontypes"] = getMaxItem("glpi_solutiontypes"); $FIRST["solutiontemplates"] = getMaxItem("glpi_solutiontemplates")+1; $nb_items = mt_rand(0,$MAX['solutiontemplates']); $st = new SolutionTemplate(); for ($i=0 ; $i<$nb_items ; $i++) { $st-> add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "solution' $i-$ID_entity", 'content' => "content solution' $i-$ID_entity", 'solutiontypes_id' => mt_rand(0,$MAX['solutiontypes']), 'comment' => "comment solution' $i-$ID_entity"))); } $LAST["solutiontemplates"] = getMaxItem("glpi_solutiontemplates"); // Add Specific questions $k = 0; $FIRST["kbitems"] = getMaxItem("glpi_knowbaseitems")+1; $ki = new KnowbaseItem(); $eki = new Entity_KnowbaseItem(); for ($i=$FIRST['kbcategories'] ; $i<=$LAST['kbcategories'] ; $i++) { $nb = mt_rand(0,$MAX_KBITEMS_BY_CAT); for ($j=0 ; $j<$nb ; $j++) { $k++; $newID = $ki->add(toolbox::addslashes_deep( array('knowbaseitemcategories_id' => $i, 'name' => "Entity' $ID_entity Question $k", 'answer' => "Answer' $k".Toolbox::getRandomString(50), 'is_faq' => mt_rand(0,1), 'users_id' => mt_rand($FIRST['users_sadmin'], $LAST['users_admin'])))); $eki->add(array('entities_id' => $ID_entity, 'knowbaseitems_id' => $newID, 'is_recursive' => 0)); } } // Add global questions for ($i=$FIRST['kbcategories'] ; $i<=$LAST['kbcategories'] ; $i++) { $nb = mt_rand(0,$MAX_KBITEMS_BY_CAT); for ($j=0 ; $j<$nb ; $j++) { $k++; $newID = $ki->add(toolbox::addslashes_deep( array('knowbaseitemcategories_id' => $i, 'name' => "Entity' $ID_entity Recursive Question $k", 'answer' => "Answer' $k".Toolbox::getRandomString(50), 'is_faq' => mt_rand(0,1), 'users_id' => mt_rand($FIRST['users_sadmin'], $LAST['users_admin'])))); $eki->add(array('entities_id' => $ID_entity, 'knowbaseitems_id' => $newID, 'is_recursive' => 1)); } } $LAST["kbitems"] = getMaxItem("glpi_knowbaseitems"); // Ajout documents specific $FIRST["document"] = getMaxItem("glpi_documents")+1; $doc = new Document(); for ($i=0 ; $i<$MAX['document'] ; $i++) { $link = ""; if (mt_rand(0,100)<50) { $link = "http://linktodoc/doc$i"; } $docID = $doc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 0, 'name' => "document' $i-$ID_entity", 'documentcategories_id' => mt_rand(1,$MAX['rubdocs']), 'comment' => "commen't $i", 'link' => $link, 'notepad' => "notes document' $i"))); $DOCUMENTS[$docID] = $ID_entity."-0"; } // Global ones for ($i=0 ; $i<$MAX['document']/2 ; $i++) { $link = ""; if (mt_rand(0,100)<50) { $link = "http://linktodoc/doc$i"; } $docID = $doc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "Recursive document' $i-$ID_entity", 'documentcategories_id' => mt_rand(1,$MAX['rubdocs']), 'comment' => "comment' $i", 'link' => $link, 'notepad' => "notes document' $i"))); $DOCUMENTS[$docID] = $ID_entity."-1"; } $LAST["document"] = getMaxItem("glpi_documents"); // Ajout budgets specific $FIRST["budget"] = getMaxItem("glpi_budgets")+1; $b = new Budget(); for ($i=0 ; $i<$MAX['budget'] ; $i++) { $date1 = strtotime(mt_rand(2000,$current_year)."-".mt_rand(1,12)."-".mt_rand(1,28)); $date2 = $date1+MONTH_TIMESTAMP*12*mt_rand(1,4); // + entre 1 et 4 ans $b->add(toolbox::addslashes_deep( array('name' => "budget' $i-$ID_entity", 'entities_id' => $ID_entity, 'is_recusive' => 0, 'comment' => "comment' $i-$ID_entity", 'begin_date' => date("Y-m-d",intval($date1)), 'end_date' => date("Y-m-d",intval($date2))))); } $LAST["budget"] = getMaxItem("glpi_budgets"); // GLobal ones for ($i=0 ; $i<$MAX['document']/2 ; $i++) { $date1 = strtotime(mt_rand(2000,$current_year)."-".mt_rand(1,12)."-".mt_rand(1,28)); $date2 = $date1+MONTH_TIMESTAMP*12*mt_rand(1,4); // + entre 1 et 4 ans $b->add(toolbox::addslashes_deep( array('name' => "Recursive budget' $i-$ID_entity", 'entities_id' => $ID_entity, 'is_recusive' => 1, 'comment' => "comment' $i-$ID_entity", 'begin_date' => date("Y-m-d",intval($date1)), 'end_date' => date("Y-m-d",intval($date2))))); } $LAST["document"] = getMaxItem("glpi_documents"); // glpi_suppliers $items = array("DELL", "IBM", "ACER", "Microsoft", "Epson", "Xerox", "Hewlett Packard", "Nikon", "Targus", "LG", "Samsung", "Lexmark"); $FIRST["enterprises"] = getMaxItem("glpi_suppliers")+1; $ent = new Supplier(); // Global ones for ($i=0 ; $i<$MAX['enterprises']/2 ; $i++) { if (isset($items[$i])) { $val = "Recursive ".$items[$i]; } else { $val = "Recursive enterprise_".$i."_ID_entity"; } $entID = $ent->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "Recursive' $val-$ID_entity", 'suppliertypes_id' => mt_rand(1,$MAX['enttype']), 'address' => "address' $i", 'postcode' => "postcode $i", 'town' => "town' $i", 'state' => "state' $i", 'country' => "country $i", 'website' => "http://www.$val.com/", 'fax' => "fax $i", 'email' => "info@ent$i.com", 'notepad' => "notes enterprises' $i"))); addDocuments('Supplier', $entID); } // Specific ones for ($i=0 ; $i<$MAX['enterprises'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "enterprise_".$i."_ID_entity"; } $entID = $ent->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 0, 'name' => "'$val-$ID_entity", 'suppliertypes_id' => mt_rand(1,$MAX['enttype']), 'address' => "address' $i", 'postcode' => "postcode $i", 'town' => "town' $i", 'state' => "state' $i", 'country' => "country $i", 'website' => "http://www.$val.com/", 'fax' => "fax $i", 'email' => "info@ent$i.com", 'notepad' => "notes supplier' $i", 'comment' => "comment supplier' $i"))); addDocuments('Supplier', $entID); } $LAST["enterprises"] = getMaxItem("glpi_suppliers"); // Ajout contracts $FIRST["contract"] = getMaxItem("glpi_contracts")+1; $c = new Contract(); $cs = new Contract_Supplier(); $cc = new ContractCost(); // Specific for ($i=0 ; $i<$MAX['contract'] ; $i++) { $date = mt_rand(2000,$current_year)."-".mt_rand(1,12)."-".mt_rand(1,28); $contractID = $c->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 0, 'name' => "contract' $i-$ID_entity", 'num' => "num' $i", 'contracttypes_id' => mt_rand(1,$MAX['contract_type']), 'begin_date' => $date, 'duration' => mt_rand(1,36), 'notice' => mt_rand(1,3), 'periodicity' => mt_rand(1,36), 'billing' => mt_rand(1,36), 'comment' => "comment' $i", 'accounting_number' => "compta num' $i", 'renewal' => 1))); addDocuments('Contract', $contractID); // Add an enterprise $cs->add(array('contracts_id' => $contractID, 'suppliers_id' => mt_rand($FIRST["enterprises"], $LAST["enterprises"]))); // Add a cost $cc->add(toolbox::addslashes_deep( array('contracts_id' => $contractID, 'cost' => mt_rand(100,10000), 'name' => "Initial 'cost", 'begin_date' => $date, 'budgets_id' => mt_rand($FIRST['budget'], $LAST['budget'])))); } for ($i=0 ; $i<$MAX['contract']/2 ; $i++) { $date = mt_rand(2000,$current_year)."-".mt_rand(1,12)."-".mt_rand(1,28); $contractID = $c->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "Recursive contract' $i-$ID_entity", 'num' => "num' $i", 'cost' => mt_rand(100,10000), 'contracttypes_id' => mt_rand(1,$MAX['contract_type']), 'begin_date' => $date, 'duration' => mt_rand(1,36), 'notice' => mt_rand(1,3), 'periodicity' => mt_rand(1,36), 'billing' => mt_rand(1,36), 'comment' => "comment' $i", 'accounting_number' => "compta num' $i", 'renewal' => 1))); addDocuments('Contract', $contractID); // Add an enterprise $cs->add(array('contracts_id' => $contractID, 'suppliers_id' => mt_rand($FIRST["enterprises"], $LAST["enterprises"]))); } $LAST["contract"] = getMaxItem("glpi_contracts"); // Ajout contacts $prenoms = array("Jean", "John", "Louis", "Pierre", "Auguste", "Albert", "Julien", "Guillaume", "Bruno", "Maurice", "Francois", "Laurent", "Richard", "Henri", "Clement", "d'avy"); $noms = array("Dupont", "Smith", "Durand", "Martin", "Dubois", "Dufour", "Dupin", "Duval", "Petit", "Grange", "Bernard", "Bonnet", "Richard", "Leroy", "Dumont", "Fontaine", "d'orleans"); $FIRST["contacts"] = getMaxItem("glpi_contacts")+1; $c = new Contact(); $cs = new Contact_Supplier(); for ($i=0 ; $i<$MAX['contacts'] ; $i++) { if (isset($noms[$i])) { $val = $noms[$i]; } else { $val = "name $i"; } if (isset($prenoms[$i])) { $val2 = $prenoms[$i]; } else { $val2 = "firstname $i"; } $contactID = $c->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 0, 'name' => "$val-$ID_entity", 'firstname' => $val2, 'contacttypes_id' => mt_rand(1,$MAX['contact_type']), 'usertitles_id' => mt_rand(0,$MAX['user_title']), 'phone' => "phone $i", 'phone2' => "phone2 $i", 'mobile' => "mobile $i", 'fax' => "fax $i", 'email' => "email $i", 'address' => "address' $i", 'postcode' => "postcode $i", 'town' => "town' $i", 'state' => "state' $i", 'country' => "country $i", 'comment' => "Comment' $i"))); // Link with enterprise $cs->add(array('contacts_id' => $contactID, 'suppliers_id' => mt_rand($FIRST['enterprises'],$LAST['enterprises']))); } for ($i=0 ; $i<$MAX['contacts']/2 ; $i++) { if (isset($items[$i])) { $val = "Recursive ".$items[$i]; } else { $val = "Recursive contact $i"; } $contactID = $c->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 0, 'name' => "$val'-$ID_entity", 'contacttypes_id' => mt_rand(1,$MAX['contact_type']), 'usertitles_id' => mt_rand(0,$MAX['user_title']), 'phone' => "phone $i", 'phone2' => "phone2 $i", 'mobile' => "mobile $i", 'fax' => "fax $i", 'email' => "email $i", 'address' => "address' $i", 'postcode' => "postcode $i", 'town' => "town' $i", 'state' => "state' $i", 'country' => "country $i", 'comment' => "Comment' $i"))); // Link with enterprise $cs->add(array('contacts_id' => $contactID, 'suppliers_id' => mt_rand($FIRST['enterprises'],$LAST['enterprises']))); } $LAST["contacts"] = getMaxItem("glpi_contacts"); // TYPE DE CONSOMMABLES $FIRST["type_of_consumables"] = getMaxItem("glpi_consumableitems")+1; $ci = new Consumableitem(); for ($i=0 ; $i<$MAX['type_of_consumables'] ; $i++) { $consID = $ci->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => mt_rand(0,1), 'name' => "consumable type' $i", 'ref' => "ref d' $i", 'locations_id' => mt_rand($FIRST["locations"], $LAST['locations']), 'consumableitemtypes_id' => mt_rand(0,$MAX['consumable_type']), 'manufacturers_id' => mt_rand(1,$MAX['manufacturer']), 'users_id_tech' => mt_rand($FIRST['users_sadmin'], $LAST['users_admin']), 'groups_id_tech' => mt_rand($FIRST["groups"], $LAST["groups"]), 'comment' => "comment' $i", 'notepad' => "notes consumableitem' $i", 'alarm_threshold' => mt_rand(0,10)))); addDocuments('ConsumableItem', $consID); // AJOUT INFOCOMS addInfocoms('ConsumableItem', $consID, $ID_entity); // Ajout consommable en stock $c = new Consumable(); for ($j=0 ; $j<mt_rand(0,$MAX['consumables_stock']) ; $j++) { $date = mt_rand(2000,$current_year)."-".mt_rand(1,12)."-".mt_rand(1,28); $ID = $c->add(array('entities_id' => $ID_entity, 'consumableitems_id' => $consID, 'date_in' => $date)); // AJOUT INFOCOMS addInfocoms('Consumable', $ID, $ID_entity); } // Ajout consommable donne for ($j=0 ; $j<mt_rand(0,$MAX['consumables_given']) ; $j++) { $date = mt_rand(2000,$current_year-1)."-".mt_rand(1,12)."-".mt_rand(1,28); $ID = $c->add(array('entities_id' => $ID_entity, 'consumableitems_id' => $consID, 'date_in' => $date, 'date_out' => date("Y-m-d"))); // AJOUT INFOCOMS addInfocoms('Consumable', $ID, $ID_entity); } } $LAST["type_of_consumables"] = getMaxItem("glpi_consumableitems"); // TYPE DE CARTOUCHES $FIRST["type_of_cartridges"] = getMaxItem("glpi_cartridgeitems")+1; $ct = new CartridgeItem(); for ($i=0 ; $i<$MAX['type_of_cartridges'] ; $i++) { $cartID = $ct->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => mt_rand(0,1), 'name' => "cartridge ' type $i", 'ref' => "ref '$i", 'locations_id' => mt_rand($FIRST["locations"], $LAST['locations']), 'manufacturers_id' => mt_rand(1,$MAX['manufacturer']), 'users_id_tech' => mt_rand($FIRST['users_sadmin'], $LAST['users_admin']), 'groups_id_tech' => mt_rand($FIRST["groups"], $LAST["groups"]), 'comment' => "comment '$i", 'notepad' => "notes cartridgeitem '$i", 'alarm_threshold' => mt_rand(0,10)))); addDocuments('CartridgeItem', $cartID); // AJOUT INFOCOMS addInfocoms('CartridgeItem', $cartID, $ID_entity); $c = new Cartridge(); $cipm = new CartridgeItem_PrinterModel(); // Ajout cartouche en stock for ($j=0 ; $j<mt_rand(0,$MAX['cartridges_stock']) ; $j++) { $date = mt_rand(2000,$current_year-1)."-".mt_rand(1,12)."-".mt_rand(1,28); $ID = $c->add(array('entities_id' => $ID_entity, 'cartridgeitems_id' => $cartID, 'date_in' => $date)); // AJOUT INFOCOMS addInfocoms('Cartridge', $ID, $ID_entity); } // Assoc printer type to cartridge type $cipm->add(array('cartridgeitems_id' => $cartID, 'printermodels_id' => mt_rand(1,$MAX['type_printers']), )); } $LAST["type_of_cartridges"] = getMaxItem("glpi_cartridgeitems"); // Networking $NET_LOC = array(); $FIRST["networking"] = getMaxItem("glpi_networkequipments")+1; $FIRST["printers"] = getMaxItem("glpi_printers")+1; $ne = new NetworkEquipment(); $p = new Printer(); $np = new Netpoint(); $c = new Cartridge(); foreach ($DB->request('glpi_locations') as $data) { $i = $data["id"]; $techID = mt_rand($FIRST['users_sadmin'],$LAST['users_admin']); $gtechID = mt_rand($FIRST["techgroups"],$LAST["techgroups"]); $infoIP = getNextIP(); $domainID = mt_rand($FIRST['domain'],$LAST['domain']); $networkID = mt_rand(1,$MAX['network']); // insert networking $netwID = $ne->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'name' => "networking '$i-$ID_entity", 'ram' => mt_rand(32,256), 'serial' => Toolbox::getRandomString(10), 'otherserial' => Toolbox::getRandomString(10), 'contact' => "contact '$i", 'contact_num' => "num '$i", 'users_id_tech' => $techID, 'groups_id_tech' => $gtechID, 'comment' => "comment '$i", 'locations_id' => $i, 'domains_id' => $domainID, 'networks_id' => $networkID, 'networkequipmenttypes_id' => mt_rand(1,$MAX['type_networking']), 'networkequipmentmodels_id' => mt_rand(1,$MAX['model_networking']), 'networkequipmentfirmwares_id' => mt_rand(1,$MAX['firmware']), 'manufacturers_id' => mt_rand(1,$MAX['enterprises']), 'mac' => getNextMAC(), 'ip' => $infoIP["ip"], 'notepad' => "notes networking '$i", 'users_id' => mt_rand($FIRST['users_sadmin'], $LAST['users_admin']), 'groups_id' => mt_rand($FIRST["groups"], $LAST["groups"]), 'states_id' => (mt_rand(0,100)<$percent['state'] ?mt_rand($FIRST['state'],$LAST['state']):0) ))); $NET_LOC[$data['id']] = $netwID; addDocuments('NetworkEquipment', $netwID); addContracts('NetworkEquipment', $netwID); // AJOUT INFOCOMS addInfocoms('NetworkEquipment', $netwID, $ID_entity); // Link with father addNetworkEthernetPort('NetworkEquipment', $netwID, $ID_entity, $i); // Ajout imprimantes reseaux : 1 par loc + connexion d un matos reseau + ajout de cartouches // Add trackings addTracking('NetworkEquipment', $netwID, $ID_entity); $typeID = mt_rand(1,$MAX['type_printers']); $modelID = mt_rand(1,$MAX['model_printers']); $recur = mt_rand(0,1); $printID = $p->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => $recur, 'name' => "printer of loc '$i", 'serial' => Toolbox::getRandomString(10), 'otherserial' => Toolbox::getRandomString(10), 'contact' => "contact '$i", 'contact_num' => "num' $i", 'users_id_tech' => $techID, 'groups_id_tech' => $gtechID, 'have_serial' => mt_rand(0,1), 'have_parallel' => mt_rand(0,1), 'have_usb' => mt_rand(0,1), 'have_wifi' => mt_rand(0,1), 'have_ethernet' => mt_rand(0,1), 'comment' => "comment' $i", 'memory_size' => mt_rand(0,128), 'locations_id' => $i, 'domains_id' => $domainID, 'networks_id' => $networkID, 'printertypes_id' => $typeID, 'printermodels_id' => $modelID, 'manufacturers_id' => mt_rand(1,$MAX['enterprises']), 'is_global' => 1, 'notepad' => "notes printers '$i", 'users_id' => mt_rand($FIRST['users_sadmin'], $LAST['users_admin']), 'groups_id' => mt_rand($FIRST["groups"], $LAST["groups"]), 'states_id' => (mt_rand(0,100)<$percent['state'] ?mt_rand($FIRST['state'],$LAST['state']):0) ))); addDocuments('Printer', $printID); addContracts('Printer', $printID); // Add trackings addTracking('Printer', $printID, $ID_entity); // AJOUT INFOCOMS addInfocoms('Printer', $printID, $ID_entity, $recur); // Add Cartouches // Get compatible cartridge $query = "SELECT `cartridgeitems_id` FROM `glpi_cartridgeitems_printermodels` WHERE `printermodels_id` = '$typeID'"; $result2 = $DB->query($query) or die("PB REQUETE ".$query); if ($DB->numrows($result2)>0) { $ctypeID = $DB->result($result2,0,0) or die (" PB RESULT ".$query); $printed = 0; $oldnb = mt_rand(1,$MAX['cartridges_by_printer']); $date1 = strtotime(mt_rand(2000,$current_year)."-".mt_rand(1,12)."-".mt_rand(1,28)); $date2 = time(); $inter = abs(round(($date2-$date1)/$oldnb)); // Add old cartridges for ($j=0 ; $j<$oldnb ; $j++) { $printed += mt_rand(0,5000); $c->add(array('entities_id' => $ID_entity, 'cartridgeitems_id' => $ctypeID, 'printers_id' => $printID, 'date_in' => date("Y-m-d",$date1), 'date_use' => date("Y-m-d",$date1+$j*$inter), 'date_out' => date("Y-m-d",$date1+($j+1)*$inter), 'pages' => $printed)); } // Add current cartridges $c->add(array('entities_id' => $ID_entity, 'cartridgeitems_id' => $ctypeID, 'printers_id' => $printID, 'date_in' => $date, 'date_use' => date("Y-m-d",$date2))); } $iface = mt_rand(1,$MAX['iface']); // Add networking ports addNetworkEthernetPort('Printer', $printID, $ID_entity, $i); } unset($NET_LOC); $LAST["networking"] = getMaxItem("glpi_networkequipments"); //////////// INVENTORY // glpi_computers $FIRST["computers"] = getMaxItem("glpi_computers")+1; $FIRST["monitors"] = getMaxItem("glpi_monitors")+1; $FIRST["phones"] = getMaxItem("glpi_phones")+1; $FIRST["peripherals"] = getMaxItem("glpi_peripherals")+1; $c = new Computer(); $mon = new Monitor(); $cdevmb = new Item_DeviceMotherBoard(); $cdevproc = new Item_DeviceProcessor(); $cdevmem = new Item_DeviceMemory(); $cdevhd = new Item_DeviceHardDrive(); $cdevnc = new Item_DeviceNetworkCard(); $cdevdr = new Item_DeviceDrive(); $cdevcon = new Item_DeviceControl(); $cdevgc = new Item_DeviceGraphicCard(); $cdevsc = new Item_DeviceSoundCard(); $cdevpci = new Item_DevicePci(); $cdevcase = new Item_DeviceCase(); $cdevps = new Item_DevicePowerSupply(); $cdisk = new ComputerDisk(); $np = new Netpoint(); $ci = new Computer_Item(); $phone = new Phone(); $print = new Printer(); $periph = new Peripheral(); $cart = new Cartridge(); for ($i=0 ; $i<$MAX['computers'] ; $i++) { $loc = mt_rand($FIRST["locations"],$LAST['locations']); $techID = mt_rand($FIRST['users_sadmin'],$LAST['users_admin']); $userID = mt_rand($FIRST['users_normal'],$LAST['users_postonly']); $groupID = mt_rand($FIRST["groups"],$LAST["groups"]); $gtechID = mt_rand($FIRST["techgroups"],$LAST["techgroups"]); $domainID = mt_rand($FIRST['domain'],$LAST['domain']); $networkID = mt_rand(1,$MAX['network']); $compID = $c->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'name' => "computer ' $i-$ID_entity", 'serial' => Toolbox::getRandomString(10), 'otherserial' => Toolbox::getRandomString(10), 'contact' => "contact' $i", 'contact_num' => "num' $i", 'users_id_tech' => $techID, 'groups_id_tech' => $gtechID, 'comment' => "comment' $i", 'operatingsystems_id' => mt_rand(1,$MAX['os']), 'operatingsystemversions_id' => mt_rand(1,$MAX['os_version']), 'operatingsystemservicepacks_id' => mt_rand(1,$MAX['os_sp']), 'os_license_number' => "os sn $i", 'os_licenseid' => "os id $i", 'autoupdatesystems_id' => mt_rand(1,$MAX['os_sp']), 'locations_id' => $loc, 'domains_id' => $domainID, 'networks_id' => $networkID, 'computertypes_id' => mt_rand(1,$MAX['type_computers']), 'computermodels_id' => mt_rand(1,$MAX['model']), 'manufacturers_id' => mt_rand(1,$MAX['manufacturer']), 'is_global' => 1, 'notepad' => "notes computer '$i", 'users_id' => $userID, 'groups_id' => $groupID, 'states_id' => (mt_rand(0,100)<$percent['state'] ?mt_rand($FIRST['state'],$LAST['state']):0), 'uuid' => Toolbox::getRandomString(30) ))); addDocuments('Computer', $compID); addContracts('Computer', $compID); $NET_PORT['Computer'][$compID] = 0; // Add trackings addTracking('Computer', $compID, $ID_entity); // Add reservation addReservation('Computer', $compID, $ID_entity); // AJOUT INFOCOMS addInfocoms('Computer', $compID, $ID_entity); // ADD DEVICE $cdevmb->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']), array('serial' => Toolbox::getRandomString(15))); $max = mt_rand(1,4); $devid = mt_rand(1,$MAX['device']); for($nb = 0; $nb<$max; $nb++) { $cdevproc->addDevices(1, 'Computer', $compID, $devid, array('serial' => Toolbox::getRandomString(15))); } $max = mt_rand(1,4); $devid = mt_rand(1,$MAX['device']); for($nb = 0; $nb<$max; $nb++) { $cdevmem->addDevices(1, 'Computer', $compID, $devid, array('serial' => Toolbox::getRandomString(15))); } $max = mt_rand(1,2); $devid = mt_rand(1,$MAX['device']); for($nb = 0; $nb<$max; $nb++) { $cdevhd->addDevices(1, 'Computer', $compID, $devid, array('serial' => Toolbox::getRandomString(15))); } $cdevnc->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']), array('serial' => Toolbox::getRandomString(15), 'mac' => getNextMAC())); $cdevdr->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']), array('serial' => Toolbox::getRandomString(15))); $cdevcon->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']), array('serial' => Toolbox::getRandomString(15))); $cdevgc->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']), array('serial' => Toolbox::getRandomString(15))); $cdevsc->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']), array('serial' => Toolbox::getRandomString(15))); $max = mt_rand(1,4); for($nb = 0; $nb<$max; $nb++) { $cdevpci->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']), array('serial' => Toolbox::getRandomString(15))); } $cdevcase->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']), array('serial'=> Toolbox::getRandomString(15))); $max = mt_rand(1,2); $devid = mt_rand(1,$MAX['device']); for($nb = 0; $nb<$max; $nb++) { $cdevps->addDevices(1, 'Computer', $compID, $devid, array('serial' => Toolbox::getRandomString(15))); } // insert disk $nb_disk = mt_rand(1,$MAX_DISK); for ($j=1 ; $j<=$nb_disk ; $j++) { $totalsize = mt_rand(10000,1000000); $freesize = mt_rand(0,$totalsize); $cdisk->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'computers_id' => $compID, 'name' => "disk '$j", 'device' => "/dev/disk$j", 'mountpoint' => "/mnt/disk$j", 'filesystems_id' => mt_rand(1,10), 'totalsize' => $totalsize, 'freesize' => $freesize))); } // Add networking ports addNetworkEthernetPort('Computer', $compID, $ID_entity, $loc); // Ajout d'un ecran sur l'ordi $monID = $mon->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'name' => "monitor' $i-$ID_entity", 'serial' => Toolbox::getRandomString(10), 'otherserial' => Toolbox::getRandomString(10), 'contact' => "contact' $i", 'contact_num' => "num' $i", 'users_id_tech' => $techID, 'groups_id_tech' => $gtechID, 'comment' => "comment' $i", 'size' => mt_rand(14,22), 'have_micro' => mt_rand(0,1), 'have_speaker' => mt_rand(0,1), 'have_subd' => mt_rand(0,1), 'have_bnc' => mt_rand(0,1), 'have_dvi' => mt_rand(0,1), 'have_pivot' => mt_rand(0,1), 'have_hdmi' => mt_rand(0,1), 'have_displayport' => mt_rand(0,1), 'locations_id' => $loc, 'monitortypes_id' => mt_rand(1,$MAX['type_monitors']), 'monitormodels_id' => mt_rand(1,$MAX['model_monitors']), 'manufacturers_id' => mt_rand(1,$MAX['manufacturer']), 'notepad' => "notes monitor' $i", 'users_id' => $userID, 'groups_id' => $groupID, 'states_id' => (mt_rand(0,100)<$percent['state'] ?mt_rand($FIRST['state'],$LAST['state']):0) ))); addDocuments('Monitor', $monID); addContracts('Monitor', $monID); // Add trackings addTracking('Monitor', $monID, $ID_entity); // AJOUT INFOCOMS addInfocoms('Monitor', $monID, $ID_entity); $ci->add(array('itemtype' => 'Monitor', 'items_id' => $monID, 'computers_id' => $compID, )); // Ajout d'un telephhone avec l'ordi $telID = $phone->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'name' => "phone' $i-$ID_entity", 'serial' => Toolbox::getRandomString(10), 'otherserial' => Toolbox::getRandomString(10), 'contact' => "contact' $i", 'contact_num' => "num' $i", 'users_id_tech' => $techID, 'groups_id_tech' => $gtechID, 'comment' => "comment' $i", 'firmware' => Toolbox::getRandomString(10), 'brand' => "brand' $i", 'phonepowersupplies_id' => mt_rand(0,$MAX['phone_power']), 'number_line' => Toolbox::getRandomString(10), 'have_headset' => mt_rand(0,1), 'have_hp' => mt_rand(0,1), 'locations_id' => $loc, 'phonetypes_id' => mt_rand(1,$MAX['type_phones']), 'phonemodels_id' => mt_rand(1,$MAX['model_phones']), 'manufacturers_id' => mt_rand(1,$MAX['manufacturer']), 'notepad' => "notes phone' $i", 'users_id' => $userID, 'groups_id' => $groupID, 'states_id' => (mt_rand(0,100)<$percent['state'] ?mt_rand($FIRST['state'],$LAST['state']):0) ))); addDocuments('Phone', $telID); addContracts('Phone', $telID); // Add trackings addTracking('Phone', $telID, $ID_entity); // AJOUT INFOCOMS addInfocoms('Phone', $telID, $ID_entity); $ci->add(array('itemtype' => 'Phone', 'items_id' => $telID, 'computers_id' => $compID)); // Ajout des periphs externes en connection directe while (mt_rand(0,100)<$percent['peripherals']) { $periphID = $periph->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'name' => "periph of comp' $i-$ID_entity", 'serial' => Toolbox::getRandomString(10), 'otherserial' => Toolbox::getRandomString(10), 'contact' => "contact' $i", 'contact_num' => "num' $i", 'users_id_tech' => $techID, 'groups_id_tech' => $gtechID, 'comment' => "comment' $i", 'brand' => "brand' $i", 'locations_id' => $loc, 'phonetypes_id' => mt_rand(1,$MAX['type_peripherals']), 'phonemodels_id' => mt_rand(1,$MAX['model_peripherals']), 'manufacturers_id' => mt_rand(1,$MAX['manufacturer']), 'notepad' => "notes peripheral' $i", 'users_id' => $userID, 'groups_id' => $groupID, 'states_id' => (mt_rand(0,100)<$percent['state'] ?mt_rand($FIRST['state'],$LAST['state']):0) ))); addDocuments('Peripheral', $periphID); addContracts('Peripheral', $periphID); // Add trackings addTracking('Peripheral', $periphID, $ID_entity); // Add connection $ci->add(array('itemtype' => 'Peripheral', 'items_id' => $periphID, 'computers_id' => $compID)); } // Ajout d'une imprimante connection directe pour X% des computers + ajout de cartouches if (mt_rand(0,100)<=$percent['printer']) { // Add printer $typeID = mt_rand(1,$MAX['type_printers']); $modelID = mt_rand(1,$MAX['model_printers']); $printID = $p->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'name' => "printer of comp' $i-$ID_entity", 'serial' => Toolbox::getRandomString(10), 'otherserial' => Toolbox::getRandomString(10), 'contact' => "contact' $i", 'contact_num' => "num' $i", 'users_id_tech' => $techID, 'groups_id_tech' => $gtechID, 'have_serial' => mt_rand(0,1), 'have_parallel' => mt_rand(0,1), 'have_usb' => mt_rand(0,1), 'have_wifi' => mt_rand(0,1), 'have_ethernet' => mt_rand(0,1), 'comment' => "comment' $i", 'memory_size' => mt_rand(0,128), 'locations_id' => $loc, 'domains_id' => $domainID, 'networks_id' => $networkID, 'printertypes_id' => $typeID, 'printermodels_id' => $modelID, 'manufacturers_id' => mt_rand(1,$MAX['manufacturer']), 'notepad' => "notes printers '$i", 'users_id' => mt_rand($FIRST['users_postonly'], $LAST['users_postonly']), 'groups_id' => mt_rand($FIRST["groups"], $LAST["groups"]), 'states_id' => (mt_rand(0,100)<$percent['state'] ?mt_rand($FIRST['state'],$LAST['state']):0) ))); addDocuments('Printer', $printID); addContracts('Printer', $printID); // Add trackings addTracking('Printer', $printID, $ID_entity); // Add connection $ci->add(array('itemtype' => 'Printer', 'items_id' => $printID, 'computers_id' => $compID)); // AJOUT INFOCOMS addInfocoms('Printer', $printID, $ID_entity); // Add Cartouches // Get compatible cartridge $query = "SELECT `cartridgeitems_id` FROM `glpi_cartridgeitems_printermodels` WHERE `printermodels_id` = '$typeID'"; $result = $DB->query($query) or die("PB REQUETE ".$query); if ($DB->numrows($result)>0) { $ctypeID = $DB->result($result,0,0) or die (" PB RESULT ".$query); $printed = 0; $oldnb = mt_rand(1,$MAX['cartridges_by_printer']); $date1 = strtotime(mt_rand(2000,$current_year)."-".mt_rand(1,12)."-".mt_rand(1,28)); $date2 = time(); $inter = round(($date2-$date1)/$oldnb); // Add old cartridges for ($j=0 ; $j<$oldnb ; $j++) { $printed += mt_rand(0,5000); $cart->add(array('entities_id' => $ID_entity, 'cartridgeitems_id' => $ctypeID, 'printers_id' => $printID, 'date_in' => date("Y-m-d",$date1), 'date_use' => date("Y-m-d",$date1+$j*$inter), 'date_out' => date("Y-m-d",$date1+($j+1)*$inter), 'pages' => $printed)); } // Add current cartridges $cart->add(array('entities_id' => $ID_entity, 'cartridgeitems_id' => $ctypeID, 'printers_id' => $printID, 'date_in' => date("Y-m-d",$date1), 'date_use' => date("Y-m-d",$date2))); } } } $LAST["computers"] = getMaxItem("glpi_computers"); $LAST["monitors"] = getMaxItem("glpi_monitors"); $LAST["phones"] = getMaxItem("glpi_phones"); // Add global peripherals $periph = new Peripheral(); $ci = new Computer_Item(); for ($i=0 ; $i<$MAX['global_peripherals'] ; $i++) { $techID = mt_rand($FIRST['users_sadmin'],$LAST['users_admin']); $gtechID = mt_rand($FIRST["techgroups"],$LAST["techgroups"]); $periphID = $periph->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'name' => "periph '$i-$ID_entity", 'serial' => Toolbox::getRandomString(10), 'otherserial' => Toolbox::getRandomString(10), 'contact' => "contact' $i", 'contact_num' => "num' $i", 'users_id_tech' => $techID, 'groups_id_tech' => $gtechID, 'comment' => "comment' $i", 'brand' => "brand' $i", 'locations_id' => $loc, 'phonetypes_id' => mt_rand(1,$MAX['type_peripherals']), 'phonemodels_id' => mt_rand(1,$MAX['model_peripherals']), 'manufacturers_id' => mt_rand(1,$MAX['manufacturer']), 'is_global' => 1, 'notepad' => "notes peripheral' $i", 'users_id' => mt_rand($FIRST['users_normal'], $LAST['users_normal']), 'groups_id' => mt_rand($FIRST["groups"], $LAST["groups"]), 'states_id' => (mt_rand(0,100)<$percent['state'] ?mt_rand($FIRST['state'],$LAST['state']):0) ))); addDocuments('Peripheral', $periphID); addContracts('Peripheral', $periphID); // Add trackings addTracking('Peripheral', $periphID, $ID_entity); // Add reservation addReservation('Peripheral', $periphID, $ID_entity); // AJOUT INFOCOMS addInfocoms('Peripheral', $periphID, $ID_entity); // Add connections $val = mt_rand(1,$MAX['connect_for_peripherals']); for ($j=1 ; $j<$val ; $j++) { $ci->add(array('itemtype' => 'Peripheral', 'items_id' => $periphID, 'computers_id' => mt_rand($FIRST["computers"],$LAST['computers']))); } } $LAST["peripherals"] = getMaxItem("glpi_peripherals"); $FIRST["software"] = getMaxItem("glpi_softwares")+1; // Ajout logiciels + licences associees a divers PCs $items = array(array("Open'Office", "1.1.4", "2.0", "2.0.1"), array("Microsoft Office", "95", "97", "XP", "2000", "2003", "2007"), array("Acrobat Reader", "6.0", "7.0", "7.04"), array("Gimp", "2.0", "2.2"), array("InkScape", "0.4")); $soft = new Software(); $softvers = new SoftwareVersion(); $softlic = new SoftwareLicense(); $csv = new Computer_SoftwareVersion(); $csl = new Computer_SoftwareLicense(); for ($i=0 ; $i<$MAX['software'] ; $i++) { if (isset($items[$i])) { $name = $items[$i][0]; } else { $name = "software '$i"; } $loc = mt_rand(1,$MAX['locations']); $techID = mt_rand($FIRST['users_sadmin'],$LAST['users_admin']); $gtechID = mt_rand($FIRST["techgroups"],$LAST["techgroups"]); $recursive = mt_rand(0,1); $softID = $soft->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => $recursive, 'name' => $name, 'comment' => "comment '$i", 'locations_id' => $loc, 'users_id_tech' => $techID, 'groups_id_tech' => $gtechID, 'manufacturers_id' => mt_rand(1,$MAX['manufacturer']), 'notepad' => "notes software '$i", 'users_id' => mt_rand($FIRST['users_admin'], $LAST['users_admin']), 'groups_id' => mt_rand($FIRST["groups"], $LAST["groups"]), 'is_helpdesk_visible' => 1, 'softwarecategories_id' => mt_rand(1,$MAX['softwarecategory']) ))); addDocuments('Software', $softID); addContracts('Software', $softID); // Add trackings addTracking('Software', $softID, $ID_entity); // AJOUT INFOCOMS addInfocoms('Software', $softID, $ID_entity); // Add versions $FIRST["version"] = getMaxItem("glpi_softwareversions")+1; if (isset($items[$i])) { $val2 = count($items[$i]); } else { $val2 = mt_rand(1,$MAX['softwareversions']+1); } for ($j=1 ; $j<=$val2 ; $j++) { if (isset($items[$i])) { $version = $items[$i][mt_rand(1,count($items[$i])-1)]; } else { $version = "$j.0"; } $os = mt_rand(1,$MAX['os']); $versID = $softvers->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => $recursive, 'softwares_id' => $softID, 'name' => $version, 'comment' => "comment '$version", 'states_id' => (mt_rand(0,100)<$percent['state'] ?mt_rand($FIRST['state'],$LAST['state']):0), 'operatingsystems_id' => $os))); $val3 = min($LAST["computers"]-$FIRST['computers'], mt_rand(1,$MAX['softwareinstall'])); $comp_id = mt_rand($FIRST["computers"], $LAST['computers']); for ($k=0 ; $k<$val3 ; $k++) { $comp_id++; if ($comp_id>$LAST["computers"]) { $comp_id = $FIRST["computers"]; } $csv->add(array('computers_id' => $comp_id, 'softwareversions_id' => $versID)); } } $LAST["version"] = getMaxItem("glpi_softwareversions"); // Add licenses $val2 = mt_rand(1,$MAX['softwarelicenses']); for ($j=0 ; $j<$val2 ; $j++) { $softwareversions_id_buy = mt_rand($FIRST["version"],$LAST["version"]); $softwareversions_id_use = mt_rand($softwareversions_id_buy,$LAST["version"]); $nbused = min($LAST["computers"]-$FIRST['computers'], mt_rand(1,$MAX['softwareinstall'])); $licID = $softlic->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => $recursive, 'softwares_id' => $softID, 'number' => $nbused, 'softwarelicensetypes_id' => mt_rand(1,$MAX['licensetype']), 'name' => "license '$j", 'serial' => "serial $j", 'otherserial' => "otherserial $j", 'comment' => "comment license '$j", 'softwareversions_id_buy' => $softwareversions_id_buy, 'softwareversions_id_use' => $softwareversions_id_use))); $comp_id = mt_rand($FIRST["computers"], $LAST['computers']); for ($k=0 ; $k<$nbused ; $k++) { $comp_id++; if ($comp_id>$LAST["computers"]) { $comp_id = $FIRST["computers"]; } $csl->add(array('computers_id' => $comp_id, 'softwarelicenses_id' => $licID)); } } } $LAST["software"] = getMaxItem("glpi_softwares"); }
/** * Generic Search and list function * * Build the query, make the search and list items after a search. * * @param $itemtype item type * @param $params array of parameters may include field, contains, searchtype, sort, order, * start, deleted, link, link2, contains2, field2, itemtype2, searchtype2 * * @return Nothing (display) **/ static function showList($itemtype, array $params) { global $DB, $CFG_GLPI; // Instanciate an object to access method $item = NULL; if ($itemtype != 'AllAssets') { $item = getItemForItemtype($itemtype); } // Default values of parameters $p['link'] = array(); // $p['field'] = array(); // $p['contains'] = array(); // $p['searchtype'] = array(); // $p['sort'] = '1'; // $p['order'] = 'ASC'; // $p['start'] = 0; // $p['is_deleted'] = 0; $p['export_all'] = 0; $p['link2'] = ''; // $p['contains2'] = ''; // $p['field2'] = ''; // $p['itemtype2'] = ''; $p['searchtype2'] = ''; foreach ($params as $key => $val) { $p[$key] = $val; } if ($p['export_all']) { $p['start'] = 0; } if (in_array('all', $p['field']) && !$CFG_GLPI['allow_search_all']) { Html::displayRightError(); } if (in_array('view', $p['field']) && !$CFG_GLPI['allow_search_view']) { Html::displayRightError(); } // Manage defautll seachtype value : for bookmark compatibility if (count($p['contains'])) { foreach ($p['contains'] as $key => $val) { if (!isset($p['searchtype'][$key])) { $p['searchtype'][$key] = 'contains'; } } } if (is_array($p['contains2']) && count($p['contains2'])) { foreach ($p['contains2'] as $key => $val) { if (!isset($p['searchtype2'][$key])) { $p['searchtype2'][$key] = 'contains'; } } } $target = Toolbox::getItemTypeSearchURL($itemtype); $limitsearchopt = self::getCleanedOptions($itemtype); $blacklist_tables = array(); if (isset($CFG_GLPI['union_search_type'][$itemtype])) { $itemtable = $CFG_GLPI['union_search_type'][$itemtype]; $blacklist_tables[] = getTableForItemType($itemtype); } else { $itemtable = getTableForItemType($itemtype); } $LIST_LIMIT = $_SESSION['glpilist_limit']; // Set display type for export if define $output_type = self::HTML_OUTPUT; if (isset($_GET['display_type'])) { $output_type = $_GET['display_type']; // Limit to 10 element if ($_GET['display_type'] == self::GLOBAL_SEARCH) { $LIST_LIMIT = self::GLOBAL_DISPLAY_COUNT; } } // hack for AllAssets if (isset($CFG_GLPI['union_search_type'][$itemtype])) { $entity_restrict = true; } else { $entity_restrict = $item->isEntityAssign(); } self::$output_type = $output_type; $metanames = array(); // Get the items to display $toview = self::addDefaultToView($itemtype); // Add items to display depending of personal prefs $displaypref = DisplayPreference::getForTypeUser($itemtype, Session::getLoginUserID()); if (count($displaypref)) { foreach ($displaypref as $val) { array_push($toview, $val); } } // Add searched items if (count($p['field']) > 0) { foreach ($p['field'] as $key => $val) { if (!in_array($val, $toview) && $val != 'all' && $val != 'view') { array_push($toview, $val); } } } // Add order item if (!in_array($p['sort'], $toview)) { array_push($toview, $p['sort']); } // Special case for Ticket : put ID in front if ($itemtype == 'Ticket') { array_unshift($toview, 2); } // Clean toview array $toview = array_unique($toview); foreach ($toview as $key => $val) { if (!isset($limitsearchopt[$val])) { unset($toview[$key]); } } $toview_count = count($toview); // Construct the request //// 1 - SELECT // request currentuser for SQL supervision, not displayed $SELECT = "SELECT '" . Toolbox::addslashes_deep($_SESSION['glpiname']) . "' AS currentuser,\n " . self::addDefaultSelect($itemtype); // Add select for all toview item foreach ($toview as $key => $val) { $SELECT .= self::addSelect($itemtype, $val, $key, 0); } //// 2 - FROM AND LEFT JOIN // Set reference table $FROM = " FROM `{$itemtable}`"; // Init already linked tables array in order not to link a table several times $already_link_tables = array(); // Put reference table array_push($already_link_tables, $itemtable); // Add default join $COMMONLEFTJOIN = self::addDefaultJoin($itemtype, $itemtable, $already_link_tables); $FROM .= $COMMONLEFTJOIN; $searchopt = array(); $searchopt[$itemtype] =& self::getOptions($itemtype); // Add all table for toview items foreach ($toview as $key => $val) { if (!in_array($searchopt[$itemtype][$val]["table"], $blacklist_tables)) { $FROM .= self::addLeftJoin($itemtype, $itemtable, $already_link_tables, $searchopt[$itemtype][$val]["table"], $searchopt[$itemtype][$val]["linkfield"], 0, 0, $searchopt[$itemtype][$val]["joinparams"]); } } // Search all case : if (in_array("all", $p['field'])) { foreach ($searchopt[$itemtype] as $key => $val) { // Do not search on Group Name if (is_array($val)) { if (!in_array($searchopt[$itemtype][$key]["table"], $blacklist_tables)) { $FROM .= self::addLeftJoin($itemtype, $itemtable, $already_link_tables, $searchopt[$itemtype][$key]["table"], $searchopt[$itemtype][$key]["linkfield"], 0, 0, $searchopt[$itemtype][$key]["joinparams"]); } } } } //// 3 - WHERE // default string $COMMONWHERE = self::addDefaultWhere($itemtype); $first = empty($COMMONWHERE); // Add deleted if item have it if ($item && $item->maybeDeleted()) { $LINK = " AND "; if ($first) { $LINK = " "; $first = false; } $COMMONWHERE .= $LINK . "`{$itemtable}`.`is_deleted` = '" . $p['is_deleted'] . "' "; } // Remove template items if ($item && $item->maybeTemplate()) { $LINK = " AND "; if ($first) { $LINK = " "; $first = false; } $COMMONWHERE .= $LINK . "`{$itemtable}`.`is_template` = '0' "; } // Add Restrict to current entities if ($entity_restrict) { $LINK = " AND "; if ($first) { $LINK = " "; $first = false; } if ($itemtype == 'Entity') { $COMMONWHERE .= getEntitiesRestrictRequest($LINK, $itemtable, 'id', '', true); } else { if (isset($CFG_GLPI["union_search_type"][$itemtype])) { // Will be replace below in Union/Recursivity Hack $COMMONWHERE .= $LINK . " ENTITYRESTRICT "; } else { $COMMONWHERE .= getEntitiesRestrictRequest($LINK, $itemtable, '', '', $item->maybeRecursive()); } } } $WHERE = ""; $HAVING = ""; // Add search conditions // If there is search items if ($_SESSION["glpisearchcount"][$itemtype] > 0 && count($p['contains']) > 0) { for ($key = 0; $key < $_SESSION["glpisearchcount"][$itemtype]; $key++) { // if real search (strlen >0) and not all and view search if (isset($p['contains'][$key]) && strlen($p['contains'][$key]) > 0) { // common search if ($p['field'][$key] != "all" && $p['field'][$key] != "view") { $LINK = " "; $NOT = 0; $tmplink = ""; if (is_array($p['link']) && isset($p['link'][$key])) { if (strstr($p['link'][$key], "NOT")) { $tmplink = " " . str_replace(" NOT", "", $p['link'][$key]); $NOT = 1; } else { $tmplink = " " . $p['link'][$key]; } } else { $tmplink = " AND "; } if (isset($searchopt[$itemtype][$p['field'][$key]]["usehaving"])) { // Manage Link if not first item if (!empty($HAVING)) { $LINK = $tmplink; } // Find key $item_num = array_search($p['field'][$key], $toview); $HAVING .= self::addHaving($LINK, $NOT, $itemtype, $p['field'][$key], $p['searchtype'][$key], $p['contains'][$key], 0, $item_num); } else { // Manage Link if not first item if (!empty($WHERE)) { $LINK = $tmplink; } $WHERE .= self::addWhere($LINK, $NOT, $itemtype, $p['field'][$key], $p['searchtype'][$key], $p['contains'][$key]); } // view and all search } else { $LINK = " OR "; $NOT = 0; $globallink = " AND "; if (is_array($p['link']) && isset($p['link'][$key])) { switch ($p['link'][$key]) { case "AND": $LINK = " OR "; $globallink = " AND "; break; case "AND NOT": $LINK = " AND "; $NOT = 1; $globallink = " AND "; break; case "OR": $LINK = " OR "; $globallink = " OR "; break; case "OR NOT": $LINK = " AND "; $NOT = 1; $globallink = " OR "; break; } } else { $tmplink = " AND "; } // Manage Link if not first item if (!empty($WHERE)) { $WHERE .= $globallink; } $WHERE .= " ( "; $first2 = true; $items = array(); if ($p['field'][$key] == "all") { $items = $searchopt[$itemtype]; } else { // toview case : populate toview foreach ($toview as $key2 => $val2) { $items[$val2] = $searchopt[$itemtype][$val2]; } } foreach ($items as $key2 => $val2) { if (isset($val2['nosearch']) && $val2['nosearch']) { continue; } if (is_array($val2)) { // Add Where clause if not to be done in HAVING CLAUSE if (!isset($val2["usehaving"])) { $tmplink = $LINK; if ($first2) { $tmplink = " "; $first2 = false; } $WHERE .= self::addWhere($tmplink, $NOT, $itemtype, $key2, $p['searchtype'][$key], $p['contains'][$key]); } } } $WHERE .= " ) "; } } } } //// 4 - ORDER $ORDER = " ORDER BY `id` "; foreach ($toview as $key => $val) { if ($p['sort'] == $val) { $ORDER = self::addOrderBy($itemtype, $p['sort'], $p['order'], $key); } } //// 5 - META SEARCH // Preprocessing if ($_SESSION["glpisearchcount2"][$itemtype] > 0 && is_array($p['itemtype2'])) { // a - SELECT for ($i = 0; $i < $_SESSION["glpisearchcount2"][$itemtype]; $i++) { if (isset($p['itemtype2'][$i]) && !empty($p['itemtype2'][$i]) && isset($p['contains2'][$i]) && strlen($p['contains2'][$i]) > 0) { $SELECT .= self::addSelect($p['itemtype2'][$i], $p['field2'][$i], $i, 1, $p['itemtype2'][$i]); } } // b - ADD LEFT JOIN // Already link meta table in order not to linked a table several times $already_link_tables2 = array(); // Link reference tables for ($i = 0; $i < $_SESSION["glpisearchcount2"][$itemtype]; $i++) { if (isset($p['itemtype2'][$i]) && !empty($p['itemtype2'][$i]) && isset($p['contains2'][$i]) && strlen($p['contains2'][$i]) > 0) { if (!in_array(getTableForItemType($p['itemtype2'][$i]), $already_link_tables2)) { $FROM .= self::addMetaLeftJoin($itemtype, $p['itemtype2'][$i], $already_link_tables2, $p['contains2'][$i] == "NULL" || strstr($p['link2'][$i], "NOT")); } } } // Link items tables for ($i = 0; $i < $_SESSION["glpisearchcount2"][$itemtype]; $i++) { if (isset($p['itemtype2'][$i]) && !empty($p['itemtype2'][$i]) && isset($p['contains2'][$i]) && strlen($p['contains2'][$i]) > 0) { if (!isset($searchopt[$p['itemtype2'][$i]])) { $searchopt[$p['itemtype2'][$i]] =& self::getOptions($p['itemtype2'][$i]); } if (!in_array($searchopt[$p['itemtype2'][$i]][$p['field2'][$i]]["table"] . "_" . $p['itemtype2'][$i], $already_link_tables2)) { $FROM .= self::addLeftJoin($p['itemtype2'][$i], getTableForItemType($p['itemtype2'][$i]), $already_link_tables2, $searchopt[$p['itemtype2'][$i]][$p['field2'][$i]]["table"], $searchopt[$p['itemtype2'][$i]][$p['field2'][$i]]["linkfield"], 1, $p['itemtype2'][$i], $searchopt[$p['itemtype2'][$i]][$p['field2'][$i]]["joinparams"]); } } } } //// 6 - Add item ID // Add ID to the select if (!empty($itemtable)) { $SELECT .= "`{$itemtable}`.`id` AS id "; } //// 7 - Manage GROUP BY $GROUPBY = ""; // Meta Search / Search All / Count tickets if ($_SESSION["glpisearchcount2"][$itemtype] > 0 || !empty($HAVING) || in_array('all', $p['field'])) { $GROUPBY = " GROUP BY `{$itemtable}`.`id`"; } if (empty($GROUPBY)) { foreach ($toview as $key2 => $val2) { if (!empty($GROUPBY)) { break; } if (isset($searchopt[$itemtype][$val2]["forcegroupby"])) { $GROUPBY = " GROUP BY `{$itemtable}`.`id`"; } } } // Specific search for others item linked (META search) if (is_array($p['itemtype2'])) { for ($key = 0; $key < $_SESSION["glpisearchcount2"][$itemtype]; $key++) { if (isset($p['itemtype2'][$key]) && !empty($p['itemtype2'][$key]) && isset($p['contains2'][$key]) && strlen($p['contains2'][$key]) > 0) { $LINK = ""; // For AND NOT statement need to take into account all the group by items if (strstr($p['link2'][$key], "AND NOT") || isset($searchopt[$p['itemtype2'][$key]][$p['field2'][$key]]["usehaving"])) { $NOT = 0; if (strstr($p['link2'][$key], "NOT")) { $tmplink = " " . str_replace(" NOT", "", $p['link2'][$key]); $NOT = 1; } else { $tmplink = " " . $p['link2'][$key]; } if (!empty($HAVING)) { $LINK = $tmplink; } $HAVING .= self::addHaving($LINK, $NOT, $p['itemtype2'][$key], $p['field2'][$key], $p['searchtype2'][$key], $p['contains2'][$key], 1, $key); } else { // Meta Where Search $LINK = " "; $NOT = 0; // Manage Link if not first item if (is_array($p['link2']) && isset($p['link2'][$key]) && strstr($p['link2'][$key], "NOT")) { $tmplink = " " . str_replace(" NOT", "", $p['link2'][$key]); $NOT = 1; } else { if (is_array($p['link2']) && isset($p['link2'][$key])) { $tmplink = " " . $p['link2'][$key]; } else { $tmplink = " AND "; } } if (!empty($WHERE)) { $LINK = $tmplink; } $WHERE .= self::addWhere($LINK, $NOT, $p['itemtype2'][$key], $p['field2'][$key], $p['searchtype2'][$key], $p['contains2'][$key], 1); } } } } // Use a ReadOnly connection if available and configured to be used $DBread = DBConnection::getReadConnection(); // If no research limit research to display item and compute number of item using simple request $nosearch = true; for ($i = 0; $i < $_SESSION["glpisearchcount"][$itemtype]; $i++) { if (isset($p['contains'][$i]) && strlen($p['contains'][$i]) > 0) { $nosearch = false; } } if ($_SESSION["glpisearchcount2"][$itemtype] > 0) { $nosearch = false; } $LIMIT = ""; $numrows = 0; //No search : count number of items using a simple count(ID) request and LIMIT search if ($nosearch) { $LIMIT = " LIMIT " . $p['start'] . ", " . $LIST_LIMIT; // Force group by for all the type -> need to count only on table ID if (!isset($searchopt[$itemtype][1]['forcegroupby'])) { $count = "count(*)"; } else { $count = "count(DISTINCT `{$itemtable}`.`id`)"; } // request currentuser for SQL supervision, not displayed $query_num = "SELECT {$count},\n '" . Toolbox::addslashes_deep($_SESSION['glpiname']) . "' AS currentuser\n FROM `{$itemtable}`" . $COMMONLEFTJOIN; $first = true; if (!empty($COMMONWHERE)) { $LINK = " AND "; if ($first) { $LINK = " WHERE "; $first = false; } $query_num .= $LINK . $COMMONWHERE; } // Union Search : if (isset($CFG_GLPI["union_search_type"][$itemtype])) { $tmpquery = $query_num; $numrows = 0; foreach ($CFG_GLPI[$CFG_GLPI["union_search_type"][$itemtype]] as $ctype) { $ctable = getTableForItemType($ctype); if (($citem = getItemForItemtype($ctype)) && $citem->canView()) { // State case if ($itemtype == 'AllAssets') { $query_num = str_replace($CFG_GLPI["union_search_type"][$itemtype], $ctable, $tmpquery); $query_num = str_replace($itemtype, $ctype, $query_num); $query_num .= " AND `{$ctable}`.`id` IS NOT NULL "; // Add deleted if item have it if ($citem && $citem->maybeDeleted()) { $query_num .= " AND `{$ctable}`.`is_deleted` = '0' "; } // Remove template items if ($citem && $citem->maybeTemplate()) { $query_num .= " AND `{$ctable}`.`is_template` = '0' "; } } else { // Ref table case $reftable = getTableForItemType($itemtype); if ($item && $item->maybeDeleted()) { $tmpquery = str_replace("`" . $CFG_GLPI["union_search_type"][$itemtype] . "`.`is_deleted`", "`{$reftable}`.`is_deleted`", $tmpquery); } $replace = "FROM `{$reftable}`\n INNER JOIN `{$ctable}`\n ON (`{$reftable}`.`items_id` =`{$ctable}`.`id`\n AND `{$reftable}`.`itemtype` = '{$ctype}')"; $query_num = str_replace("FROM `" . $CFG_GLPI["union_search_type"][$itemtype] . "`", $replace, $tmpquery); $query_num = str_replace($CFG_GLPI["union_search_type"][$itemtype], $ctable, $query_num); } $query_num = str_replace("ENTITYRESTRICT", getEntitiesRestrictRequest('', $ctable, '', '', $citem->maybeRecursive()), $query_num); $result_num = $DBread->query($query_num); $numrows += $DBread->result($result_num, 0, 0); } } } else { $result_num = $DBread->query($query_num); $numrows = $DBread->result($result_num, 0, 0); } } // If export_all reset LIMIT condition if ($p['export_all']) { $LIMIT = ""; } if (!empty($WHERE) || !empty($COMMONWHERE)) { if (!empty($COMMONWHERE)) { $WHERE = ' WHERE ' . $COMMONWHERE . (!empty($WHERE) ? ' AND ( ' . $WHERE . ' )' : ''); } else { $WHERE = ' WHERE ' . $WHERE . ' '; } $first = false; } if (!empty($HAVING)) { $HAVING = ' HAVING ' . $HAVING; } // Create QUERY if (isset($CFG_GLPI["union_search_type"][$itemtype])) { $first = true; $QUERY = ""; foreach ($CFG_GLPI[$CFG_GLPI["union_search_type"][$itemtype]] as $ctype) { $ctable = getTableForItemType($ctype); if (($citem = getItemForItemtype($ctype)) && $citem->canView()) { if ($first) { $first = false; } else { $QUERY .= " UNION "; } $tmpquery = ""; // AllAssets case if ($itemtype == 'AllAssets') { $tmpquery = $SELECT . ", '{$ctype}' AS TYPE " . $FROM . $WHERE; if ($itemtype == 'AllAssets') { $tmpquery .= " AND `{$ctable}`.`id` IS NOT NULL "; } // Add deleted if item have it if ($citem && $citem->maybeDeleted()) { $tmpquery .= " AND `{$ctable}`.`is_deleted` = '0' "; } // Remove template items if ($citem && $citem->maybeTemplate()) { $tmpquery .= " AND `{$ctable}`.`is_template` = '0' "; } $tmpquery .= $GROUPBY . $HAVING; $tmpquery = str_replace($CFG_GLPI["union_search_type"][$itemtype], $ctable, $tmpquery); $tmpquery = str_replace($itemtype, $ctype, $tmpquery); } else { // Ref table case $reftable = getTableForItemType($itemtype); $tmpquery = $SELECT . ", '{$ctype}' AS TYPE,\n `{$reftable}`.`id` AS refID, " . "\n `{$ctable}`.`entities_id` AS ENTITY " . $FROM . $WHERE; if ($item->maybeDeleted()) { $tmpquery = str_replace("`" . $CFG_GLPI["union_search_type"][$itemtype] . "`.`is_deleted`", "`{$reftable}`.`is_deleted`", $tmpquery); } $replace = "FROM `{$reftable}`" . "\n INNER JOIN `{$ctable}`" . "\n ON (`{$reftable}`.`items_id`=`{$ctable}`.`id`" . "\n AND `{$reftable}`.`itemtype` = '{$ctype}')"; $tmpquery = str_replace("FROM `" . $CFG_GLPI["union_search_type"][$itemtype] . "`", $replace, $tmpquery); $tmpquery = str_replace($CFG_GLPI["union_search_type"][$itemtype], $ctable, $tmpquery); } $tmpquery = str_replace("ENTITYRESTRICT", getEntitiesRestrictRequest('', $ctable, '', '', $citem->maybeRecursive()), $tmpquery); // SOFTWARE HACK if ($ctype == 'Software') { $tmpquery = str_replace("glpi_softwares.serial", "''", $tmpquery); $tmpquery = str_replace("glpi_softwares.otherserial", "''", $tmpquery); } $QUERY .= $tmpquery; } } if (empty($QUERY)) { echo self::showError($output_type); return; } $QUERY .= str_replace($CFG_GLPI["union_search_type"][$itemtype] . ".", "", $ORDER) . $LIMIT; } else { $QUERY = $SELECT . $FROM . $WHERE . $GROUPBY . $HAVING . $ORDER . $LIMIT; } $DBread->query("SET SESSION group_concat_max_len = 4096;"); $result = $DBread->query($QUERY); /// Check group concat limit : if warning : increase limit if ($result2 = $DBread->query('SHOW WARNINGS')) { if ($DBread->numrows($result2) > 0) { $data = $DBread->fetch_assoc($result2); if ($data['Code'] == 1260) { $DBread->query("SET SESSION group_concat_max_len = 4194304;"); $result = $DBread->query($QUERY); } } } // Get it from database and DISPLAY if ($result) { // if real search or complete export : get numrows from request if (!$nosearch || $p['export_all']) { $numrows = $DBread->numrows($result); } // Contruct Pager parameters $globallinkto = self::getArrayUrlLink("field", $p['field']) . self::getArrayUrlLink("link", $p['link']) . self::getArrayUrlLink("contains", $p['contains']) . self::getArrayUrlLink("searchtype", $p['searchtype']) . self::getArrayUrlLink("field2", $p['field2']) . self::getArrayUrlLink("contains2", $p['contains2']) . self::getArrayUrlLink("itemtype2", $p['itemtype2']) . self::getArrayUrlLink("searchtype2", $p['searchtype2']) . self::getArrayUrlLink("link2", $p['link2']); $parameters = "sort=" . $p['sort'] . "&order=" . $p['order'] . $globallinkto; // Not more used : clean pages : try to comment it /* $tmp=explode('?',$target,2); if (count($tmp)>1) { $target = $tmp[0]; $parameters = $tmp[1].'&'.$parameters; } */ if ($output_type == self::GLOBAL_SEARCH) { if ($item = getItemForItemtype($itemtype)) { echo "<div class='center'><h2>" . $item->getTypeName(); // More items if ($numrows > $p['start'] + self::GLOBAL_DISPLAY_COUNT) { echo " <a href='{$target}?{$parameters}'>" . __('All') . "</a>"; } echo "</h2></div>\n"; } else { return false; } } // If the begin of the view is before the number of items if ($p['start'] < $numrows) { // Display pager only for HTML if ($output_type == self::HTML_OUTPUT) { // For plugin add new parameter if available if ($plug = isPluginItemType($itemtype)) { $function = 'plugin_' . $plug['plugin'] . '_addParamFordynamicReport'; if (function_exists($function)) { $out = $function($itemtype); if (is_array($out) && count($out)) { foreach ($out as $key => $val) { if (is_array($val)) { $parameters .= self::getArrayUrlLink($key, $val); } else { $parameters .= "&{$key}={$val}"; } } } } } $search_config = ""; if (Session::haveRight("search_config", DisplayPreference::GENERAL)) { //|| Session::haveRight("search_config_global",CREATE)) { // Ajax::createModalWindow('searchconfig_window', // $CFG_GLPI['root_doc']."/ajax/searchconfig.php?itemtype=$itemtype", // array('title' => __('Select default items to show'), // 'width' => '1000')); // $tmp = " class='pointer' onClick=\"searchconfig_window.show()\""; $tmp = " class='pointer' onClick=\"var w = window.open('" . $CFG_GLPI["root_doc"] . "/front/popup.php?popup=search_config&itemtype={$itemtype}' ,'glpipopup', " . "'height=400, width=1000, top=100, left=100, scrollbars=yes'); w.focus();\""; $search_config = "<img alt=\"" . __s('Select default items to show') . "\" title=\"" . __s('Select default items to show') . "\" src='" . $CFG_GLPI["root_doc"] . "/pics/options_search.png' "; $search_config .= $tmp . ">"; } Html::printPager($p['start'], $numrows, $target, $parameters, $itemtype, 0, $search_config); } // Define begin and end var for loop // Search case $begin_display = $p['start']; $end_display = min($numrows, $p['start'] + $LIST_LIMIT); // No search Case if ($nosearch) { $begin_display = 0; $end_display = min($numrows - $p['start'], $LIST_LIMIT); } // Export All case if ($p['export_all']) { $begin_display = 0; $end_display = $numrows; } // Form to massive actions $isadmin = $item && $item->canUpdate(); if (!$isadmin && in_array($itemtype, $CFG_GLPI["infocom_types"])) { $isadmin = Infocom::canUpdate() || Infocom::canCreate(); } $showmassiveactions = false; if ($itemtype != 'AllAssets') { $showmassiveactions = count($item->getAllMassiveActions($p['is_deleted'])); if ($showmassiveactions && $output_type == self::HTML_OUTPUT) { Html::openMassiveActionsForm('massform' . $itemtype); $massiveactionparams = array('num_displayed' => $end_display - $begin_display, 'fixed' => false, 'is_deleted' => $p['is_deleted']); Html::showMassiveActions($itemtype, $massiveactionparams); } } // Compute number of columns to display // Add toview elements $nbcols = $toview_count; $already_printed = array(); // Add meta search elements if real search (strlen>0) or only NOT search if ($_SESSION["glpisearchcount2"][$itemtype] > 0 && is_array($p['itemtype2'])) { for ($i = 0; $i < $_SESSION["glpisearchcount2"][$itemtype]; $i++) { if (isset($p['itemtype2'][$i]) && !empty($p['itemtype2'][$i]) && isset($p['contains2'][$i]) && strlen($p['contains2'][$i]) > 0 && (!isset($p['link2'][$i]) || !strstr($p['link2'][$i], "NOT"))) { if (!isset($already_printed[$p['itemtype2'][$i] . $p['field2'][$i]])) { $nbcols++; $already_printed[$p['itemtype2'][$i] . $p['field2'][$i]] = 1; } } } } if ($output_type == self::HTML_OUTPUT) { // HTML display - massive modif $nbcols++; } // Display List Header echo self::showHeader($output_type, $end_display - $begin_display + 1, $nbcols); // New Line for Header Items Line $headers_line = ''; $headers_line_top = ''; $headers_line_bottom = ''; echo self::showNewLine($output_type); $header_num = 1; if ($output_type == self::HTML_OUTPUT && $showmassiveactions) { // HTML display - massive modif $headers_line_top .= self::showHeaderItem($output_type, Html::getCheckAllAsCheckbox('massform' . $itemtype), $header_num, "", 0, $p['order']); $headers_line_bottom .= self::showHeaderItem($output_type, Html::getCheckAllAsCheckbox('massform' . $itemtype), $header_num, "", 0, $p['order']); } // Display column Headers for toview items foreach ($toview as $key => $val) { $linkto = ''; if (!isset($searchopt[$itemtype][$val]['nosort']) || !$searchopt[$itemtype][$val]['nosort']) { $linkto = "{$target}?itemtype={$itemtype}&sort=" . $val . "&order=" . ($p['order'] == "ASC" ? "DESC" : "ASC") . "&start=" . $p['start'] . $globallinkto; } $headers_line .= self::showHeaderItem($output_type, $searchopt[$itemtype][$val]["name"], $header_num, $linkto, $p['sort'] == $val, $p['order']); } // Display columns Headers for meta items $already_printed = array(); if ($_SESSION["glpisearchcount2"][$itemtype] > 0 && is_array($p['itemtype2'])) { for ($i = 0; $i < $_SESSION["glpisearchcount2"][$itemtype]; $i++) { if (isset($p['itemtype2'][$i]) && !empty($p['itemtype2'][$i]) && isset($p['contains2'][$i]) && strlen($p['contains2'][$i]) > 0) { if (!isset($already_printed[$p['itemtype2'][$i] . $p['field2'][$i]])) { if (!isset($metanames[$p['itemtype2'][$i]])) { if ($metaitem = getItemForItemtype($p['itemtype2'][$i])) { $metanames[$p['itemtype2'][$i]] = $metaitem->getTypeName(); } } $headers_line .= self::showHeaderItem($output_type, sprintf(__('%1$s - %2$s'), $metanames[$p['itemtype2'][$i]], $searchopt[$p['itemtype2'][$i]][$p['field2'][$i]]["name"]), $header_num); $already_printed[$p['itemtype2'][$i] . $p['field2'][$i]] = 1; } } } } // Add specific column Header if ($itemtype == 'CartridgeItem') { $headers_line .= self::showHeaderItem($output_type, _n('Cartridge', 'Cartridges', 2), $header_num); } if ($itemtype == 'ConsumableItem') { $headers_line .= self::showHeaderItem($output_type, _n('Consumable', 'Consumables', 2), $header_num); } if (isset($CFG_GLPI["union_search_type"][$itemtype])) { $headers_line .= self::showHeaderItem($output_type, __('Item type'), $header_num); } if ($itemtype == 'ReservationItem' && $output_type == self::HTML_OUTPUT) { $headers_line .= self::showHeaderItem($output_type, " ", $header_num); } // End Line for column headers $headers_line .= self::showEndLine($output_type); $headers_line_top .= $headers_line; $headers_line_bottom .= $headers_line; echo $headers_line_top; // if real search seek to begin of items to display (because of complete search) if (!$nosearch) { $DBread->data_seek($result, $p['start']); } // Define begin and end var for loop // Search case $i = $begin_display; // Init list of items displayed if ($output_type == self::HTML_OUTPUT) { Session::initNavigateListItems($itemtype); } // Num of the row (1=header_line) $row_num = 1; $massiveaction_field = 'id'; if (isset($CFG_GLPI["union_search_type"][$itemtype])) { $massiveaction_field = 'refID'; } // Display Loop while ($i < $numrows && $i < $end_display) { // Column num $item_num = 1; // Get data and increment loop variables $data = $DBread->fetch_assoc($result); $i++; $row_num++; // New line echo self::showNewLine($output_type, $i % 2, $p['is_deleted']); // Add item in item list Session::addToNavigateListItems($itemtype, $data["id"]); if ($output_type == self::HTML_OUTPUT && $showmassiveactions) { // HTML display - massive modif $tmpcheck = ""; if ($itemtype == 'Entity' && !in_array($data["id"], $_SESSION["glpiactiveentities"])) { $tmpcheck = " "; } else { if ($item->maybeRecursive() && !in_array($data["entities_id"], $_SESSION["glpiactiveentities"])) { $tmpcheck = " "; } else { $tmpcheck = Html::getMassiveActionCheckBox($itemtype, $data[$massiveaction_field]); } } echo self::showItem($output_type, $tmpcheck, $item_num, $row_num, "width='10'"); } // Print other toview items foreach ($toview as $key => $val) { echo self::showItem($output_type, self::giveItem($itemtype, $val, $data, $key), $item_num, $row_num, self::displayConfigItem($itemtype, $val, $data, $key)); } // Print Meta Item $already_printed = array(); if ($_SESSION["glpisearchcount2"][$itemtype] > 0 && is_array($p['itemtype2'])) { for ($j = 0; $j < $_SESSION["glpisearchcount2"][$itemtype]; $j++) { if (isset($p['itemtype2'][$j]) && !empty($p['itemtype2'][$j]) && isset($p['contains2'][$j]) && strlen($p['contains2'][$j]) > 0) { if (!isset($already_printed[$p['itemtype2'][$j] . $p['field2'][$j]])) { // General case if (strpos($data["META_{$j}"], "\$\$\$\$") === false) { $out = self::giveItem($p['itemtype2'][$j], $p['field2'][$j], $data, $j, 1); echo self::showItem($output_type, $out, $item_num, $row_num); // Case of GROUP_CONCAT item : split item and multilline display } else { $split = explode("\$\$\$\$", $data["META_{$j}"]); $count_display = 0; $out = ""; $unit = ""; $separate = '<br>'; if (isset($searchopt[$p['itemtype2'][$j]][$p['field2'][$j]]['splititems']) && $searchopt[$p['itemtype2'][$j]][$p['field2'][$j]]['splititems']) { $separate = '<hr>'; } if (isset($searchopt[$p['itemtype2'][$j]][$p['field2'][$j]]['unit'])) { $unit = $searchopt[$p['itemtype2'][$j]][$p['field2'][$j]]['unit']; } for ($k = 0; $k < count($split); $k++) { if ($p['contains2'][$j] == "NULL" || strlen($p['contains2'][$j]) == 0 || preg_match('/' . $p['contains2'][$j] . '/i', $split[$k]) || isset($searchopt[$p['itemtype2'][$j]][$p['field2'][$j]]['forcegroupby'])) { if ($count_display) { $out .= $separate; } $count_display++; // Manage Link to item $split2 = self::explodeWithID("\$\$", $split[$k]); if (isset($split2[1])) { if (isset($searchopt[$p['itemtype2'][$j]][$p['field2'][$j]]['datatype']) && $searchopt[$p['itemtype2'][$j]][$p['field2'][$j]]['datatype'] == 'itemlink') { $out .= "<a id='" . $p['itemtype2'][$j] . '_' . $data["id"] . '_' . $split2[1] . "' "; $out .= "href=\"" . Toolbox::getItemTypeFormURL($p['itemtype2'][$j]) . "?id=" . $split2[1] . "\">"; $out .= Dropdown::getValueWithUnit($split2[0], $unit); $linkout = $out; if ($_SESSION["glpiis_ids_visible"] || empty($split2[0])) { $linkout = sprintf(__('%1$s (%2$s)'), $linkout, $split2[1]); } $out = $linkout . "</a>"; } else { $out .= Dropdown::getValueWithUnit($split2[0], $unit); } } else { $out .= Dropdown::getValueWithUnit($split[$k], $unit); } } } echo self::showItem($output_type, $out, $item_num, $row_num); } $already_printed[$p['itemtype2'][$j] . $p['field2'][$j]] = 1; } } } } // Specific column display if ($itemtype == 'CartridgeItem') { echo self::showItem($output_type, Cartridge::getCount($data["id"], $data["ALARM"], $output_type != self::HTML_OUTPUT), $item_num, $row_num); } if ($itemtype == 'ConsumableItem') { echo self::showItem($output_type, Consumable::getCount($data["id"], $data["ALARM"], $output_type != self::HTML_OUTPUT), $item_num, $row_num); } if (isset($CFG_GLPI["union_search_type"][$itemtype])) { $typename = $data["TYPE"]; if ($itemtmp = getItemForItemtype($data["TYPE"])) { $typename = $itemtmp->getTypeName(); } echo self::showItem($output_type, $typename, $item_num, $row_num); } if ($itemtype == 'ReservationItem' && $output_type == self::HTML_OUTPUT) { if ($data["ACTIVE"]) { echo self::showItem($output_type, "<a href='reservation.php?reservationitems_id=" . $data["refID"] . "' title=\"" . __s('See planning') . "\">" . "<img src=\"" . $CFG_GLPI["root_doc"] . "/pics/reservation-3.png\" alt='' title=''></a>", $item_num, $row_num, "class='center'"); } else { echo self::showItem($output_type, " ", $item_num, $row_num); } } // End Line echo self::showEndLine($output_type); } $title = ""; // Create title if ($output_type == self::PDF_OUTPUT_LANDSCAPE || $output_type == self::PDF_OUTPUT_PORTRAIT) { if ($_SESSION["glpisearchcount"][$itemtype] > 0 && count($p['contains']) > 0) { for ($key = 0; $key < $_SESSION["glpisearchcount"][$itemtype]; $key++) { $titlecontain = ''; if (strlen($p['contains'][$key]) > 0) { if (isset($p["link"][$key])) { $titlecontain = " " . $p["link"][$key] . " "; } switch ($p['field'][$key]) { case "all": $titlecontain = sprintf(__('%1$s %2$s'), $titlecontain, __('All')); break; case "view": $titlecontain = sprintf(__('%1$s %2$s'), $titlecontain, __('Items seen')); break; default: $titlecontain = sprintf(__('%1$s %2$s'), $titlecontain, $searchopt[$itemtype][$p['field'][$key]]["name"]); } switch ($p['searchtype'][$key]) { case "equals": if (in_array($searchopt[$itemtype][$p['field'][$key]]["field"], array('name', 'completename'))) { $titlecontain = sprintf(__('%1$s = %2$s'), $titlecontain, Dropdown::getDropdownName($searchopt[$itemtype][$p['field'][$key]]["table"], $p['contains'][$key])); } else { $titlecontain = sprintf(__('%1$s = %2$s'), $titlecontain, $p['contains'][$key]); } break; case "notequals": if (in_array($searchopt[$itemtype][$p['field'][$key]]["field"], array('name', 'completename'))) { $titlecontain = sprintf(__('%1$s <> %2$s'), $titlecontain, Dropdown::getDropdownName($searchopt[$itemtype][$p['field'][$key]]["table"], $p['contains'][$key])); } else { $titlecontain = sprintf(__('%1$s <> %2$s'), $titlecontain, $p['contains'][$key]); } break; case "lessthan": $titlecontain = sprintf(__('%1$s < %2$s'), $titlecontain, $p['contains'][$key]); break; case "morethan": $titlecontain = sprintf(__('%1$s > %2$s'), $titlecontain, $p['contains'][$key]); break; case "contains": $titlecontain = sprintf(__('%1$s = %2$s'), $titlecontain, '%' . $p['contains'][$key] . '%'); break; case "under": $titlecontain = sprintf(__('%1$s %2$s'), $titlecontain, sprintf(__('%1$s %2$s'), __('under'), Dropdown::getDropdownName($searchopt[$itemtype][$p['field'][$key]]["table"], $p['contains'][$key]))); break; case "notunder": $titlecontain = sprintf(__('%1$s %2$s'), $titlecontain, sprintf(__('%1$s %2$s'), __('not under'), Dropdown::getDropdownName($searchopt[$itemtype][$p['field'][$key]]["table"], $p['contains'][$key]))); break; default: $titlecontain = sprintf(__('%1$s = %2$s'), $titlecontain, $p['contains'][$key]); break; } } $title .= $titlecontain; } } if ($_SESSION["glpisearchcount2"][$itemtype] > 0 && count($p['contains2']) > 0) { for ($key = 0; $key < $_SESSION["glpisearchcount2"][$itemtype]; $key++) { $titlecontain2 = ''; if (strlen($p['contains2'][$key]) > 0) { if (isset($p['link2'][$key])) { $titlecontain2 = sprintf(__('%1$s %2$s'), $titlecontain2, $p['link2'][$key]); } $titlecontain2 = sprintf(__('%1$s %2$s'), $titlecontain2, sprintf(__('%1$s / %2$s'), $metanames[$p['itemtype2'][$key]], $searchopt[$p['itemtype2'][$key]][$p['field2'][$key]]["name"])); switch ($p['searchtype2'][$key]) { case "equals": if (in_array($searchopt[$p['itemtype2'][$key]][$p['field2'][$key]]["field"], array('name', 'completename'))) { $titlecontain2 = sprintf(__('%1$s = %2$s'), $titlecontain2, Dropdown::getDropdownName($searchopt[$p['itemtype2'][$key]][$p['field2'][$key]]["table"], $p['contains2'][$key])); } else { $titlecontain2 = sprintf(__('%1$s = %2$s'), $titlecontain2, $p['contains2'][$key]); } break; case "notequals": if (in_array($searchopt[$p['itemtype2'][$key]][$p['field2'][$key]]["field"], array('name', 'completename'))) { $titlecontain2 = sprintf(__('%1$s <> %2$s'), $titlecontain2, Dropdown::getDropdownName($searchopt[$p['itemtype2'][$key]][$p['field2'][$key]]["table"], $p['contains2'][$key])); } else { $titlecontain2 = sprintf(__('%1$s <> %2$s'), $titlecontain2, $p['contains2'][$key]); } break; case "lessthan": $titlecontain2 = sprintf(__('%1$s < %2$s'), $titlecontain2, $p['contains2'][$key]); break; case "morethan": $titlecontain2 = sprintf(__('%1$s > %2$s'), $titlecontain2, $p['contains2'][$key]); break; case "contains": $titlecontain2 = sprintf(__('%1$s = %2$s'), $titlecontain2, '%' . $p['contains2'][$key] . '%'); break; case "under": $titlecontain2 = sprintf(__('%1$s %2$s'), $titlecontain2, sprintf(__('%1$s %2$s'), __('under'), Dropdown::getDropdownName($searchopt[$p['itemtype2'][$key]][$p['field2'][$key]]["table"], $p['contains2'][$key]))); break; case "notunder": $titlecontain2 = sprintf(__('%1$s %2$s'), $titlecontain2, sprintf(__('%1$s %2$s'), __('not under'), Dropdown::getDropdownName($searchopt[$p['itemtype2'][$key]][$p['field2'][$key]]["table"], $p['contains2'][$key]))); break; default: $titlecontain2 = sprintf(__('%1$s = %2$s'), $titlecontain2, $p['contains2'][$key]); break; } } $title .= $titlecontain2; } } } if ($output_type == self::HTML_OUTPUT) { echo $headers_line_bottom; } // Display footer echo self::showFooter($output_type, $title); // Delete selected item if ($output_type == self::HTML_OUTPUT) { if ($showmassiveactions) { $massiveactionparams['ontop'] = false; Html::showMassiveActions($itemtype, $massiveactionparams); // End form for delete item Html::closeForm(); } else { echo "<br>"; } } if ($output_type == self::HTML_OUTPUT) { // In case of HTML display Html::printPager($p['start'], $numrows, $target, $parameters, '', 0, $search_config); } } else { echo self::showError($output_type); } } else { echo $DBread->error(); } }
public function createLinkWithItem($detailID = 0, $items_id = 0, $itemtype = 0, $plugin_order_orders_id = 0, $entity = 0, $templateID = 0, $history = true, $check_link = true) { global $DB; if (!$check_link || !$this->itemAlreadyLinkedToAnOrder($itemtype, $items_id, $plugin_order_orders_id, $detailID)) { $detail = new PluginOrderOrder_Item(); $restricted = array('ConsumableItem', 'CartridgeItem'); if ($itemtype == 'SoftwareLicense') { $detail->getFromDB($detailID); $query = "SELECT `id`\n FROM `glpi_plugin_order_orders_items`\n WHERE `plugin_order_orders_id` = '{$plugin_order_orders_id}'\n AND `plugin_order_references_id` = '{$detail->fields["plugin_order_references_id"]}'\n AND `price_taxfree` LIKE '{$detail->fields["price_taxfree"]}'\n AND `discount` LIKE '{$detail->fields["discount"]}'\n AND `states_id` = 1 "; $result = $DB->query($query); $nb = $DB->numrows($result); if ($nb) { for ($i = 0; $i < $nb; $i++) { $ID = $DB->result($result, $i, 'id'); $input["id"] = $ID; $input["items_id"] = $items_id; $detail->update($input); $this->generateInfoComRelatedToOrder($entity, $ID, $itemtype, $items_id, 0); $lic = new SoftwareLicense(); $lic->getFromDB($items_id); $values["id"] = $lic->fields["id"]; $values["number"] = $lic->fields["number"] + 1; $lic->update($values); } if ($history) { $order = new PluginOrderOrder(); $new_value = __("Item linked to order", "order") . ' : ' . $lic->getField("name"); $order->addHistory('PluginOrderOrder', '', $new_value, $plugin_order_orders_id); } } } elseif (in_array($itemtype, $restricted)) { if ($itemtype == 'ConsumableItem') { $item = new Consumable(); $type = 'Consumable'; $pkey = 'consumableitems_id'; } elseif ($itemtype == 'CartridgeItem') { $item = new Cartridge(); $type = 'Cartridge'; $pkey = 'cartridgeitems_id'; } $detail->getFromDB($detailID); $input[$pkey] = $items_id; $input["date_in"] = $detail->fields["delivery_date"]; $newID = $item->add($input); $input["id"] = $detailID; $input["items_id"] = $newID; $input["itemtype"] = $itemtype; if ($detail->update($input)) { $this->generateInfoComRelatedToOrder($entity, $detailID, $type, $newID, 0); } } elseif ($itemtype == 'Contract') { $input["id"] = $detailID; $input["items_id"] = $items_id; $input["itemtype"] = $itemtype; if ($detail->update($input)) { $detail->getFromDB($detailID); $item = new Contract(); if ($item->update(array('id' => $items_id, 'cost' => $detail->fields["price_discounted"]))) { $order = new PluginOrderOrder(); $order->getFromDB($plugin_order_orders_id); if (!countElementsInTable('glpi_contracts_suppliers', "`contracts_id`='{$items_id}' AND `suppliers_id`='" . $order->fields['suppliers_id'] . "'")) { $contract_supplier = new Contract_Supplier(); $contract_supplier->add(array('contracts_id' => $items_id, 'suppliers_id' => $order->fields['suppliers_id'])); } } } } else { $input["id"] = $detailID; $input["items_id"] = $items_id; $input["itemtype"] = $itemtype; if ($detail->update($input)) { $this->generateInfoComRelatedToOrder($entity, $detailID, $itemtype, $items_id, $templateID); if ($history) { $order = new PluginOrderOrder(); $order->getFromDB($detail->fields["plugin_order_orders_id"]); $item = new $itemtype(); $item->getFromDB($items_id); $new_value = __("Item linked to order", "order") . ' : ' . $item->getField("name"); $order->addHistory('PluginOrderOrder', '', $new_value, $order->fields["id"]); } } } if ($history) { $order = new PluginOrderOrder(); $order->getFromDB($detail->fields["plugin_order_orders_id"]); $new_value = __("Item linked to order", "order") . ' : ' . $order->fields["name"]; $order->addHistory($itemtype, '', $new_value, $items_id); } Session::addMessageAfterRedirect(__("Item linked to order", "order"), true); } else { Session::addMessageAfterRedirect(__("Item already linked to another one", "order"), true, ERROR); } }
/** * Cron action on cartridges : alert if a stock is behind the threshold * * @param $task for log, display information if NULL? (default NULL) * * @return 0 : nothing to do 1 : done with success **/ static function cronCartridge($task = NULL) { global $DB, $CFG_GLPI; $cron_status = 1; if ($CFG_GLPI["use_mailing"]) { $message = array(); $alert = new Alert(); foreach (Entity::getEntitiesToNotify('cartridges_alert_repeat') as $entity => $repeat) { // if you change this query, please don't forget to also change in showDebug() $query_alert = "SELECT `glpi_cartridgeitems`.`id` AS cartID,\n `glpi_cartridgeitems`.`entities_id` AS entity,\n `glpi_cartridgeitems`.`ref` AS ref,\n `glpi_cartridgeitems`.`name` AS name,\n `glpi_cartridgeitems`.`alarm_threshold` AS threshold,\n `glpi_alerts`.`id` AS alertID,\n `glpi_alerts`.`date`\n FROM `glpi_cartridgeitems`\n LEFT JOIN `glpi_alerts`\n ON (`glpi_cartridgeitems`.`id` = `glpi_alerts`.`items_id`\n AND `glpi_alerts`.`itemtype` = 'CartridgeItem')\n WHERE `glpi_cartridgeitems`.`is_deleted` = '0'\n AND `glpi_cartridgeitems`.`alarm_threshold` >= '0'\n AND `glpi_cartridgeitems`.`entities_id` = '" . $entity . "'\n AND (`glpi_alerts`.`date` IS NULL\n OR (`glpi_alerts`.`date`+{$repeat}) < CURRENT_TIMESTAMP());"; $message = ""; $items = array(); foreach ($DB->request($query_alert) as $cartridge) { if (($unused = Cartridge::getUnusedNumber($cartridge["cartID"])) <= $cartridge["threshold"]) { //TRANS: %1$s is the cartridge name, %2$s its reference, %3$d the remaining number $message .= sprintf(__('Threshold of alarm reached for the type of cartridge: %1$s - Reference %2$s - Remaining %3$d'), $cartridge["name"], $cartridge["ref"], $unused); $message .= '<br>'; $items[$cartridge["cartID"]] = $cartridge; // if alert exists -> delete if (!empty($cartridge["alertID"])) { $alert->delete(array("id" => $cartridge["alertID"])); } } } if (!empty($items)) { $options['entities_id'] = $entity; $options['items'] = $items; $entityname = Dropdown::getDropdownName("glpi_entities", $entity); if (NotificationEvent::raiseEvent('alert', new CartridgeItem(), $options)) { if ($task) { $task->log(sprintf(__('%1$s: %2$s') . "\n", $entityname, $message)); $task->addVolume(1); } else { Session::addMessageAfterRedirect(sprintf(__('%1$s: %2$s'), $entityname, $message)); } $input["type"] = Alert::THRESHOLD; $input["itemtype"] = 'CartridgeItem'; // add alerts foreach ($items as $ID => $consumable) { $input["items_id"] = $ID; $alert->add($input); unset($alert->fields['id']); } } else { //TRANS: %s is entity name $msg = sprintf(__('%s: send cartridge alert failed'), $entityname); if ($task) { $task->log($msg); } else { //TRANS: %s is the entity Session::addMessageAfterRedirect($msg, false, ERROR); } } } } } }
$cartype->redirectToList(); } else { if (isset($_POST["restore"])) { $cartype->check($_POST["id"], PURGE); if ($cartype->restore($_POST)) { Event::log($_POST["id"], "cartridgeitems", 4, "inventory", sprintf(__('%s restores an item'), $_SESSION["glpiname"])); } $cartype->redirectToList(); } else { if (isset($_POST["purge"])) { $cartype->check($_POST["id"], PURGE); if ($cartype->delete($_POST, 1)) { Event::log($_POST["id"], "cartridgeitems", 4, "inventory", sprintf(__('%s purges an item'), $_SESSION["glpiname"])); } $cartype->redirectToList(); } else { if (isset($_POST["update"])) { $cartype->check($_POST["id"], UPDATE); if ($cartype->update($_POST)) { Event::log($_POST["id"], "cartridgeitems", 4, "inventory", sprintf(__('%s updates an item'), $_SESSION["glpiname"])); } Html::back(); } else { Html::header(Cartridge::getTypeName(Session::getPluralNumber()), $_SERVER['PHP_SELF'], "assets", "cartridgeitem"); $cartype->display(array('id' => $_GET["id"])); Html::footer(); } } } } }
GLPI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GLPI. If not, see <http://www.gnu.org/licenses/>. -------------------------------------------------------------------------- */ /** @file * @brief */ include '../inc/includes.php'; Session::checkRight("cartridge", "r"); $cart = new Cartridge(); $cartype = new CartridgeItem(); if (isset($_POST["add"])) { $cartype->check($_POST["cartridgeitems_id"], 'w'); for ($i = 0; $i < $_POST["to_add"]; $i++) { unset($cart->fields["id"]); $cart->add($_POST); } Event::log($_POST["cartridgeitems_id"], "cartridges", 4, "inventory", sprintf(__('%s adds cartridges'), $_SESSION["glpiname"])); Html::back(); } else { if (isset($_POST["delete"])) { $cartype->check($_POST["cartridgeitems_id"], 'w'); if ($cart->delete($_POST)) { Event::log($_POST["cartridgeitems_id"], "cartridges", 4, "inventory", sprintf(__('%s deletes a cartridge'), $_SESSION["glpiname"])); }
/** * Cron action on cartridges : alert if a stock is behind the threshold * * @param $task for log, display informations if NULL? * * @return 0 : nothing to do 1 : done with success * **/ static function cronCartridge($task = NULL) { global $DB, $CFG_GLPI, $LANG; $cron_status = 1; if ($CFG_GLPI["use_mailing"]) { $message = array(); $alert = new Alert(); foreach (Entity::getEntitiesToNotify('cartridges_alert_repeat') as $entity => $repeat) { // if you change this query, please don't forget to also change in showDebug() $query_alert = "SELECT `glpi_cartridgeitems`.`id` AS cartID,\n `glpi_cartridgeitems`.`entities_id` AS entity,\n `glpi_cartridgeitems`.`ref` AS cartref,\n `glpi_cartridgeitems`.`name` AS cartname,\n `glpi_cartridgeitems`.`alarm_threshold` AS threshold,\n `glpi_alerts`.`id` AS alertID,\n `glpi_alerts`.`date`\n FROM `glpi_cartridgeitems`\n LEFT JOIN `glpi_alerts`\n ON (`glpi_cartridgeitems`.`id` = `glpi_alerts`.`items_id`\n AND `glpi_alerts`.`itemtype` = 'CartridgeItem')\n WHERE `glpi_cartridgeitems`.`is_deleted` = '0'\n AND `glpi_cartridgeitems`.`alarm_threshold` >= '0'\n AND `glpi_cartridgeitems`.`entities_id` = '" . $entity . "'\n AND (`glpi_alerts`.`date` IS NULL\n OR (`glpi_alerts`.date+{$repeat}) < CURRENT_TIMESTAMP());"; $message = ""; $items = array(); foreach ($DB->request($query_alert) as $cartridge) { if (($unused = Cartridge::getUnusedNumber($cartridge["cartID"])) <= $cartridge["threshold"]) { // define message alert $message .= $LANG['mailing'][35] . " " . $cartridge["cartname"] . " - " . $LANG['consumables'][2] . " : " . $cartridge["cartref"] . " - " . $LANG['software'][20] . " : " . $unused . "<br>"; $items[$cartridge["cartID"]] = $cartridge; // if alert exists -> delete if (!empty($cartridge["alertID"])) { $alert->delete(array("id" => $cartridge["alertID"])); } } } if (!empty($items)) { $options['entities_id'] = $entity; $options['cartridges'] = $items; if (NotificationEvent::raiseEvent('alert', new Cartridge(), $options)) { if ($task) { $task->log(Dropdown::getDropdownName("glpi_entities", $entity) . " : {$message}\n"); $task->addVolume(1); } else { addMessageAfterRedirect(Dropdown::getDropdownName("glpi_entities", $entity) . " : {$message}"); } $input["type"] = Alert::THRESHOLD; $input["itemtype"] = 'CartridgeItem'; // add alerts foreach ($items as $ID => $consumable) { $input["items_id"] = $ID; $alert->add($input); unset($alert->fields['id']); } } else { if ($task) { $task->log(Dropdown::getDropdownName("glpi_entities", $entity) . " : Send cartidge alert failed\n"); } else { addMessageAfterRedirect(Dropdown::getDropdownName("glpi_entities", $entity) . " : Send cartidge alert failed", false, ERROR); } } } } } }
Copyright (C) 2003-2013 by the INDEPNET Development Team. http://indepnet.net/ http://glpi-project.org ------------------------------------------------------------------------- LICENSE This file is part of GLPI. GLPI is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GLPI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GLPI. If not, see <http://www.gnu.org/licenses/>. -------------------------------------------------------------------------- */ /** @file * @brief */ include '../inc/includes.php'; Session::checkRight("cartridge", "r"); Html::header(Cartridge::getTypeName(2), $_SERVER['PHP_SELF'], "inventory", "cartridge"); Search::show('CartridgeItem'); Html::footer();
static function showList($itemtype, $params) { global $DB, $CFG_GLPI, $LANG, $PLUGIN_HOOKS; // Instanciate an object to access method $item = NULL; if ($itemtype != 'States' && class_exists($itemtype)) { $item = new $itemtype(); } $_SESSION['plugin_mobile']['rows_limit'] = 10; // sdb38l $_SESSION['plugin_mobile']['cols_limit'] = 5; // sdb38l $LIST_LIMIT = $_SESSION['plugin_mobile']['rows_limit']; // Default values of parameters $p['link'] = array(); // $p['field'] = array(); // $p['contains'] = array(); // $p['searchtype'] = array(); // $p['sort'] = '1'; // $p['order'] = 'ASC'; // $p['start'] = 0; // $p['is_deleted'] = 0; $p['export_all'] = 0; $p['link2'] = ''; // $p['contains2'] = ''; // $p['field2'] = ''; // $p['itemtype2'] = ''; $p['searchtype2'] = ''; $p['showheader'] = true; foreach ($params as $key => $val) { $p[$key] = $val; } if ($p['export_all']) { $p['start'] = 0; } // Manage defautll seachtype value : for bookmark compatibility if (count($p['contains'])) { foreach ($p['contains'] as $key => $val) { if (!isset($p['searchtype'][$key])) { $p['searchtype'][$key] = 'contains'; } } } if (is_array($p['contains2']) && count($p['contains2'])) { foreach ($p['contains2'] as $key => $val) { if (!isset($p['searchtype2'][$key])) { $p['searchtype2'][$key] = 'contains'; } } } $target = Toolbox::getItemTypeSearchURL($itemtype); $limitsearchopt = Search::getCleanedOptions($itemtype); if (isset($CFG_GLPI['union_search_type'][$itemtype])) { $itemtable = $CFG_GLPI['union_search_type'][$itemtype]; } else { $itemtable = getTableForItemType($itemtype); } // Set display type for export if define $output_type = Search::HTML_OUTPUT; if (isset($_GET['display_type'])) { $output_type = $_GET['display_type']; // Limit to 10 element if ($_GET['display_type'] == Search::GLOBAL_SEARCH) { $LIST_LIMIT = Search::GLOBAL_SEARCH_DISPLAY_COUNT; } } // hack for States if (isset($CFG_GLPI['union_search_type'][$itemtype])) { $entity_restrict = true; } else { $entity_restrict = $item->isEntityAssign(); } $metanames = array(); // Get the items to display $toview = Search::addDefaultToView($itemtype); // Add items to display depending of personal prefs $displaypref = DisplayPreference::getForTypeUser($itemtype, Session::getLoginUserID()); if (count($displaypref)) { foreach ($displaypref as $val) { array_push($toview, $val); } } // Add searched items if (count($p['field']) > 0) { foreach ($p['field'] as $key => $val) { if (!in_array($val, $toview) && $val != 'all' && $val != 'view') { array_push($toview, $val); } } } // Add order item if (!in_array($p['sort'], $toview)) { array_push($toview, $p['sort']); } // Special case for Ticket : put ID in front if ($itemtype == 'Ticket') { array_unshift($toview, 2); } // Clean toview array $toview = array_unique($toview); foreach ($toview as $key => $val) { if (!isset($limitsearchopt[$val])) { unset($toview[$key]); } } // delete entities display //var_dump($toview); if (array_search('80', $toview) !== false) { unset($toview[array_search('80', $toview)]); } $toview_count = count($toview); // Construct the request //// 1 - SELECT //$SELECT = "SELECT ".PluginMobileSearch::addDefaultSelect($itemtype); $SELECT = "SELECT '" . $_SESSION['glpiname'] . "' AS currentuser, " . PluginMobileSearch::addDefaultSelect($itemtype); // Add select for all toview item foreach ($toview as $key => $val) { $SELECT .= Search::addSelect($itemtype, $val, $key, 0); } //// 2 - FROM AND LEFT JOIN // Set reference table $FROM = " FROM `{$itemtable}`"; // Init already linked tables array in order not to link a table several times $already_link_tables = array(); // Put reference table array_push($already_link_tables, $itemtable); // Add default join $COMMONLEFTJOIN = Search::addDefaultJoin($itemtype, $itemtable, $already_link_tables); $FROM .= $COMMONLEFTJOIN; $searchopt = array(); $searchopt[$itemtype] =& Search::getOptions($itemtype); // Add all table for toview items //foreach ($toview as $key => $val) { // $FROM .= Search::addLeftJoin($itemtype,$itemtable,$already_link_tables, // $searchopt[$itemtype][$val]["table"], // $searchopt[$itemtype][$val]["linkfield"]); //} foreach ($toview as $key => $val) { $FROM .= self::addLeftJoin($itemtype, $itemtable, $already_link_tables, $searchopt[$itemtype][$val]["table"], $searchopt[$itemtype][$val]["linkfield"], 0, 0, $searchopt[$itemtype][$val]["joinparams"]); } // Search all case : //if (in_array("all",$p['field'])) { // foreach ($searchopt[$itemtype] as $key => $val) { // // Do not search on Group Name // if (is_array($val)) { // $FROM .= Search::addLeftJoin($itemtype,$itemtable,$already_link_tables, // $searchopt[$itemtype][$key]["table"], // $searchopt[$itemtype][$key]["linkfield"]); // } // } //} // Search all case : if (in_array("all", $p['field'])) { foreach ($searchopt[$itemtype] as $key => $val) { // Do not search on Group Name if (is_array($val)) { $FROM .= self::addLeftJoin($itemtype, $itemtable, $already_link_tables, $searchopt[$itemtype][$key]["table"], $searchopt[$itemtype][$key]["linkfield"], 0, 0, $searchopt[$itemtype][$key]["joinparams"]); } } } //// 3 - WHERE // default string $COMMONWHERE = self::addDefaultWhere($itemtype); $first = empty($COMMONWHERE); // Add deleted if item have it if ($item && $item->maybeDeleted()) { $LINK = " AND "; if ($first) { $LINK = " "; $first = false; } $COMMONWHERE .= $LINK . "`{$itemtable}`.`is_deleted` = '" . $p['is_deleted'] . "' "; } // Remove template items if ($item && $item->maybeTemplate()) { $LINK = " AND "; if ($first) { $LINK = " "; $first = false; } $COMMONWHERE .= $LINK . "`{$itemtable}`.`is_template` = '0' "; } // Add Restrict to current entities if ($entity_restrict) { $LINK = " AND "; if ($first) { $LINK = " "; $first = false; } if ($itemtype == 'Entity') { $COMMONWHERE .= getEntitiesRestrictRequest($LINK, $itemtable, 'id', '', true); } else { if (isset($CFG_GLPI["union_search_type"][$itemtype])) { // Will be replace below in Union/Recursivity Hack $COMMONWHERE .= $LINK . " ENTITYRESTRICT "; } else { $COMMONWHERE .= getEntitiesRestrictRequest($LINK, $itemtable, '', '', $item->maybeRecursive()); } } } $WHERE = ""; $HAVING = ""; // Add search conditions // If there is search items if ($_SESSION["glpisearchcount"][$itemtype] > 0 && count($p['contains']) > 0) { for ($key = 0; $key < $_SESSION["glpisearchcount"][$itemtype]; $key++) { // if real search (strlen >0) and not all and view search if (isset($p['contains'][$key]) && strlen($p['contains'][$key]) > 0) { // common search if ($p['field'][$key] != "all" && $p['field'][$key] != "view") { $LINK = " "; $NOT = 0; $tmplink = ""; if (is_array($p['link']) && isset($p['link'][$key])) { if (strstr($p['link'][$key], "NOT")) { $tmplink = " " . str_replace(" NOT", "", $p['link'][$key]); $NOT = 1; } else { $tmplink = " " . $p['link'][$key]; } } else { $tmplink = " AND "; } if (isset($searchopt[$itemtype][$p['field'][$key]]["usehaving"])) { // Manage Link if not first item if (!empty($HAVING)) { $LINK = $tmplink; } // Find key $item_num = array_search($p['field'][$key], $toview); $HAVING .= Search::addHaving($LINK, $NOT, $itemtype, $p['field'][$key], $p['searchtype'][$key], $p['contains'][$key], 0, $item_num); } else { // Manage Link if not first item if (!empty($WHERE)) { $LINK = $tmplink; } $WHERE .= self::addWhere($LINK, $NOT, $itemtype, $p['field'][$key], $p['searchtype'][$key], $p['contains'][$key]); } // view and all search } else { $LINK = " OR "; $NOT = 0; $globallink = " AND "; if (is_array($p['link']) && isset($p['link'][$key])) { switch ($p['link'][$key]) { case "AND": $LINK = " OR "; $globallink = " AND "; break; case "AND NOT": $LINK = " AND "; $NOT = 1; $globallink = " AND "; break; case "OR": $LINK = " OR "; $globallink = " OR "; break; case "OR NOT": $LINK = " AND "; $NOT = 1; $globallink = " OR "; break; } } else { $tmplink = " AND "; } // Manage Link if not first item if (!empty($WHERE)) { $WHERE .= $globallink; } $WHERE .= " ( "; $first2 = true; $items = array(); if ($p['field'][$key] == "all") { $items = $searchopt[$itemtype]; } else { // toview case : populate toview foreach ($toview as $key2 => $val2) { $items[$val2] = $searchopt[$itemtype][$val2]; } } foreach ($items as $key2 => $val2) { if (is_array($val2)) { // Add Where clause if not to be done in HAVING CLAUSE if (!isset($val2["usehaving"])) { $tmplink = $LINK; if ($first2) { $tmplink = " "; $first2 = false; } $WHERE .= self::addWhere($tmplink, $NOT, $itemtype, $key2, $p['searchtype'][$key], $p['contains'][$key]); } } } $WHERE .= " ) "; } } } } //// 4 - ORDER $ORDER = " ORDER BY `id` "; foreach ($toview as $key => $val) { if ($p['sort'] == $val) { $ORDER = self::addOrderBy($itemtype, $p['sort'], $p['order'], $key); } } //// 5 - META SEARCH // Preprocessing if ($_SESSION["glpisearchcount2"][$itemtype] > 0 && is_array($p['itemtype2'])) { // a - SELECT for ($i = 0; $i < $_SESSION["glpisearchcount2"][$itemtype]; $i++) { if (isset($p['itemtype2'][$i]) && !empty($p['itemtype2'][$i]) && isset($p['contains2'][$i]) && strlen($p['contains2'][$i]) > 0) { $SELECT .= self::addSelect($p['itemtype2'][$i], $p['field2'][$i], $i, 1, $p['itemtype2'][$i]); } } // b - ADD LEFT JOIN // Already link meta table in order not to linked a table several times $already_link_tables2 = array(); // Link reference tables for ($i = 0; $i < $_SESSION["glpisearchcount2"][$itemtype]; $i++) { if (isset($p['itemtype2'][$i]) && !empty($p['itemtype2'][$i]) && isset($p['contains2'][$i]) && strlen($p['contains2'][$i]) > 0) { if (!in_array(getTableForItemType($p['itemtype2'][$i]), $already_link_tables2)) { $FROM .= Search::addMetaLeftJoin($itemtype, $p['itemtype2'][$i], $already_link_tables2, $p['contains2'][$i] == "NULL" || strstr($p['link2'][$i], "NOT")); } } } // Link items tables for ($i = 0; $i < $_SESSION["glpisearchcount2"][$itemtype]; $i++) { if (isset($p['itemtype2'][$i]) && !empty($p['itemtype2'][$i]) && isset($p['contains2'][$i]) && strlen($p['contains2'][$i]) > 0) { if (!isset($searchopt[$p['itemtype2'][$i]])) { $searchopt[$p['itemtype2'][$i]] =& self::getOptions($p['itemtype2'][$i]); } if (!in_array($searchopt[$p['itemtype2'][$i]][$p['field2'][$i]]["table"] . "_" . $p['itemtype2'][$i], $already_link_tables2)) { $FROM .= self::addLeftJoin($p['itemtype2'][$i], getTableForItemType($p['itemtype2'][$i]), $already_link_tables2, $searchopt[$p['itemtype2'][$i]][$p['field2'][$i]]["table"], $searchopt[$p['itemtype2'][$i]][$p['field2'][$i]]["linkfield"], 1, $p['itemtype2'][$i], $searchopt[$p['itemtype2'][$i]][$p['field2'][$i]]["joinparams"]); } } } } //// 6 - Add item ID // Add ID to the select if (!empty($itemtable)) { $SELECT .= "`{$itemtable}`.`id` AS id "; } //// 7 - Manage GROUP BY $GROUPBY = ""; // Meta Search / Search All / Count tickets if ($_SESSION["glpisearchcount2"][$itemtype] > 0 || !empty($HAVING) || in_array('all', $p['field'])) { $GROUPBY = " GROUP BY `{$itemtable}`.`id`"; } if (empty($GROUPBY)) { foreach ($toview as $key2 => $val2) { if (!empty($GROUPBY)) { break; } if (isset($searchopt[$itemtype][$val2]["forcegroupby"])) { $GROUPBY = " GROUP BY `{$itemtable}`.`id`"; } } } // Specific search for others item linked (META search) if (is_array($p['itemtype2'])) { for ($key = 0; $key < $_SESSION["glpisearchcount2"][$itemtype]; $key++) { if (isset($p['itemtype2'][$key]) && !empty($p['itemtype2'][$key]) && isset($p['contains2'][$key]) && strlen($p['contains2'][$key]) > 0) { $LINK = ""; // For AND NOT statement need to take into account all the group by items if (strstr($p['link2'][$key], "AND NOT") || isset($searchopt[$p['itemtype2'][$key]][$p['field2'][$key]]["usehaving"])) { $NOT = 0; if (strstr($p['link2'][$key], "NOT")) { $tmplink = " " . str_replace(" NOT", "", $p['link2'][$key]); $NOT = 1; } else { $tmplink = " " . $p['link2'][$key]; } if (!empty($HAVING)) { $LINK = $tmplink; } $HAVING .= self::addHaving($LINK, $NOT, $p['itemtype2'][$key], $p['field2'][$key], $p['searchtype2'][$key], $p['contains2'][$key], 1, $key); } else { // Meta Where Search $LINK = " "; $NOT = 0; // Manage Link if not first item if (is_array($p['link2']) && isset($p['link2'][$key]) && strstr($p['link2'][$key], "NOT")) { $tmplink = " " . str_replace(" NOT", "", $p['link2'][$key]); $NOT = 1; } else { if (is_array($p['link2']) && isset($p['link2'][$key])) { $tmplink = " " . $p['link2'][$key]; } else { $tmplink = " AND "; } } if (!empty($WHERE)) { $LINK = $tmplink; } $WHERE .= self::addWhere($LINK, $NOT, $p['itemtype2'][$key], $p['field2'][$key], $p['searchtype2'][$key], $p['contains2'][$key], 1); } } } } // Use a ReadOnly connection if available and configured to be used $DBread = DBConnection::getReadConnection(); // If no research limit research to display item and compute number of item using simple request $nosearch = true; for ($i = 0; $i < $_SESSION["glpisearchcount"][$itemtype]; $i++) { if (isset($p['contains'][$i]) && strlen($p['contains'][$i]) > 0) { $nosearch = false; } } if ($_SESSION["glpisearchcount2"][$itemtype] > 0) { $nosearch = false; } $LIMIT = ""; $numrows = 0; //No search : count number of items using a simple count(ID) request and LIMIT search if ($nosearch) { $LIMIT = " LIMIT " . $p['start'] . ", " . $LIST_LIMIT; // Force group by for all the type -> need to count only on table ID if (!isset($searchopt[$itemtype][1]['forcegroupby'])) { $count = "count(*)"; } else { $count = "count(DISTINCT `{$itemtable}`.`id`)"; } // request currentuser for SQL supervision, not displayed $query_num = "SELECT {$count}, '" . $_SESSION['glpiname'] . "' AS currentuser\n FROM `{$itemtable}`" . $COMMONLEFTJOIN; $first = true; if (!empty($COMMONWHERE)) { $LINK = " AND "; if ($first) { $LINK = " WHERE "; $first = false; } $query_num .= $LINK . $COMMONWHERE; } // Union Search : if (isset($CFG_GLPI["union_search_type"][$itemtype])) { $tmpquery = $query_num; $numrows = 0; foreach ($CFG_GLPI[$CFG_GLPI["union_search_type"][$itemtype]] as $ctype) { $ctable = getTableForItemType($ctype); $citem = new $ctype(); if ($citem->canView()) { // State case if ($itemtype == 'States') { $query_num = str_replace($CFG_GLPI["union_search_type"][$itemtype], $ctable, $tmpquery); $query_num .= " AND {$ctable}.`states_id` > '0' "; // Add deleted if item have it if ($citem && $citem->maybeDeleted()) { $query_num .= " AND `{$ctable}`.`is_deleted` = '0' "; } // Remove template items if ($citem && $citem->maybeTemplate()) { $query_num .= " AND `{$ctable}`.`is_template` = '0' "; } } else { // Ref table case $reftable = getTableForItemType($itemtype); $replace = "FROM `{$reftable}`\n INNER JOIN `{$ctable}`\n ON (`{$reftable}`.`items_id`=`{$ctable}`.`id`\n AND `{$reftable}`.`itemtype` = '{$ctype}')"; $query_num = str_replace("FROM `" . $CFG_GLPI["union_search_type"][$itemtype] . "`", $replace, $tmpquery); $query_num = str_replace($CFG_GLPI["union_search_type"][$itemtype], $ctable, $query_num); } $query_num = str_replace("ENTITYRESTRICT", getEntitiesRestrictRequest('', $ctable, '', '', $citem->maybeRecursive()), $query_num); $result_num = $DBread->query($query_num); $numrows += $DBread->result($result_num, 0, 0); } } } else { $result_num = $DBread->query($query_num); $numrows = $DBread->result($result_num, 0, 0); } } // If export_all reset LIMIT condition if ($p['export_all']) { $LIMIT = ""; } if (!empty($WHERE) || !empty($COMMONWHERE)) { if (!empty($COMMONWHERE)) { $WHERE = ' WHERE ' . $COMMONWHERE . (!empty($WHERE) ? ' AND ( ' . $WHERE . ' )' : ''); } else { $WHERE = ' WHERE ' . $WHERE . ' '; } $first = false; } if (!empty($HAVING)) { $HAVING = ' HAVING ' . $HAVING; } $DB->query("SET SESSION group_concat_max_len = 9999999;"); // Create QUERY if (isset($CFG_GLPI["union_search_type"][$itemtype])) { $first = true; $QUERY = ""; foreach ($CFG_GLPI[$CFG_GLPI["union_search_type"][$itemtype]] as $ctype) { $ctable = getTableForItemType($ctype); $citem = new $ctype(); if ($citem->canView()) { if ($first) { $first = false; } else { $QUERY .= " UNION "; } $tmpquery = ""; // State case if ($itemtype == 'States') { $tmpquery = $SELECT . ", '{$ctype}' AS TYPE " . $FROM . $WHERE; $tmpquery = str_replace($CFG_GLPI["union_search_type"][$itemtype], $ctable, $tmpquery); $tmpquery .= " AND `{$ctable}`.`states_id` > '0' "; // Add deleted if item have it if ($citem && $citem->maybeDeleted()) { $tmpquery .= " AND `{$ctable}`.`is_deleted` = '0' "; } // Remove template items if ($citem && $citem->maybeTemplate()) { $tmpquery .= " AND `{$ctable}`.`is_template` = '0' "; } } else { // Ref table case $reftable = getTableForItemType($itemtype); $tmpquery = $SELECT . ", '{$ctype}' AS TYPE, `{$reftable}`.`id` AS refID, " . "`{$ctable}`.`entities_id` AS ENTITY " . $FROM . $WHERE; $replace = "FROM `{$reftable}`" . " INNER JOIN `{$ctable}`" . " ON (`{$reftable}`.`items_id`=`{$ctable}`.`id`" . " AND `{$reftable}`.`itemtype` = '{$ctype}')"; $tmpquery = str_replace("FROM `" . $CFG_GLPI["union_search_type"][$itemtype] . "`", $replace, $tmpquery); $tmpquery = str_replace($CFG_GLPI["union_search_type"][$itemtype], $ctable, $tmpquery); } $tmpquery = str_replace("ENTITYRESTRICT", getEntitiesRestrictRequest('', $ctable, '', '', $citem->maybeRecursive()), $tmpquery); // SOFTWARE HACK if ($ctype == 'Software') { $tmpquery = str_replace("glpi_softwares.serial", "''", $tmpquery); $tmpquery = str_replace("glpi_softwares.otherserial", "''", $tmpquery); } $QUERY .= $tmpquery; } } if (empty($QUERY)) { echo Search::showError($output_type); return; } $QUERY .= str_replace($CFG_GLPI["union_search_type"][$itemtype] . ".", "", $ORDER) . $LIMIT; } else { $QUERY = $SELECT . $FROM . $WHERE . $GROUPBY . $HAVING . $ORDER . $LIMIT; } $DBread->query("SET SESSION group_concat_max_len = 4096;"); $result = $DBread->query($QUERY); if ($result2 = $DBread->query('SHOW WARNINGS')) { if ($DBread->numrows($result2) > 0) { $data = $DBread->fetch_assoc($result2); if ($data['Code'] == 1260) { $DBread->query("SET SESSION group_concat_max_len = 4194304;"); $result = $DBread->query($QUERY); } } } if ($result) { // if real search or complete export : get numrows from request if (!$nosearch || $p['export_all']) { $numrows = $DBread->numrows($result); } // Contruct Pager parameters $globallinkto = ""; if (count($p['field']) > 0) { $globallinkto .= self::getArrayUrlLink("field", $p['field']); } if ($p['link'] != '') { $globallinkto .= self::getArrayUrlLink("link", $p['link']); } if ($p['contains'] != array("")) { $globallinkto .= self::getArrayUrlLink("contains", $p['contains']); } if (count($p['field2']) > 0) { $globallinkto .= self::getArrayUrlLink("field2", $p['field2']); } if ($p['contains2'] != array("")) { $globallinkto .= self::getArrayUrlLink("contains2", $p['contains2']); } if ($p['itemtype2'] != '') { $globallinkto .= self::getArrayUrlLink("itemtype2", $p['itemtype2']); } if ($p['link2'] != '') { $globallinkto .= self::getArrayUrlLink("link2", $p['link2']); } $parameters = "sort=" . $p['sort'] . "&order=" . $p['order'] . $globallinkto; if ($output_type == Search::GLOBAL_SEARCH) { if (class_exists($itemtype)) { echo "<div class='center'><h2>" . $item->getTypeName(); // More items if ($numrows > $p['start'] + Search::GLOBAL_SEARCH_DISPLAY_COUNT) { echo " <a href='{$target}?{$parameters}' data-back='false'>" . $LANG['common'][66] . "</a>"; } echo "</h2></div>\n"; } else { return false; } } // If the begin of the view is before the number of items if ($p['start'] < $numrows) { // Form to massive actions $isadmin = false; // Compute number of columns to display // Add toview elements $nbcols = $toview_count; $already_printed = array(); // Add meta search elements if real search (strlen>0) or only NOT search if ($_SESSION["glpisearchcount2"][$itemtype] > 0 && is_array($p['itemtype2'])) { for ($i = 0; $i < $_SESSION["glpisearchcount2"][$itemtype]; $i++) { if (isset($p['itemtype2'][$i]) && isset($p['contains2'][$i]) && strlen($p['contains2'][$i]) > 0 && !empty($p['itemtype2'][$i]) && (!isset($p['link2'][$i]) || !strstr($p['link2'][$i], "NOT"))) { if (!isset($already_printed[$p['itemtype2'][$i] . $p['field2'][$i]])) { $nbcols++; $already_printed[$p['itemtype2'][$i] . $p['field2'][$i]] = 1; } } } } if ($output_type == Search::HTML_OUTPUT) { // HTML display - massive modif $nbcols++; } // Define begin and end var for loop // Search case $begin_display = $p['start']; $end_display = $p['start'] + $LIST_LIMIT; // No search Case if ($nosearch) { $begin_display = 0; $end_display = min($numrows - $p['start'], $LIST_LIMIT); } // Export All case if ($p['export_all']) { $begin_display = 0; $end_display = $numrows; } // Display List Header echo PluginMobileSearch::showHeader($output_type, $end_display - $begin_display + 1, $nbcols); // New Line for Header Items Line echo self::showNewLine($output_type); $header_num = 1; if ($output_type == Search::HTML_OUTPUT) { // HTML display - massive modif $search_config = ""; echo PluginMobileSearch::showHeaderItem($output_type, $search_config, $header_num, "", 0, $p['order']); } if ($p['showheader']) { // Display column Headers for toview items echo "<div data-type='horizontal' data-role='controlgroup' class='mobile_list_header'>"; $cpt = 0; foreach ($toview as $key => $val) { $linkto = ''; if (!isset($searchopt[$itemtype][$val]['nosort']) || !$searchopt[$itemtype][$val]['nosort']) { /*$linkto = "$target?itemtype=$itemtype&sort=".$val."&order=".($p['order']=="ASC"?"DESC":"ASC"). "&start=".$p['start'].$globallinkto;*/ $linkto = "search.php?itemtype={$itemtype}&menu=" . $_GET['menu'] . "&ssmenu=" . $_GET['ssmenu'] . "&sort=" . $val . "&order=" . ($p['order'] == "ASC" ? "DESC" : "ASC") . "&start=" . $p['start'] . $globallinkto; } echo PluginMobileSearch::showHeaderItem($output_type, $searchopt[$itemtype][$val]["name"], $header_num, $linkto, $p['sort'] == $val, $p['order']); $cpt++; if ($cpt == $_SESSION['plugin_mobile']['cols_limit']) { break; } } echo "<a href='searchconfig.php?type=global&itemtype={$itemtype}&rand=" . mt_rand() . "' data-icon='plus'\n data-role='button' class='button-header'> </a>"; echo "</div>"; // Display columns Headers for meta items $already_printed = array(); if ($_SESSION["glpisearchcount2"][$itemtype] > 0 && is_array($p['itemtype2'])) { for ($i = 0; $i < $_SESSION["glpisearchcount2"][$itemtype]; $i++) { if (isset($p['itemtype2'][$i]) && !empty($p['itemtype2'][$i]) && isset($p['contains2'][$i]) && strlen($p['contains2'][$i]) > 0) { if (!isset($already_printed[$p['itemtype2'][$i] . $p['field2'][$i]])) { if (!isset($metanames[$p['itemtype2'][$i]])) { $metaitem = new $p['itemtype2'][$i](); echo PluginMobileSearch::showHeaderItem($output_type, $metanames[$p['itemtype2'][$i]] . " - " . $searchopt[$p['itemtype2'][$i]][$p['field2'][$i]]["name"], $header_num); $already_printed[$p['itemtype2'][$i] . $p['field2'][$i]] = 1; } } } } } // End Line for column headers echo PluginMobileSearch::showEndLine($output_type); } // if real search seek to begin of items to display (because of complete search) if (!$nosearch) { $DB->data_seek($result, $p['start']); } // Define begin and end var for loop // Search case $i = $begin_display; // Init list of items displayed if ($output_type == Search::HTML_OUTPUT) { Session::initNavigateListItems($itemtype); } // Num of the row (1=header_line) $row_num = 1; // Display Loop while ($i < $numrows && $i < $end_display) { // Column num $item_num = 1; // Get data and increment loop variables $data = $DBread->fetch_assoc($result); $i++; $row_num++; // New line // Add item in item list Session::addToNavigateListItems($itemtype, $data["id"]); /*if ($output_type==Search::HTML_OUTPUT) { // HTML display - massive modif $tmpcheck=""; if ($isadmin) { if ($itemtype == 'Entity' && !in_array($data["id"],$_SESSION["glpiactiveentities"])) { $tmpcheck=" "; } else if ($item->maybeRecursive() && !in_array($data["entities_id"],$_SESSION["glpiactiveentities"])) { $tmpcheck=" "; } else { $sel=""; if (isset($_GET["select"]) && $_GET["select"]=="all") { $sel="checked"; } if (isset($_SESSION['glpimassiveactionselected'][$data["id"]])) { $sel="checked"; } $tmpcheck="<input type='checkbox' name='item[".$data["id"]."]' value='1' $sel>"; } } echo PluginMobileSearch::showItem($output_type,$tmpcheck,$item_num,$row_num,"width='10'"); }*/ // Print other toview items $itemsToShow = array(); $cpt = 0; foreach ($toview as $key => $val) { $itemsToShow[] = PluginMobileSearch::showItem($output_type, PluginMobileSearch::giveItem($itemtype, $val, $data, $key), $item_num, $row_num, self::displayConfigItem($itemtype, $val, $data, $key)); $cpt++; if ($cpt == $_SESSION['plugin_mobile']['cols_limit']) { break; } } // Print Meta Item if ($_SESSION["glpisearchcount2"][$itemtype] > 0 && is_array($p['itemtype2'])) { for ($j = 0; $j < $_SESSION["glpisearchcount2"][$itemtype]; $j++) { if (isset($p['itemtype2'][$j]) && !empty($p['itemtype2'][$j]) && isset($p['contains2'][$j]) && strlen($p['contains2'][$j]) > 0) { // General case if (strpos($data["META_{$j}"], "\$\$\$\$") === false) { $out = self::giveItem($p['itemtype2'][$j], $p['field2'][$j], $data, $j, 1); $itemsToShow[] = PluginMobileSearch::showItem($output_type, $out, $item_num, $row_num); // Case of GROUP_CONCAT item : split item and multilline display } else { $split = explode("\$\$\$\$", $data["META_{$j}"]); $count_display = 0; $out = ""; $unit = ""; $separate = '<br>'; if (isset($searchopt[$p['itemtype2'][$j]][$p['field2'][$j]]['splititems']) && $searchopt[$p['itemtype2'][$j]][$p['field2'][$j]]['splititems']) { $separate = '<hr>'; } if (isset($searchopt[$p['itemtype2'][$j]][$p['field2'][$j]]['unit'])) { $unit = $searchopt[$p['itemtype2'][$j]][$p['field2'][$j]]['unit']; } for ($k = 0; $k < count($split); $k++) { if ($p['contains2'][$j] == "NULL" || strlen($p['contains2'][$j]) == 0 || preg_match('/' . $p['contains2'][$j] . '/i', $split[$k]) || isset($searchopt[$p['itemtype2'][$j]][$p['field2'][$j]]['forcegroupby'])) { if ($count_display) { $out .= $separate; } $count_display++; // Manage Link to item $split2 = explode("\$\$", $split[$k]); if (isset($split2[1])) { $out .= "<a href=\"" . getItemTypeFormURLMobile($p['itemtype2'][$j]) . "?id=" . $split2[1] . "\" data-back='false'>"; $out .= $split2[0] . $unit; if ($_SESSION["glpiis_ids_visible"] || empty($split2[0])) { $out .= " (" . $split2[1] . ")"; } $out .= "</a>"; } else { $out .= $split[$k] . $unit; } } } $itemsToShow[] = PluginMobileSearch::showItem($output_type, $out, $item_num, $row_num); } } } } // Specific column display if ($itemtype == 'CartridgeItem') { $itemsToShow[] = PluginMobileSearch::showItem($output_type, Cartridge::getCount($data["id"], $data["ALARM"], $output_type), $item_num, $row_num); } if ($itemtype == 'ConsumableItem') { $itemsToShow[] = PluginMobileSearch::showItem($output_type, Consumable::getCount($data["id"], $data["ALARM"], $output_type), $item_num, $row_num); } if ($itemtype == 'States' || $itemtype == 'ReservationItem') { $typename = $data["TYPE"]; if (class_exists($data["TYPE"])) { $itemtmp = new $data["TYPE"](); $typename = $itemtmp->getTypeName(); } $itemsToShow[] = PluginMobileSearch::showItem($output_type, $typename, $item_num, $row_num); } if ($itemtype == 'ReservationItem' && $output_type == Search::HTML_OUTPUT) { if (Session::haveRight("reservation_central", UPDATE)) { if (!haveAccessToEntity($data["ENTITY"])) { $itemsToShow[] = PluginMobileSearch::showItem($output_type, " ", $item_num, $row_num); $itemsToShow[] = PluginMobileSearch::showItem($output_type, " ", $item_num, $row_num); } else { $itemsToShow[] = PluginMobileSearch::showItem($output_type, "<a href=\"" . getItemTypeFormURLMobile($itemtype) . "?id=" . $data["refID"] . "&is_active=" . ($data["ACTIVE"] ? 0 : 1) . "&update=update\" " . "title='" . ($data["ACTIVE"] ? $LANG['buttons'][42] : $LANG['buttons'][41]) . "' data-back='false'><img src=\"" . $CFG_GLPI["root_doc"] . "/pics/" . ($data["ACTIVE"] ? "moins" : "plus") . ".png\" alt='' title=''></a>", $item_num, $row_num, "class='center'"); /*echo PluginMobileSearch::showItem($output_type,"<a href=\"javascript:confirmAction('". addslashes($LANG['reservation'][38])."\\n". addslashes($LANG['reservation'][39])."','". Toolbox::getItemTypeFormURL($itemtype)."?id=".$data["refID"]. "&delete=delete')\" title='". $LANG['reservation'][6]."'><img src=\"". $CFG_GLPI["root_doc"]."/pics/delete.png\" alt='' title=''></a>", $item_num,$row_num,"class='center'");*/ } } if ($data["ACTIVE"]) { $itemsToShow[] = PluginMobileSearch::showItem($output_type, "<a href='reservation.php?reservationitems_id=" . $data["refID"] . "' title='" . $LANG['reservation'][21] . "' data-back='false'><img src=\"" . $CFG_GLPI["root_doc"] . "/pics/reservation-3.png\" alt='' title=''></a>", $item_num, $row_num, "class='center'"); } else { $itemsToShow[] = PluginMobileSearch::showItem($output_type, " ", $item_num, $row_num); } } echo PluginMobileSearch::showNewLine($output_type, $i % 2); foreach ($itemsToShow as $item) { echo $item; } // End Line echo PluginMobileSearch::showEndLine($output_type); } $title = ""; // Create title if ($output_type == Search::PDF_OUTPUT_LANDSCAPE || $output_type == Search::PDF_OUTPUT_PORTRAIT) { if ($_SESSION["glpisearchcount"][$itemtype] > 0 && count($p['contains']) > 0) { for ($key = 0; $key < $_SESSION["glpisearchcount"][$itemtype]; $key++) { if (strlen($p['contains'][$key]) > 0) { if (isset($p["link"][$key])) { $title .= " " . $p["link"][$key] . " "; } switch ($p['field'][$key]) { case "all": $title .= $LANG['common'][66]; break; case "view": $title .= $LANG['search'][11]; break; default: $title .= $searchopt[$itemtype][$p['field'][$key]]["name"]; } $title .= " = " . $p['contains'][$key]; } } } if ($_SESSION["glpisearchcount2"][$itemtype] > 0 && count($p['contains2']) > 0) { for ($key = 0; $key < $_SESSION["glpisearchcount2"][$itemtype]; $key++) { if (strlen($p['contains2'][$key]) > 0) { if (isset($p['link2'][$key])) { $title .= " " . $p['link2'][$key] . " "; } $title .= $metanames[$p['itemtype2'][$key]] . "/"; $title .= $searchopt[$p['itemtype2'][$key]][$p['field2'][$key]]["name"]; $title .= " = " . $p['contains2'][$key]; } } } } // Display footer echo PluginMobileSearch::showFooter($output_type, $title); // Delete selected item if ($output_type == Search::HTML_OUTPUT) { if ($isadmin) { openArrowMassives("massiveaction_form"); Dropdown::showForMassiveAction($itemtype, $p['is_deleted']); closeArrowMassives(); // End form for delete item //echo "</form>\n"; Html::closeForm(); } else { echo "<br>"; } } } else { echo Search::showError($output_type); } } else { echo $DBread > error(); } // Clean selection $_SESSION['glpimassiveactionselected'] = array(); //echo $QUERY; return $numrows; }
$cartridge->showCompatiblePrinters(); Cartridge::showAddForm($cartridge); Cartridge::showForCartridgeItem($cartridge); Cartridge::showForCartridgeItem($cartridge, 1); Infocom::showForItem($cartridge); Document::showAssociated($cartridge); Link::showForItem('CartridgeItem', $_POST["id"]); Plugin::displayAction($cartridge, $_REQUEST['glpi_tab']); break; case 4: Infocom::showForItem($cartridge); break; case 5: Document::showAssociated($cartridge); break; case 7: Link::showForItem('CartridgeItem', $_POST["id"]); break; case 10: showNotesForm($_POST['target'], 'CartridgeItem', $_POST["id"]); break; default: if (!Plugin::displayAction($cartridge, $_REQUEST['glpi_tab'])) { $cartridge->showCompatiblePrinters(); Cartridge::showAddForm($cartridge); Cartridge::showForCartridgeItem($cartridge); Cartridge::showForCartridgeItem($cartridge, 1); } } } ajaxFooter();
case 4: Infocom::showForItem($printer); Contract::showAssociated($printer); break; case 5: Document::showAssociated($printer); break; case 6: Ticket::showListForItem('Printer', $_POST["id"]); break; case 7: Link::showForItem('Printer', $_POST["id"]); break; case 10: showNotesForm($_POST['target'], 'Printer', $_POST["id"]); break; case 11: Reservation::showForItem('Printer', $_POST["id"]); break; case 12: Log::showForItem($printer); break; default: if (!Plugin::displayAction($printer, $_REQUEST['glpi_tab'])) { Cartridge::showInstalled($printer); Cartridge::showInstalled($printer, 1); } } } } ajaxFooter();
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -------------------------------------------------------------------------- */ // ---------------------------------------------------------------------- // Original Author of file: Julien Dombre // Purpose of file: // ---------------------------------------------------------------------- define('GLPI_ROOT', '..'); include GLPI_ROOT . "/inc/includes.php"; if (!isset($_GET["tID"])) { $_GET["tID"] = ""; } if (!isset($_GET["cID"])) { $_GET["cID"] = ""; } $cart = new Cartridge(); $cartype = new CartridgeItem(); if (isset($_POST["update_pages"]) || isset($_POST["update_pages_x"])) { $cart->check($_POST["cID"], 'w'); if ($cart->updatePages($_POST['pages'])) { Event::log(0, "cartridges", 4, "inventory", $_SESSION["glpiname"] . " " . $LANG['log'][94]); } glpi_header($_SERVER['HTTP_REFERER']); } else { if (isset($_POST["add_several"])) { $cartype->check($_POST["tID"], 'w'); for ($i = 0; $i < $_POST["to_add"]; $i++) { unset($cart->fields["id"]); $cart->add($_POST); } Event::log($_POST["tID"], "cartridges", 4, "inventory", $_SESSION["glpiname"] . " " . $LANG['log'][88] . ": " . $_POST["to_add"]);