substr() static public method

substr function for utf8 string
static public substr ( $str, $start, $length ) : substring
$str string
$start integer start of the result substring
$length integer The maximum length of the returned string if > 0 (default -1)
return substring
 static function giveItem($itemtype, $ID, array $data, $num, $meta = 0, array $addobjectparams = array())
 {
     global $CFG_GLPI, $LANG, $PLUGIN_HOOKS;
     $searchopt =& Search::getOptions($itemtype);
     if (isset($CFG_GLPI["union_search_type"][$itemtype]) && $CFG_GLPI["union_search_type"][$itemtype] == $searchopt[$ID]["table"]) {
         return PluginMobileSearch::giveItem($data["TYPE"], $ID, $data, $num, $meta);
     }
     // Plugin can override core definition for its type
     if ($plug = isPluginItemType($itemtype)) {
         $function = 'plugin_' . $plug['plugin'] . '_giveItem';
         if (function_exists($function)) {
             $out = $function($itemtype, $ID, $data, $num);
             if (!empty($out)) {
                 return $out;
             }
         }
     }
     $NAME = "ITEM_";
     if ($meta) {
         $NAME = "META_";
     }
     $table = $searchopt[$ID]["table"];
     $field = $searchopt[$ID]["field"];
     $linkfield = $searchopt[$ID]["linkfield"];
     switch ($table . '.' . $field) {
         case "glpi_users_validation.name":
         case "glpi_users.name":
             // USER search case
             if ($itemtype != 'User' && isset($searchopt[$ID]["forcegroupby"]) && $searchopt[$ID]["forcegroupby"]) {
                 $out = "";
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $count_display = 0;
                 $added = array();
                 for ($k = 0; $k < count($split); $k++) {
                     if ($split[$k] > 0) {
                         if ($count_display) {
                             $out .= "<br>";
                         }
                         $count_display++;
                         if ($itemtype == 'Ticket') {
                             $userdata = getUserNameMobile($split[$k], 2);
                             $out .= $userdata['name'] . "&nbsp;";
                         } else {
                             $out .= getUserNameMobile($split[$k], 1);
                         }
                     }
                 }
                 return $out;
             } else {
                 if (!empty($linkfield)) {
                     $toadd = '';
                     if ($itemtype == 'Ticket' && $data[$NAME . $num . "_3"] > 0) {
                         $userdata = getUserNameMobile($data[$NAME . $num . "_3"], 2);
                         $toadd = "&nbsp;";
                     }
                     //Stevenes
                     $name1 = explode("\$\$", $data[$NAME . $num]);
                     //	return $name1['0'].' ('.$name1['1'].')';
                     $link_user = $_SESSION['mobileSearchLastLink'] = "<a href=" . $CFG_GLPI["root_doc"] . "/plugins/mobile/front/item.php?itemtype=user&menu=admin&ssmenu=user&id=" . $name1['1'] . ">" . $name1['0'] . " (" . $name1['1'] . ")</a>";
                     return $link_user;
                     // return formatUserNameMobile($data[$NAME.$num."_3"],$data[$NAME.$num],$data[$NAME.$num."_2"], $data[$NAME.$num."_4"],1).$toadd;
                 }
             }
             break;
         case "glpi_profiles.interface":
             return Profile::getInterfaceName($data[$NAME . $num]);
             break;
         case "glpi_profiles.name":
             if ($itemtype == 'User') {
                 $out = "";
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $split2 = explode("\$\$\$\$", $data[$NAME . $num . "_2"]);
                 $split3 = explode("\$\$\$\$", $data[$NAME . $num . "_3"]);
                 $count_display = 0;
                 $added = array();
                 for ($k = 0; $k < count($split); $k++) {
                     if (strlen(trim($split[$k])) > 0) {
                         $text = $split[$k] . " - " . $split2[$k];
                         if ($split3[$k]) {
                             $text .= " (R)";
                         }
                         if (!in_array($text, $added)) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= $text;
                             $added[] = $text;
                         }
                     }
                 }
                 return $out;
             }
             break;
         case "glpi_entities.completename":
             if ($itemtype == 'User') {
                 $out = "";
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $split2 = explode("\$\$\$\$", $data[$NAME . $num . "_2"]);
                 $split3 = explode("\$\$\$\$", $data[$NAME . $num . "_3"]);
                 $added = array();
                 $count_display = 0;
                 for ($k = 0; $k < count($split); $k++) {
                     if (strlen(trim($split[$k])) > 0) {
                         $text = $split[$k] . " - " . $split2[$k];
                         if ($split3[$k]) {
                             $text .= " (R)";
                         }
                         if (!in_array($text, $added)) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= $text;
                             $added[] = $text;
                         }
                     }
                 }
                 return $out;
             } else {
                 if ($data[$NAME . $num . "_2"] == 0) {
                     // Set name for Root entity
                     $data[$NAME . $num] = $LANG['entity'][2];
                 }
             }
             break;
         case "glpi_documenttypes.icon":
             if (!empty($data[$NAME . $num])) {
                 return "<img class='middle' alt='' src='" . $CFG_GLPI["typedoc_icon_dir"] . "/" . $data[$NAME . $num] . "'>";
             }
             return "&nbsp;";
         case "glpi_documents.filename":
             $doc = new Document();
             if ($doc->getFromDB($data['id'])) {
                 return $doc->getDownloadLink();
             }
             return NOT_AVAILABLE;
         case "glpi_deviceharddrives.specificity":
         case "glpi_devicememories.specificity":
         case "glpi_deviceprocessors.specificity":
             return $data[$NAME . $num];
         case "glpi_networkports.mac":
             $out = "";
             if ($itemtype == 'Computer') {
                 $displayed = array();
                 if (!empty($data[$NAME . $num . "_2"])) {
                     $split = explode("\$\$\$\$", $data[$NAME . $num . "_2"]);
                     $count_display = 0;
                     for ($k = 0; $k < count($split); $k++) {
                         $lowstr = utf8_strtolower($split[$k]);
                         if (strlen(trim($split[$k])) > 0 && !in_array($lowstr, $displayed)) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= $split[$k];
                             $displayed[] = $lowstr;
                         }
                     }
                     if (!empty($data[$NAME . $num])) {
                         $out .= "<br>";
                     }
                 }
                 if (!empty($data[$NAME . $num])) {
                     $split = explode("\$\$\$\$", $data[$NAME . $num]);
                     $count_display = 0;
                     for ($k = 0; $k < count($split); $k++) {
                         $lowstr = utf8_strtolower($split[$k]);
                         if (strlen(trim($split[$k])) > 0 && !in_array($lowstr, $displayed)) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= $split[$k];
                             $displayed[] = $lowstr;
                         }
                     }
                 }
                 return $out;
             }
             break;
         case "glpi_contracts.duration":
         case "glpi_contracts.notice":
         case "glpi_contracts.periodicity":
         case "glpi_contracts.billing":
             if (!empty($data[$NAME . $num])) {
                 $split = explode('$$$$', $data[$NAME . $num]);
                 $output = "";
                 foreach ($split as $duration) {
                     $output .= (empty($output) ? '' : '<br>') . $duration . " " . $LANG['financial'][57];
                 }
                 return $output;
             }
             return "&nbsp;";
         case "glpi_contracts.renewal":
             return Contract::getContractRenewalName($data[$NAME . $num]);
         case "glpi_infocoms.sink_time":
             if (!empty($data[$NAME . $num])) {
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $out = '';
                 foreach ($split as $val) {
                     $out .= empty($out) ? '' : '<br>';
                     if ($val > 0) {
                         $out .= $val . " " . $LANG['financial'][9];
                     }
                 }
                 return $out;
             }
             return "&nbsp;";
         case "glpi_infocoms.warranty_duration":
             if (!empty($data[$NAME . $num])) {
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $out = '';
                 foreach ($split as $val) {
                     $out .= empty($out) ? '' : '<br>';
                     if ($val > 0) {
                         $out .= $val . " " . $LANG['financial'][57];
                     }
                     if ($val < 0) {
                         $out .= $LANG['financial'][2];
                     }
                 }
                 return $out;
             }
             return "&nbsp;";
         case "glpi_infocoms.sink_type":
             $split = explode("\$\$\$\$", $data[$NAME . $num]);
             $out = '';
             foreach ($split as $val) {
                 $out .= (empty($out) ? '' : '<br>') . Infocom::getAmortTypeName($val);
             }
             return $out;
         case "glpi_infocoms.alert":
             if ($data[$NAME . $num] == pow(2, Alert::END)) {
                 return $LANG['financial'][80];
             }
             return "";
         case "glpi_contracts.alert":
             switch ($data[$NAME . $num]) {
                 case pow(2, Alert::END):
                     return $LANG['buttons'][32];
                 case pow(2, Alert::NOTICE):
                     return $LANG['financial'][10];
                 case pow(2, Alert::END) + pow(2, Alert::NOTICE):
                     return $LANG['buttons'][32] . " + " . $LANG['financial'][10];
             }
             return "";
         case "glpi_tickets.count":
             if ($data[$NAME . $num] > 0 && Session::haveRight("ticket", Ticket::READALL)) {
                 $options['field'][0] = 12;
                 $options['searchtype'][0] = 'equals';
                 $options['contains'][0] = 'all';
                 $options['link'][0] = 'AND';
                 $options['itemtype2'][0] = $itemtype;
                 $options['field2'][0] = self::getOptionNumber($itemtype, 'name');
                 $options['searchtype2'][0] = 'equals';
                 $options['contains2'][0] = $data['id'];
                 $options['link2'][0] = 'AND';
                 $options['reset'] = 'reset';
                 $out = "<a href=\"" . $CFG_GLPI["root_doc"] . "/front/ticket.php?" . Toolbox::append_params($options) . "\" data-back='false'>";
                 $out .= $data[$NAME . $num];
                 $out .= "</a>";
             } else {
                 $out = $data[$NAME . $num];
             }
             return $out;
         case "glpi_softwarelicenses.number":
             if ($data[$NAME . $num . "_2"] == -1) {
                 return $LANG['software'][4];
             }
             if (empty($data[$NAME . $num])) {
                 return 0;
             }
             return $data[$NAME . $num];
         case "glpi_auth_tables.name":
             return Auth::getMethodName($data[$NAME . $num], $data[$NAME . $num . "_2"], 1, $data[$NAME . $num . "_3"] . $data[$NAME . $num . "_4"]);
         case "glpi_reservationitems.comment":
             if (empty($data[$NAME . $num])) {
                 return "<a title='" . $LANG['reservation'][22] . "'\n                        href='" . $CFG_GLPI["root_doc"] . "/front/reservationitem.form.php?id=" . $data["refID"] . "' data-back='false'>" . $LANG['common'][49] . "</a>";
             }
             return "<a title='" . $LANG['reservation'][22] . "'\n                     href='" . $CFG_GLPI["root_doc"] . "/front/reservationitem.form.php?id=" . $data['refID'] . "' data-back='false'>" . resume_text($data[$NAME . $num]) . "</a>";
         case 'glpi_notifications.mode':
             return Notification::getMode($data[$NAME . $num]);
         case 'glpi_notifications.event':
             $item = NotificationTarget::getInstanceByType($data['itemtype']);
             if ($item) {
                 $events = $item->getAllEvents();
                 return $events[$data[$NAME . $num]];
             }
             return '';
         case 'glpi_crontasks.description':
             $tmp = new CronTask();
             return $tmp->getDescription($data['id']);
         case 'glpi_crontasks.state':
             return CronTask::getStateName($data[$NAME . $num]);
         case 'glpi_crontasks.mode':
             return CronTask::getModeName($data[$NAME . $num]);
         case 'glpi_crontasks.itemtype':
             if ($plug = isPluginItemType($data[$NAME . $num])) {
                 return $plug['plugin'];
             }
             return '';
         case 'glpi_tickets.status':
             $status = Ticket::getStatus($data[$NAME . $num]);
             // status Stevenes Donato
             if ($data[$NAME . $num] == "1") {
                 $data[$NAME . $num] = "new";
             }
             if ($data[$NAME . $num] == "2") {
                 $data[$NAME . $num] = "assign";
             }
             if ($data[$NAME . $num] == "3") {
                 $data[$NAME . $num] = "plan";
             }
             if ($data[$NAME . $num] == "4") {
                 $data[$NAME . $num] = "waiting";
             }
             if ($data[$NAME . $num] == "5") {
                 $data[$NAME . $num] = "solved";
             }
             if ($data[$NAME . $num] == "6") {
                 $data[$NAME . $num] = "closed";
             }
             //
             return "<img src=\"" . $CFG_GLPI["root_doc"] . "/pics/" . $data[$NAME . $num] . ".png\"\n                        alt='{$status}' title='{$status}'>&nbsp;{$status}";
         case 'glpi_tickets.priority':
             return Ticket::getPriorityName($data[$NAME . $num]);
         case 'glpi_tickets.urgency':
             return Ticket::getUrgencyName($data[$NAME . $num]);
         case 'glpi_tickets.impact':
             return Ticket::getImpactName($data[$NAME . $num]);
         case 'glpi_tickets.items_id':
             if (!empty($data[$NAME . $num . "_2"]) && class_exists($data[$NAME . $num . "_2"])) {
                 $item = new $data[$NAME . $num . "_2"]();
                 if ($item->getFromDB($data[$NAME . $num])) {
                     return $item->getLink(true);
                 }
             }
             return '&nbsp;';
         case 'glpi_tickets.id':
             $link = getItemTypeFormURLMobile('Ticket');
             $out = "<a id='ticket" . $data[$NAME . $num . "_2"] . "' href=\"" . $link;
             $out .= strstr($link, '?') ? '&amp;' : '?';
             $out .= 'id=' . $data[$NAME . $num];
             //$out .= 'id='.$data[$NAME.$num."_2"];
             $out .= "\" data-back='false'>" . $data[$NAME . $num];
             if ($_SESSION["glpiis_ids_visible"] || empty($data[$NAME . $num])) {
                 //$out .= " (".$data[$NAME.$num."_2"].")";
                 $out .= $data[$NAME . $num . "_2"];
             }
             $out .= "</a>";
             return $out;
         case 'glpi_ticketvalidations.status':
         case "glpi_tickets.global_validation":
             $split = explode("\$\$\$\$", $data[$NAME . $num]);
             $out = '';
             foreach ($split as $val) {
                 $status = TicketValidation::getStatus($val);
                 $bgcolor = TicketValidation::getStatusColor($val);
                 $out .= (empty($out) ? '' : '<br>') . "<div style=\"background-color:" . $bgcolor . ";\">" . $status . '</div>';
             }
             return $out;
         case 'glpi_notimportedemails.reason':
             return NotImportedEmail::getReason($data[$NAME . $num]);
         case 'glpi_notimportedemails.messageid':
             $clean = array('<' => '', '>' => '');
             return strtr($data[$NAME . $num], $clean);
     }
     //// Default case
     // Link with plugin tables : need to know left join structure
     if (preg_match("/^glpi_plugin_([a-z0-9]+)/", $table . '.' . $field, $matches)) {
         if (count($matches) == 2) {
             $plug = $matches[1];
             $function = 'plugin_' . $plug . '_giveItem';
             if (function_exists($function)) {
                 $out = $function($itemtype, $ID, $data, $num);
                 if (!empty($out)) {
                     return $out;
                 }
             }
         }
     }
     $unit = '';
     if (isset($searchopt[$ID]['unit'])) {
         $unit = $searchopt[$ID]['unit'];
     }
     // Preformat items
     if (isset($searchopt[$ID]["datatype"])) {
         switch ($searchopt[$ID]["datatype"]) {
             case "itemlink":
                 if (!empty($data[$NAME . $num . "_2"])) {
                     if (isset($searchopt[$ID]["itemlink_type"])) {
                         $link = getItemTypeFormURLMobile($searchopt[$ID]["itemlink_type"]);
                     } else {
                         $link = getItemTypeFormURLMobile($itemtype);
                     }
                     $out = "<a id='" . $itemtype . "_" . $data[$NAME . $num . "_2"] . "' href=\"" . $link;
                     $out .= strstr($link, '?') ? '&amp;' : '?';
                     $out .= 'id=' . $data[$NAME . $num . "_2"] . "\" data-back='false'>";
                     $out .= $data[$NAME . $num] . $unit;
                     if ($_SESSION["glpiis_ids_visible"] || empty($data[$NAME . $num])) {
                         $out .= " (" . $data[$NAME . $num . "_2"] . ")";
                     }
                     $out .= "</a>";
                     return $out;
                 } else {
                     if (isset($searchopt[$ID]["itemlink_type"])) {
                         $out = "";
                         $split = explode("\$\$\$\$", $data[$NAME . $num]);
                         $count_display = 0;
                         $separate = '<br>';
                         if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) {
                             $separate = '<hr>';
                         }
                         for ($k = 0; $k < count($split); $k++) {
                             if (strlen(trim($split[$k])) > 0) {
                                 $split2 = explode("\$\$", $split[$k]);
                                 if (isset($split2[1]) && $split2[1] > 0) {
                                     if ($count_display) {
                                         $out .= $separate;
                                     }
                                     $count_display++;
                                     $page = getItemTypeFormURLMobile($searchopt[$ID]["itemlink_type"]);
                                     $page .= strpos($page, '?') ? '&id' : '?id';
                                     $out .= "<a id='" . $searchopt[$ID]["itemlink_type"] . "_" . $split2[1] . "'\n                                       href='{$page}=" . $split2[1] . "' data-back='false'>";
                                     $out .= $split2[0] . $unit;
                                     if ($_SESSION["glpiis_ids_visible"] || empty($split2[0])) {
                                         $out .= " (" . $split2[1] . ")";
                                     }
                                     $out .= "</a>";
                                 }
                             }
                         }
                         return $out;
                     }
                 }
                 break;
             case "text":
                 $separate = '<br>';
                 if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) {
                     $separate = '<hr>';
                 }
                 return str_replace('$$$$', $separate, nl2br($data[$NAME . $num]));
             case "date":
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $out = '';
                 foreach ($split as $val) {
                     $out .= (empty($out) ? '' : '<br>') . convDate($val);
                 }
                 return $out;
             case "datetime":
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $out = '';
                 foreach ($split as $val) {
                     $out .= (empty($out) ? '' : '<br>') . Html::convDateTime($val);
                 }
                 return $out;
             case "timestamp":
                 return timestampToString($data[$NAME . $num]);
             case "realtime":
                 return Ticket::getRealtime($data[$NAME . $num]);
             case "date_delay":
                 $split = explode('$$$$', $data[$NAME . $num]);
                 $out = '';
                 foreach ($split as $val) {
                     if (strpos($val, ',')) {
                         list($dat, $dur) = explode(',', $val);
                         if (!empty($dat)) {
                             $out .= (empty($out) ? '' : '<br>') . getWarrantyExpir($dat, $dur);
                         }
                     }
                 }
                 return empty($out) ? "&nbsp;" : $out;
             case "email":
                 // Stevenes
                 //               $email=trim($data[$NAME.$num]);
                 $email = explode('$$', $data[$NAME . $num]);
                 if (!empty($email['0'])) {
                     return $email['0'];
                     //return "<a href='mailto:$email'>$email</a>";
                 }
                 return "&nbsp;";
             case "weblink":
                 $orig_link = trim($data[$NAME . $num]);
                 if (!empty($orig_link)) {
                     // strip begin of link
                     $link = preg_replace('/https?:\\/\\/(www[^\\.]*\\.)?/', '', $orig_link);
                     $link = preg_replace('/\\/$/', '', $link);
                     if (utf8_strlen($link) > 30) {
                         $link = Toolbox::substr($link, 0, 30) . "...";
                     }
                     //return "<a href=\"".formatOutputWebLink($orig_link)."\" target='_blank'>$link</a>";
                     return $orig_link;
                 }
                 return "&nbsp;";
             case "number":
                 if (isset($searchopt[$ID]['forcegroupby']) && $searchopt[$ID]['forcegroupby']) {
                     $out = "";
                     $split = explode("\$\$\$\$", $data[$NAME . $num]);
                     $count_display = 0;
                     for ($k = 0; $k < count($split); $k++) {
                         if (strlen(trim($split[$k])) > 0) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= str_replace(' ', '&nbsp;', Html::formatNumber($split[$k], false, 0)) . $unit;
                         }
                     }
                     return $out;
                 }
                 return str_replace(' ', '&nbsp;', Html::formatNumber($data[$NAME . $num], false, 0)) . $unit;
             case "decimal":
                 if (isset($searchopt[$ID]['forcegroupby']) && $searchopt[$ID]['forcegroupby']) {
                     $out = "";
                     $split = explode("\$\$\$\$", $data[$NAME . $num]);
                     $count_display = 0;
                     for ($k = 0; $k < count($split); $k++) {
                         if (strlen(trim($split[$k])) > 0) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= str_replace(' ', '&nbsp;', Html::formatNumber($split[$k])) . $unit;
                         }
                     }
                     return $out;
                 }
                 return str_replace(' ', '&nbsp;', Html::formatNumber($data[$NAME . $num])) . $unit;
             case "bool":
                 return Dropdown::getYesNo($data[$NAME . $num]) . $unit;
             case "right":
                 return Profile::getRightValue($data[$NAME . $num]);
             case "itemtypename":
                 if (class_exists($data[$NAME . $num])) {
                     $obj = new $data[$NAME . $num]();
                     return $obj->getTypeName();
                 } else {
                     return "";
                 }
             case "language":
                 if (isset($CFG_GLPI['languages'][$data[$NAME . $num]])) {
                     return $CFG_GLPI['languages'][$data[$NAME . $num]][0];
                 } else {
                     return $LANG['setup'][46];
                 }
                 break;
         }
     }
     // Manage items with need group by / group_concat
     if (isset($searchopt[$ID]['forcegroupby']) && $searchopt[$ID]['forcegroupby']) {
         $out = "";
         $split = explode("\$\$\$\$", $data[$NAME . $num]);
         $count_display = 0;
         $separate = '<br>';
         if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) {
             $separate = '<hr>';
         }
         for ($k = 0; $k < count($split); $k++) {
             if (strlen(trim($split[$k])) > 0) {
                 if ($count_display) {
                     $out .= $separate;
                 }
                 $count_display++;
                 $out .= $split[$k] . $unit;
             }
         }
         return $out;
     }
     return $data[$NAME . $num] . $unit;
 }
Example #2
0
 /**
  * Print pager for search option (first/previous/next/last)
  *
  * @param $start                       from witch item we start
  * @param $numrows                     total items
  * @param $target                      page would be open when click on the option (last,previous etc)
  * @param $parameters                  parameters would be passed on the URL.
  * @param $item_type_output            item type display - if >0 display export PDF et Sylk form
  *                                     (default 0)
  * @param $item_type_output_param      item type parameter for export (default 0)
  * @param $additional_info             Additional information to display (default '')
  *
  * @return nothing (print a pager)
  *
  **/
 static function printPager($start, $numrows, $target, $parameters, $item_type_output = 0, $item_type_output_param = 0, $additional_info = '')
 {
     global $CFG_GLPI;
     $list_limit = $_SESSION['glpilist_limit'];
     // Forward is the next step forward
     $forward = $start + $list_limit;
     // This is the end, my friend
     $end = $numrows - $list_limit;
     // Human readable count starts here
     $current_start = $start + 1;
     // And the human is viewing from start to end
     $current_end = $current_start + $list_limit - 1;
     if ($current_end > $numrows) {
         $current_end = $numrows;
     }
     // Empty case
     if ($current_end == 0) {
         $current_start = 0;
     }
     // Backward browsing
     if ($current_start - $list_limit <= 0) {
         $back = 0;
     } else {
         $back = $start - $list_limit;
     }
     // Print it
     echo "<div><table class='tab_cadre_pager'>";
     echo "<tr>";
     if (strpos($target, '?') == false) {
         $fulltarget = $target . "?" . $parameters;
     } else {
         $fulltarget = $target . "&" . $parameters;
     }
     // Back and fast backward button
     if (!$start == 0) {
         echo "<th class='left'>";
         echo "<a href='{$fulltarget}&amp;start=0'>";
         echo "<img src='" . $CFG_GLPI["root_doc"] . "/pics/first.png' alt=\"" . __s('Start') . "\" title=\"" . __s('Start') . "\" class='pointer'>";
         echo "</a></th>";
         echo "<th class='left'>";
         echo "<a href='{$fulltarget}&amp;start={$back}'>";
         echo "<img src='" . $CFG_GLPI["root_doc"] . "/pics/left.png' alt=\"" . __s('Previous') . "\" title=\"" . __s('Previous') . "\" class='pointer'>";
         echo "</a></th>";
     }
     // Print the "where am I?"
     echo "<td width='31%' class='tab_bg_2'>";
     self::printPagerForm("{$fulltarget}&amp;start={$start}");
     echo "</td>";
     if (!empty($additional_info)) {
         echo "<td class='tab_bg_2'>";
         echo $additional_info;
         echo "</td>";
     }
     if (!empty($item_type_output) && isset($_SESSION["glpiactiveprofile"]) && $_SESSION["glpiactiveprofile"]["interface"] == "central") {
         echo "<td class='tab_bg_2 responsive_hidden' width='30%'>";
         echo "<form method='GET' action='" . $CFG_GLPI["root_doc"] . "/front/report.dynamic.php'\n                target='_blank'>";
         echo Html::hidden('item_type', array('value' => $item_type_output));
         if ($item_type_output_param != 0) {
             echo Html::hidden('item_type_param', array('value' => Toolbox::prepareArrayForInput($item_type_output_param)));
         }
         $split = explode("&amp;", $parameters);
         for ($i = 0; $i < count($split); $i++) {
             $pos = Toolbox::strpos($split[$i], '=');
             $length = Toolbox::strlen($split[$i]);
             echo Html::hidden(Toolbox::substr($split[$i], 0, $pos), array('value' => urldecode(Toolbox::substr($split[$i], $pos + 1))));
         }
         Dropdown::showOutputFormat();
         Html::closeForm();
         echo "</td>";
     }
     echo "<td width='20%' class='tab_bg_2 b'>";
     //TRANS: %1$d, %2$d, %3$d are page numbers
     printf(__('From %1$d to %2$d on %3$d'), $current_start, $current_end, $numrows);
     echo "</td>\n";
     // Forward and fast forward button
     if ($forward < $numrows) {
         echo "<th class='right'>";
         echo "<a href='{$fulltarget}&amp;start={$forward}'>";
         echo "<img src='" . $CFG_GLPI["root_doc"] . "/pics/right.png' alt=\"" . __s('Next') . "\" title=\"" . __s('Next') . "\" class='pointer'>";
         echo "</a></th>\n";
         echo "<th class='right'>";
         echo "<a href='{$fulltarget}&amp;start={$end}'>";
         echo "<img src='" . $CFG_GLPI["root_doc"] . "/pics/last.png' alt=\"" . __s('End') . "\" title=\"" . __s('End') . "\" class='pointer'>";
         echo "</a></th>\n";
     }
     // End pager
     echo "</tr></table></div>";
 }
Example #3
0
 /**
  * Make a select box with all glpi users where select key = name
  *
  * @param $options array of possible options:
  *    - name         : string / name of the select (default is users_id)
  *    - value
  *    - right        : string / limit user who have specific right :
  *                         id -> only current user (default case);
  *                         interface -> central ;
  *                         all -> all users ;
  *                         specific right like show_all_ticket, create_ticket.... (is array passed one of all passed right is needed)
  *    - comments     : boolean / is the comments displayed near the dropdown (default true)
  *    - entity       : integer or array / restrict to a defined entity or array of entities
  *                      (default -1 : no restriction)
  *    - entity_sons  : boolean / if entity restrict specified auto select its sons
  *                      only available if entity is a single value not an array(default false)
  *    - all          : Nobody or All display for none selected
  *                         all=0 (default) -> Nobody
  *                         all=1 -> All
  *                         all=-1-> nothing
  *    - rand         : integer / already computed rand value
  *    - toupdate     : array / Update a specific item on select change on dropdown
  *                      (need value_fieldname, to_update, url
  *                      (see Ajax::updateItemOnSelectEvent for information)
  *                      and may have moreparams)
  *    - used         : array / Already used items ID: not to display in dropdown (default empty)
  *    - ldap_import
  *    - on_change    : string / value to transmit to "onChange"
  *    - display      : boolean / display or get string (default true)
  *
  * @return rand value if displayed / string if not
  **/
 static function dropdown($options = array())
 {
     global $DB, $CFG_GLPI;
     // Default values
     $p['name'] = 'users_id';
     $p['value'] = '';
     $p['right'] = 'id';
     $p['all'] = 0;
     $p['on_change'] = '';
     $p['comments'] = 1;
     $p['entity'] = -1;
     $p['entity_sons'] = false;
     $p['used'] = array();
     $p['ldap_import'] = false;
     $p['toupdate'] = '';
     $p['rand'] = mt_rand();
     $p['display'] = true;
     if (is_array($options) && count($options)) {
         foreach ($options as $key => $val) {
             $p[$key] = $val;
         }
     }
     $output = '';
     if (!($p['entity'] < 0) && $p['entity_sons']) {
         if (is_array($p['entity'])) {
             $output .= "entity_sons options is not available with array of entity";
         } else {
             $p['entity'] = getSonsOf('glpi_entities', $p['entity']);
         }
     }
     // Make a select box with all glpi users
     $use_ajax = false;
     if ($CFG_GLPI["use_ajax"]) {
         $res = self::getSqlSearchResult(true, $p['right'], $p['entity'], $p['value'], $p['used']);
         $nb = $res ? $DB->result($res, 0, "CPT") : 0;
         if ($nb > $CFG_GLPI["ajax_limit_count"]) {
             $use_ajax = true;
         }
     }
     $user = getUserName($p['value'], 2);
     $default_display = "<select id='dropdown_" . $p['name'] . $p['rand'] . "' name='" . $p['name'] . "'>";
     $default_display .= "<option value='" . $p['value'] . "'>";
     $default_display .= Toolbox::substr($user["name"], 0, $_SESSION["glpidropdown_chars_limit"]);
     $default_display .= "</option></select>";
     $view_users = Session::haveRight("user", "r");
     $params = array('searchText' => '__VALUE__', 'value' => $p['value'], 'myname' => $p['name'], 'all' => $p['all'], 'right' => $p['right'], 'comment' => $p['comments'], 'rand' => $p['rand'], 'on_change' => $p['on_change'], 'entity_restrict' => $p['entity'], 'used' => $p['used'], 'update_item' => $p['toupdate']);
     if ($view_users) {
         $params['update_link'] = $view_users;
     }
     $default = "";
     if (!empty($p['value']) && $p['value'] > 0) {
         $default = $default_display;
     } else {
         $default = "<select name='" . $p['name'] . "' id='dropdown_" . $p['name'] . $p['rand'] . "'>";
         if ($p['all']) {
             $default .= "<option value='0'>--" . __('All') . "--</option></select>";
         } else {
             $default .= "<option value='0'>" . Dropdown::EMPTY_VALUE . "</option></select>\n";
         }
     }
     $output .= Ajax::dropdown($use_ajax, "/ajax/dropdownUsers.php", $params, $default, $p['rand'], false);
     // Display comment
     if ($p['comments']) {
         if (!$view_users) {
             $user["link"] = '';
         } else {
             if (empty($user["link"])) {
                 $user["link"] = $CFG_GLPI['root_doc'] . "/front/user.php";
             }
         }
         $output .= Html::showToolTip($user["comment"], array('contentid' => "comment_" . $p['name'] . $p['rand'], 'display' => false, 'link' => $user["link"], 'linkid' => "comment_link_" . $p["name"] . $p['rand']));
     }
     if (Session::haveRight('import_externalauth_users', 'w') && $p['ldap_import'] && Entity::isEntityDirectoryConfigured($_SESSION['glpiactive_entity'])) {
         $output .= "<img alt='' title=\"" . __s('Import a user') . "\" src='" . $CFG_GLPI["root_doc"] . "/pics/add_dropdown.png' style='cursor:pointer; margin-left:2px;'\n                      onClick=\"var w = window.open('" . $CFG_GLPI['root_doc'] . "/front/popup.php?popup=add_ldapuser&amp;rand=" . $p['rand'] . "&amp;entity=" . $_SESSION['glpiactive_entity'] . "' ,'glpipopup', 'height=400, " . "width=1000, top=100, left=100, scrollbars=yes' );w.focus();\">";
     }
     if ($p['display']) {
         echo $output;
         return $p['rand'];
     }
     return $output;
 }
Example #4
0
 /**
  * @param $width
  **/
 function showSystemInformations($width)
 {
     // No need to translate, this part always display in english (for copy/paste to forum)
     echo "\n<tr class='tab_bg_2'><th>Plugins list</th></tr>";
     echo "<tr class='tab_bg_1'><td><pre>\n&nbsp;\n";
     $plug = new Plugin();
     $pluglist = $plug->find("", "name, directory");
     foreach ($pluglist as $plugin) {
         $msg = substr(str_pad($plugin['directory'], 30), 0, 20) . " Name: " . Toolbox::substr(str_pad($plugin['name'], 40), 0, 30) . " Version: " . str_pad($plugin['version'], 10) . " State: ";
         switch ($plugin['state']) {
             case self::ANEW:
                 $msg .= 'New';
                 break;
             case self::ACTIVATED:
                 $msg .= 'Enabled';
                 break;
             case self::NOTINSTALLED:
                 $msg .= 'Not installed';
                 break;
             case self::TOBECONFIGURED:
                 $msg .= 'To be configured';
                 break;
             case self::NOTACTIVATED:
                 $msg .= 'Not activated';
                 break;
             case self::TOBECLEANED:
             default:
                 $msg .= 'To be cleaned';
                 break;
         }
         echo wordwrap("\t" . $msg . "\n", $width, "\n\t\t");
     }
     echo "\n</pre></td></tr>";
 }
Example #5
0
 /**
  * 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 "&nbsp;";
             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, '&amp;') . "\">";
                         $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, '&amp;') . "\">";
                         $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;'>&nbsp;" . $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}\">&nbsp;{$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}\">&nbsp;{$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}\">&nbsp;{$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 '&nbsp;';
             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 '&nbsp;';
             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, '?') ? '&amp;' : '?';
                     $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 .= "&amp;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 "&nbsp;";
                 }
         }
     }
     //// 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) ? "&nbsp;" : $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 "&nbsp;";
             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(' ', '&nbsp;', 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(' ', '&nbsp;', 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);
 }
Example #6
0
 /**
  * Print a select with contracts
  *
  * Print a select named $name with contracts options and selected value $value
  * @param $options   array of possible options:
  *    - name : string / name of the select (default is contracts_id)
  *    - value : integer / preselected value (default 0)
  *    - entity : integer or array / restrict to a defined entity or array of entities
  *                   (default -1 : no restriction)
  *    - entity_sons : boolean / if entity restrict specified auto select its sons
  *                   only available if entity is a single value not an array (default false)
  *    - used : array / Already used items ID: not to display in dropdown (default empty)
  *    - nochecklimit : boolean / disable limit for nomber of device (for supplier, default false)
  *
  * @return Nothing (display)
  **/
 static function dropdown($options = array())
 {
     global $DB;
     //$name,$entity_restrict=-1,$alreadyused=array(),$nochecklimit=false
     $p['name'] = 'contracts_id';
     $p['value'] = '';
     $p['entity'] = '';
     $p['entity_sons'] = false;
     $p['used'] = array();
     $p['nochecklimit'] = false;
     $p['on_change'] = '';
     if (is_array($options) && count($options)) {
         foreach ($options as $key => $val) {
             $p[$key] = $val;
         }
     }
     if (!($p['entity'] < 0) && $p['entity_sons']) {
         if (is_array($p['entity'])) {
             // no translation needed (only for dev)
             echo "entity_sons options is not available with array of entity";
         } else {
             $p['entity'] = getSonsOf('glpi_entities', $p['entity']);
         }
     }
     $entrest = "";
     $idrest = "";
     if ($p['entity'] >= 0) {
         $entrest = getEntitiesRestrictRequest("AND", "glpi_contracts", "entities_id", $p['entity'], true);
     }
     if (count($p['used'])) {
         $idrest = " AND `glpi_contracts`.`id` NOT IN('" . implode("','", $p['used']) . "') ";
     }
     $query = "SELECT `glpi_contracts`.*\n                FROM `glpi_contracts`\n                LEFT JOIN `glpi_entities` ON (`glpi_contracts`.`entities_id` = `glpi_entities`.`id`)\n                WHERE `glpi_contracts`.`is_deleted` = '0' {$entrest} {$idrest}\n                ORDER BY `glpi_entities`.`completename`,\n                         `glpi_contracts`.`name` ASC,\n                         `glpi_contracts`.`begin_date` DESC";
     $result = $DB->query($query);
     echo "<select name='" . $p['name'] . "'";
     if (!empty($p["on_change"])) {
         echo " onChange='" . $p["on_change"] . "'";
     }
     echo '>';
     if ($p['value'] > 0) {
         $output = Dropdown::getDropdownName('glpi_contracts', $p['value']);
         if ($_SESSION["glpiis_ids_visible"]) {
             $output = sprintf(__('%1$s (%2$s)'), $output, $p['value']);
         }
         echo "<option selected value='" . $p['value'] . "'>" . $output . "</option>";
     } else {
         echo "<option value='-1'>" . Dropdown::EMPTY_VALUE . "</option>";
     }
     $prev = -1;
     while ($data = $DB->fetch_assoc($result)) {
         if ($p['nochecklimit'] || $data["max_links_allowed"] == 0 || $data["max_links_allowed"] > countElementsInTable("glpi_contracts_items", "contracts_id\n                                                                     = '" . $data['id'] . "'")) {
             if ($data["entities_id"] != $prev) {
                 if ($prev >= 0) {
                     echo "</optgroup>";
                 }
                 $prev = $data["entities_id"];
                 echo "<optgroup label=\"" . Dropdown::getDropdownName("glpi_entities", $prev) . "\">";
             }
             $name = $data["name"];
             if ($_SESSION["glpiis_ids_visible"] || empty($data["name"])) {
                 $name = sprintf(__('%1$s (%2$s)'), $name, $data["id"]);
             }
             echo "<option  value='" . $data["id"] . "'>";
             $tmp = sprintf(__('%1$s - %2$s'), $name, $data["num"]);
             $tmp = sprintf(__('%1$s - %2$s'), $tmp, Html::convDateTime($data["begin_date"]));
             echo Toolbox::substr($tmp, 0, $_SESSION["glpidropdown_chars_limit"]);
             echo "</option>";
         }
     }
     if ($prev >= 0) {
         echo "</optgroup>";
     }
     echo "</select>";
 }
* @brief
*/
if (strpos($_SERVER['PHP_SELF'], "dropdownSelectSoftware.php")) {
    $AJAX_INCLUDE = 1;
    include '../inc/includes.php';
    header("Content-Type: text/html; charset=UTF-8");
    Html::header_nocache();
}
Session::checkRight("software", "w");
// Make a select box
$rand = mt_rand();
$where = "";
if (strlen($_POST['searchText']) > 0 && $_POST['searchText'] != $CFG_GLPI["ajax_wildcard"]) {
    $where .= " AND `name` " . Search::makeTextSearch($_POST['searchText']) . " ";
}
$where .= getEntitiesRestrictRequest(' AND', 'glpi_softwares', 'entities_id', $_POST["entity_restrict"], true);
$query = "SELECT DISTINCT `glpi_softwares`.`id`,\n                          `glpi_softwares`.`name`\n          FROM `glpi_softwares`\n          WHERE `glpi_softwares`.`is_deleted` = '0'\n                AND `glpi_softwares`.`is_template` = '0'\n                {$where}\n          ORDER BY `glpi_softwares`.`name`";
$result = $DB->query($query);
echo "<select name='softwares_id' id='item_type{$rand}'>\n";
echo "<option value='0'>" . Dropdown::EMPTY_VALUE . "</option>\n";
if ($DB->numrows($result)) {
    while ($data = $DB->fetch_assoc($result)) {
        $softwares_id = $data["id"];
        $output = $data["name"];
        echo "<option value='{$softwares_id}' title=\"" . Html::cleanInputText($output) . "\">" . Toolbox::substr($output, 0, $_SESSION["glpidropdown_chars_limit"]) . "</option>";
    }
}
echo "</select>\n";
$paramsselsoft = array('softwares_id' => '__VALUE__', 'myname' => $_POST["myname"]);
Ajax::updateItemOnSelectEvent("item_type{$rand}", "show_" . $_POST["myname"] . $rand, $CFG_GLPI["root_doc"] . "/ajax/dropdownInstallVersion.php", $paramsselsoft);
echo "<span id='show_" . $_POST["myname"] . "{$rand}'>&nbsp;</span>\n";
Example #8
0
 /** show GANTT diagram for a project or for all
  *
  * @param $ID ID of the project or -1 for all projects
  */
 static function showGantt($ID)
 {
     global $DB;
     if ($ID > 0) {
         $project = new Project();
         if ($project->getFromDB($ID) && $project->canView()) {
             $todisplay = static::getDataToDisplayOnGantt($ID);
         } else {
             return false;
         }
     } else {
         $todisplay = array();
         // Get all root projects
         $query = "SELECT *\n                   FROM `glpi_projects`\n                   WHERE `projects_id` = '0'\n                        AND `show_on_global_gantt` = '1'\n                         " . getEntitiesRestrictRequest("AND", 'glpi_projects', "", '', true);
         foreach ($DB->request($query) as $data) {
             $todisplay += static::getDataToDisplayOnGantt($data['id'], false);
         }
         ksort($todisplay);
     }
     $data = array();
     $invalid = array();
     if (count($todisplay)) {
         // Prepare for display
         foreach ($todisplay as $key => $val) {
             if (!empty($val['from']) && !empty($val['to'])) {
                 $temp = array();
                 $color = 'ganttRed';
                 if ($val['percent'] > 50) {
                     $color = 'ganttOrange';
                 }
                 if ($val['percent'] == 100) {
                     $color = 'ganttGreen';
                 }
                 switch ($val['type']) {
                     case 'project':
                         $temp = array('name' => $val['link'], 'desc' => '', 'values' => array(array('from' => "/Date(" . strtotime($val['from']) . "000)/", 'to' => "/Date(" . strtotime($val['to']) . "000)/", 'desc' => $val['desc'], 'label' => $val['percent'] . "%", 'customClass' => $color)));
                         break;
                     case 'task':
                         if (isset($val['is_milestone']) && $val['is_milestone']) {
                             $color = 'ganttMilestone';
                         }
                         $temp = array('name' => ' ', 'desc' => str_repeat('-', $val['parents']) . $val['link'], 'values' => array(array('from' => "/Date(" . strtotime($val['from']) . "000)/", 'to' => "/Date(" . strtotime($val['to']) . "000)/", 'desc' => $val['desc'], 'label' => strlen($val['percent'] == 0) ? '' : $val['percent'] . "%", 'customClass' => $color)));
                         break;
                 }
                 $data[] = $temp;
             } else {
                 $invalid[] = $val['link'];
             }
         }
         // Html::printCleanArray($data);
     }
     if (count($invalid)) {
         echo sprintf(__('Invalid items (no start or end date): %s'), implode(',', $invalid));
         echo "<br><br>";
     }
     if (count($data)) {
         $months = array(__('January'), __('February'), __('March'), __('April'), __('May'), __('June'), __('July'), __('August'), __('September'), __('October'), __('November'), __('December'));
         $dow = array(Toolbox::substr(__('Sunday'), 0, 1), Toolbox::substr(__('Monday'), 0, 1), Toolbox::substr(__('Tuesday'), 0, 1), Toolbox::substr(__('Wednesday'), 0, 1), Toolbox::substr(__('Thursday'), 0, 1), Toolbox::substr(__('Friday'), 0, 1), Toolbox::substr(__('Saturday'), 0, 1));
         echo "<div class='gantt'></div>";
         $js = "\n                           \$('.gantt').gantt({\n                                 source: " . json_encode($data) . ",\n                                 navigate: 'scroll',\n                                 maxScale: 'months',\n                                 itemsPerPage: 20,\n                                 months: " . json_encode($months) . ",\n                                 dow: " . json_encode($dow) . ",\n                                 onItemClick: function(data) {\n                                 //    alert('Item clicked - show some details');\n                                 },\n                                 onAddClick: function(dt, rowId) {\n                                 //    alert('Empty space clicked - add an item!');\n                                 },\n                           });";
         echo Html::scriptBlock($js);
     } else {
         _e('No item to display');
     }
 }
Example #9
0
 /**
  * Generic Function to display Items
  *
  * @param $itemtype              item type
  * @param $ID                    ID of the SEARCH_OPTION item
  * @param $data            array containing data results
  * @param $num                   item num in the request
  * @param $meta                  is a meta item ? (default 0)
  * @param $addobjectparams array added parameters for union search
  *
  * @return string to print
  **/
 static function giveItem($itemtype, $ID, array $data, $num, $meta = 0, array $addobjectparams = array())
 {
     global $CFG_GLPI;
     $showuserlink = 0;
     if (Session::haveRight('user', READ)) {
         $showuserlink = 1;
     }
     $searchopt =& self::getOptions($itemtype);
     if (isset($CFG_GLPI["union_search_type"][$itemtype]) && $CFG_GLPI["union_search_type"][$itemtype] == $searchopt[$ID]["table"]) {
         if (isset($searchopt[$ID]['addobjectparams']) && $searchopt[$ID]['addobjectparams']) {
             return self::giveItem($data["TYPE"], $ID, $data, $num, $meta, $searchopt[$ID]['addobjectparams']);
         }
         return self::giveItem($data["TYPE"], $ID, $data, $num, $meta);
     }
     if (count($addobjectparams)) {
         $searchopt[$ID] = array_merge($searchopt[$ID], $addobjectparams);
     }
     // Plugin can override core definition for its type
     if ($plug = isPluginItemType($itemtype)) {
         $function = 'plugin_' . $plug['plugin'] . '_giveItem';
         if (function_exists($function)) {
             $out = $function($itemtype, $ID, $data, $num);
             if (!empty($out)) {
                 return $out;
             }
         }
     }
     $NAME = "ITEM_";
     if ($meta) {
         $NAME = "META_";
     }
     $table = $searchopt[$ID]["table"];
     $field = $searchopt[$ID]["field"];
     $linkfield = $searchopt[$ID]["linkfield"];
     /// TODO try to clean all specific cases using SpecificToDisplay
     switch ($table . '.' . $field) {
         case "glpi_users.name":
             // USER search case
             if ($itemtype != 'User' && isset($searchopt[$ID]["forcegroupby"]) && $searchopt[$ID]["forcegroupby"]) {
                 $out = "";
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $count_display = 0;
                 $added = array();
                 for ($k = 0; $k < count($split); $k++) {
                     if ($split[$k] > 0) {
                         if ($count_display) {
                             $out .= "<br>";
                         }
                         $count_display++;
                         if ($itemtype == 'Ticket') {
                             $userdata = getUserName($split[$k], 2);
                             $tooltip = "";
                             if (Session::haveRight('user', READ)) {
                                 $tooltip = Html::showToolTip($userdata["comment"], array('link' => $userdata["link"], 'display' => false));
                             }
                             $out .= sprintf(__('%1$s %2$s'), $userdata['name'], $tooltip);
                         } else {
                             $out .= getUserName($split[$k], $showuserlink);
                         }
                     }
                 }
                 // Manage alternative_email for tickets_users
                 if ($itemtype == 'Ticket' && isset($data[$NAME . $num . '_2'])) {
                     $split = explode("\$\$\$\$", $data[$NAME . $num . '_2']);
                     for ($k = 0; $k < count($split); $k++) {
                         $split2 = explode(" ", $split[$k]);
                         if (count($split2) == 2 && $split2[0] == 0 && !empty($split2[1])) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= "<a href='mailto:" . $split2[1] . "'>" . $split2[1] . "</a>";
                         }
                     }
                 }
                 return $out;
             }
             if ($itemtype != 'User') {
                 $toadd = '';
                 if ($itemtype == 'Ticket' && $data[$NAME . $num . "_3"] > 0) {
                     $userdata = getUserName($data[$NAME . $num . "_3"], 2);
                     $toadd = Html::showToolTip($userdata["comment"], array('link' => $userdata["link"], 'display' => false));
                 }
                 if (Session::haveRight('user', READ)) {
                     $usernameformat = formatUserName($data[$NAME . $num . "_3"], $data[$NAME . $num], $data[$NAME . $num . "_2"], $data[$NAME . $num . "_4"], 1);
                 } else {
                     $usernameformat = formatUserName($data[$NAME . $num . "_3"], $data[$NAME . $num], $data[$NAME . $num . "_2"], $data[$NAME . $num . "_4"], 0);
                 }
                 return sprintf(__('%1$s %2$s'), $usernameformat, $toadd);
             }
             break;
         case "glpi_profiles.interface":
             return Profile::getInterfaceName($data[$NAME . $num]);
         case "glpi_profiles.name":
             if ($itemtype == 'User' && $ID == 20) {
                 $out = "";
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $split2 = explode("\$\$\$\$", $data[$NAME . $num . "_2"]);
                 $split3 = explode("\$\$\$\$", $data[$NAME . $num . "_3"]);
                 $split4 = explode("\$\$\$\$", $data[$NAME . $num . "_4"]);
                 $count_display = 0;
                 $added = array();
                 for ($k = 0; $k < count($split); $k++) {
                     if (strlen(trim($split[$k])) > 0) {
                         $text = sprintf(__('%1$s - %2$s'), $split[$k], Dropdown::getDropdownName('glpi_entities', $split2[$k]));
                         $comp = '';
                         if ($split3[$k]) {
                             $comp = __(READ);
                             if ($split4[$k]) {
                                 $comp = sprintf(__('%1$s%2$s'), $comp, ", ");
                             }
                         }
                         if ($split4[$k]) {
                             $comp = sprintf(__('%1$s%2$s'), $comp, __('D'));
                         }
                         if (!empty($comp)) {
                             $text = sprintf(__('%1$s %2$s'), $text, "(" . $comp . ")");
                         }
                         if (!in_array($text, $added)) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= $text;
                             $added[] = $text;
                         }
                     }
                 }
                 return $out;
             }
             break;
         case "glpi_entities.completename":
             if ($itemtype == 'User') {
                 $out = "";
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $split2 = explode("\$\$\$\$", $data[$NAME . $num . "_2"]);
                 $split3 = explode("\$\$\$\$", $data[$NAME . $num . "_3"]);
                 $split4 = explode("\$\$\$\$", $data[$NAME . $num . "_4"]);
                 $added = array();
                 $count_display = 0;
                 for ($k = 0; $k < count($split); $k++) {
                     if (strlen(trim($split[$k])) > 0) {
                         $text = sprintf(__('%1$s - %2$s'), $split[$k], Dropdown::getDropdownName('glpi_profiles', $split2[$k]));
                         $comp = '';
                         if ($split3[$k]) {
                             $comp = __(READ);
                             if ($split4[$k]) {
                                 $comp = sprintf(__('%1$s%2$s'), $comp, ", ");
                             }
                         }
                         if ($split4[$k]) {
                             $comp = sprintf(__('%1$s%2$s'), $comp, __('D'));
                         }
                         if (!empty($comp)) {
                             $text = sprintf(__('%1$s %2$s'), $text, "(" . $comp . ")");
                         }
                         if (!in_array($text, $added)) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= $text;
                             $added[] = $text;
                         }
                     }
                 }
                 return $out;
             }
             break;
         case "glpi_documenttypes.icon":
             if (!empty($data[$NAME . $num])) {
                 return "<img class='middle' alt='' src='" . $CFG_GLPI["typedoc_icon_dir"] . "/" . $data[$NAME . $num] . "'>";
             }
             return "&nbsp;";
         case "glpi_documents.filename":
             $doc = new Document();
             if ($doc->getFromDB($data['id'])) {
                 return $doc->getDownloadLink();
             }
             return NOT_AVAILABLE;
         case "glpi_deviceharddrives.specificity":
         case "glpi_devicememories.specificity":
         case "glpi_deviceprocessors.specificity":
             return $data[$NAME . $num];
         case "glpi_networkports.mac":
             $out = "";
             if ($itemtype == 'Computer') {
                 $displayed = array();
                 if (!empty($data[$NAME . $num . "_2"])) {
                     $split = explode("\$\$\$\$", $data[$NAME . $num . "_2"]);
                     $count_display = 0;
                     for ($k = 0; $k < count($split); $k++) {
                         $lowstr = Toolbox::strtolower($split[$k]);
                         if (strlen(trim($split[$k])) > 0 && !in_array($lowstr, $displayed)) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= $split[$k];
                             $displayed[] = $lowstr;
                         }
                     }
                     if (!empty($data[$NAME . $num])) {
                         $out .= "<br>";
                     }
                 }
                 if (!empty($data[$NAME . $num])) {
                     $split = explode("\$\$\$\$", $data[$NAME . $num]);
                     $count_display = 0;
                     for ($k = 0; $k < count($split); $k++) {
                         $lowstr = Toolbox::strtolower($split[$k]);
                         if (strlen(trim($split[$k])) > 0 && !in_array($lowstr, $displayed)) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= $split[$k];
                             $displayed[] = $lowstr;
                         }
                     }
                 }
                 return $out;
             }
             break;
         case "glpi_contracts.duration":
         case "glpi_contracts.notice":
         case "glpi_contracts.periodicity":
         case "glpi_contracts.billing":
             if (!empty($data[$NAME . $num])) {
                 $split = explode('$$$$', $data[$NAME . $num]);
                 $output = "";
                 foreach ($split as $duration) {
                     $output .= (empty($output) ? '' : '<br>') . sprintf(_n('%d month', '%d months', $duration), $duration);
                 }
                 return $output;
             }
             return "&nbsp;";
         case "glpi_contracts.renewal":
             return Contract::getContractRenewalName($data[$NAME . $num]);
             //          case "glpi_infocoms.sink_time" :
             //             if (!empty($data[$NAME.$num])) {
             //                $split = explode("$$$$", $data[$NAME.$num]);
             //                $out   = '';
             //                foreach ($split as $val) {
             //                   $out .= (empty($out)?'':'<br>');
             //                   if ($val > 0) {
             //                      //TRANS: %d is a number of years
             //                      $out .= sprintf(_n('%d year', '%d years', $val), $val);
             //                   }
             //                }
             //                return $out;
             //             }
             //             return "&nbsp;";
             //
             //          case "glpi_infocoms.warranty_duration" :
             //             if (!empty($data[$NAME.$num])) {
             //                $split = explode("$$$$", $data[$NAME.$num]);
             //                $out   = '';
             //                foreach ($split as $val) {
             //                   $out .= (empty($out)?'':'<br>');
             //                   if ($val > 0) {
             //                      $out .= sprintf(_n('%d month', '%d months', $val), $val);
             //                   }
             //                   if ($val < 0) {
             //                      $out .= __('Lifelong');
             //                   }
             //                }
             //                return $out;
             //             }
             //             return "&nbsp;";
         //          case "glpi_infocoms.sink_time" :
         //             if (!empty($data[$NAME.$num])) {
         //                $split = explode("$$$$", $data[$NAME.$num]);
         //                $out   = '';
         //                foreach ($split as $val) {
         //                   $out .= (empty($out)?'':'<br>');
         //                   if ($val > 0) {
         //                      //TRANS: %d is a number of years
         //                      $out .= sprintf(_n('%d year', '%d years', $val), $val);
         //                   }
         //                }
         //                return $out;
         //             }
         //             return "&nbsp;";
         //
         //          case "glpi_infocoms.warranty_duration" :
         //             if (!empty($data[$NAME.$num])) {
         //                $split = explode("$$$$", $data[$NAME.$num]);
         //                $out   = '';
         //                foreach ($split as $val) {
         //                   $out .= (empty($out)?'':'<br>');
         //                   if ($val > 0) {
         //                      $out .= sprintf(_n('%d month', '%d months', $val), $val);
         //                   }
         //                   if ($val < 0) {
         //                      $out .= __('Lifelong');
         //                   }
         //                }
         //                return $out;
         //             }
         //             return "&nbsp;";
         case "glpi_infocoms.sink_type":
             $split = explode("\$\$\$\$", $data[$NAME . $num]);
             $out = '';
             foreach ($split as $val) {
                 $out .= (empty($out) ? '' : '<br>') . Infocom::getAmortTypeName($val);
             }
             return $out;
         case "glpi_infocoms.alert":
             if ($data[$NAME . $num] == pow(2, Alert::END)) {
                 return __s('Warranty expiration date');
             }
             return "";
         case "glpi_contracts.alert":
             switch ($data[$NAME . $num]) {
                 case pow(2, Alert::END):
                     return __('End');
                 case pow(2, Alert::NOTICE):
                     return __('Notice');
                 case pow(2, Alert::END) + pow(2, Alert::NOTICE):
                     return __('End + Notice');
             }
             return "";
         case "glpi_tickets_tickets.tickets_id_1":
             $out = "";
             $split = explode("\$\$\$\$", $data[$NAME . $num]);
             $split2 = explode("\$\$\$\$", $data[$NAME . $num . "_2"]);
             $displayed = array();
             for ($k = 0; $k < count($split); $k++) {
                 $linkid = $split[$k] == $data['id'] ? $split2[$k] : $split[$k];
                 if ($linkid > 0 && !isset($displayed[$linkid])) {
                     $text = "<a ";
                     $text .= "href=\"" . $CFG_GLPI["root_doc"] . "/front/ticket.form.php?id={$linkid}\">";
                     $text .= Dropdown::getDropdownName('glpi_tickets', $linkid) . "</a>";
                     if (count($displayed)) {
                         $out .= "<br>";
                     }
                     $displayed[$linkid] = $linkid;
                     $out .= $text;
                 }
             }
             return $out;
         case "glpi_problems.count":
             if ($data[$NAME . $num] > 0 && Session::haveRight("problem", Problem::READALL)) {
                 if ($itemtype == 'ITILCategory') {
                     $options['field'][0] = 7;
                     $options['searchtype'][0] = 'equals';
                     $options['contains'][0] = $data['id'];
                     $options['link'][0] = 'AND';
                 }
                 $options['reset'] = 'reset';
                 $out = "<a id='problem{$itemtype}" . $data['id'] . "' ";
                 $out .= "href=\"" . $CFG_GLPI["root_doc"] . "/front/problem.php?" . Toolbox::append_params($options, '&amp;') . "\">";
                 $out .= $data[$NAME . $num] . "</a>";
             } else {
                 $out = $data[$NAME . $num];
             }
             return $out;
         case "glpi_tickets.count":
             if ($data[$NAME . $num] > 0 && Session::haveRight("ticket", Ticket::READALL)) {
                 if ($itemtype == 'User') {
                     $options['field'][0] = 4;
                     $options['searchtype'][0] = 'equals';
                     $options['contains'][0] = $data['id'];
                     $options['link'][0] = 'AND';
                     $options['field'][1] = 22;
                     $options['searchtype'][1] = 'equals';
                     $options['contains'][1] = $data['id'];
                     $options['link'][1] = 'OR';
                     $options['field'][2] = 5;
                     $options['searchtype'][2] = 'equals';
                     $options['contains'][2] = $data['id'];
                     $options['link'][2] = 'OR';
                 } else {
                     if ($itemtype == 'ITILCategory') {
                         $options['field'][0] = 7;
                         $options['searchtype'][0] = 'equals';
                         $options['contains'][0] = $data['id'];
                         $options['link'][0] = 'AND';
                     } else {
                         $options['field'][0] = 12;
                         $options['searchtype'][0] = 'equals';
                         $options['contains'][0] = 'all';
                         $options['link'][0] = 'AND';
                         $options['itemtype2'][0] = $itemtype;
                         $options['field2'][0] = self::getOptionNumber($itemtype, 'name');
                         $options['searchtype2'][0] = 'equals';
                         $options['contains2'][0] = $data['id'];
                         $options['link2'][0] = 'AND';
                     }
                 }
                 $options['reset'] = 'reset';
                 $out = "<a id='ticket{$itemtype}" . $data['id'] . "' ";
                 $out .= "href=\"" . $CFG_GLPI["root_doc"] . "/front/ticket.php?" . Toolbox::append_params($options, '&amp;') . "\">";
                 $out .= $data[$NAME . $num] . "</a>";
             } else {
                 $out = $data[$NAME . $num];
             }
             return $out;
         case "glpi_tickets.due_date":
             // Due date + progress
             if ($ID == 151) {
                 $out = Html::convDate($data[$NAME . $num]);
                 // No due date in waiting status
                 if ($data[$NAME . $num . '_2'] == CommonITILObject::WAITING) {
                     return '';
                 }
                 if (empty($data[$NAME . $num])) {
                     return '';
                 }
                 if ($data[$NAME . $num . '_2'] == Ticket::SOLVED || $data[$NAME . $num . '_2'] == Ticket::CLOSED) {
                     return $data[$NAME . $num];
                 }
                 $ticket = new Ticket();
                 $ticket->getFromDB($data['ITEM_0']);
                 $percentage = 0;
                 $totaltime = 0;
                 $currenttime = 0;
                 if ($ticket->fields['slas_id'] != 0) {
                     // Have SLA
                     $sla = new SLA();
                     $sla->getFromDB($ticket->fields['slas_id']);
                     $currenttime = $sla->getActiveTimeBetween($ticket->fields['date'], date('Y-m-d H:i:s'));
                     $totaltime = $sla->getActiveTimeBetween($ticket->fields['date'], $data[$NAME . $num]);
                 } else {
                     $calendars_id = Entity::getUsedConfig('calendars_id', $ticket->fields['entities_id']);
                     if ($calendars_id != 0) {
                         // Ticket entity have calendar
                         $calendar = new Calendar();
                         $calendar->getFromDB($calendars_id);
                         $currenttime = $calendar->getActiveTimeBetween($ticket->fields['date'], date('Y-m-d H:i:s'));
                         $totaltime = $calendar->getActiveTimeBetween($ticket->fields['date'], $data[$NAME . $num]);
                     } else {
                         // No calendar
                         $currenttime = strtotime(date('Y-m-d H:i:s')) - strtotime($ticket->fields['date']);
                         $totaltime = strtotime($data[$NAME . $num]) - strtotime($ticket->fields['date']);
                     }
                 }
                 if ($totaltime != 0) {
                     $percentage = round(100 * $currenttime / $totaltime);
                 } else {
                     // Total time is null : no active time
                     $percentage = 100;
                 }
                 if ($percentage > 100) {
                     $percentage = 100;
                 }
                 $percentage_text = $percentage;
                 if ($_SESSION['glpiduedatewarning_unit'] == '%') {
                     $less_warn_limit = $_SESSION['glpiduedatewarning_less'];
                     $less_warn = 100 - $percentage;
                 } else {
                     if ($_SESSION['glpiduedatewarning_unit'] == 'hours') {
                         $less_warn_limit = $_SESSION['glpiduedatewarning_less'] * HOUR_TIMESTAMP;
                         $less_warn = $totaltime - $currenttime;
                     } else {
                         if ($_SESSION['glpiduedatewarning_unit'] == 'days') {
                             $less_warn_limit = $_SESSION['glpiduedatewarning_less'] * DAY_TIMESTAMP;
                             $less_warn = $totaltime - $currenttime;
                         }
                     }
                 }
                 if ($_SESSION['glpiduedatecritical_unit'] == '%') {
                     $less_crit_limit = $_SESSION['glpiduedatecritical_less'];
                     $less_crit = 100 - $percentage;
                 } else {
                     if ($_SESSION['glpiduedatecritical_unit'] == 'hours') {
                         $less_crit_limit = $_SESSION['glpiduedatecritical_less'] * HOUR_TIMESTAMP;
                         $less_crit = $totaltime - $currenttime;
                     } else {
                         if ($_SESSION['glpiduedatecritical_unit'] == 'days') {
                             $less_crit_limit = $_SESSION['glpiduedatecritical_less'] * DAY_TIMESTAMP;
                             $less_crit = $totaltime - $currenttime;
                         }
                     }
                 }
                 $color = $_SESSION['glpiduedateok_color'];
                 if ($less_crit < $less_crit_limit) {
                     $color = $_SESSION['glpiduedatecritical_color'];
                 } else {
                     if ($less_warn < $less_warn_limit) {
                         $color = $_SESSION['glpiduedatewarning_color'];
                     }
                 }
                 //Calculate bar progress
                 $out .= "<div class='center' style='background-color: #ffffff; width: 100%;\n                         border: 1px solid #9BA563;' >";
                 $out .= "<div style='position:absolute;'>&nbsp;" . $percentage_text . "%</div>";
                 $out .= "<div class='center' style='background-color: " . $color . ";\n                         width: " . $percentage . "%; height: 12px' ></div>";
                 $out .= "</div>";
                 return $out;
             }
             break;
         case "glpi_softwarelicenses.number":
             if ($data[$NAME . $num . "_2"] == -1) {
                 return __('Unlimited');
             }
             if (empty($data[$NAME . $num])) {
                 return 0;
             }
             return $data[$NAME . $num];
         case "glpi_auth_tables.name":
             return Auth::getMethodName($data[$NAME . $num], $data[$NAME . $num . "_2"], 1, $data[$NAME . $num . "_3"] . $data[$NAME . $num . "_4"]);
         case "glpi_reservationitems.comment":
             if (empty($data[$NAME . $num])) {
                 return "<a title=\"" . __s('Modify the comment') . "\"\n                        href='" . $CFG_GLPI["root_doc"] . "/front/reservationitem.form.php?id=" . $data["refID"] . "' >" . __('None') . "</a>";
             }
             return "<a title=\"" . __s('Modify the comment') . "\"\n                     href='" . $CFG_GLPI["root_doc"] . "/front/reservationitem.form.php?id=" . $data['refID'] . "' >" . Html::resume_text($data[$NAME . $num]) . "</a>";
         case 'glpi_notifications.mode':
             return Notification::getMode($data[$NAME . $num]);
         case 'glpi_notifications.event':
             $item = NotificationTarget::getInstanceByType($data['itemtype']);
             if ($item) {
                 $events = $item->getAllEvents();
                 if (isset($events[$data[$NAME . $num]])) {
                     return $events[$data[$NAME . $num]];
                 }
             }
             return '';
         case 'glpi_reminders.state':
             return Planning::getState($data[$NAME . $num]);
         case 'glpi_crontasks.description':
             $tmp = new CronTask();
             return $tmp->getDescription($data['id']);
         case 'glpi_crontasks.state':
             return CronTask::getStateName($data[$NAME . $num]);
         case 'glpi_crontasks.mode':
             return CronTask::getModeName($data[$NAME . $num]);
         case 'glpi_crontasks.itemtype':
             if ($plug = isPluginItemType($data[$NAME . $num])) {
                 return $plug['plugin'];
             }
             return '';
         case 'glpi_changes.status':
             $status = Change::getStatus($data[$NAME . $num]);
             return "<img src=\"" . Change::getStatusIconURL($data[$NAME . $num]) . "\"\n                     alt=\"{$status}\" title=\"{$status}\">&nbsp;{$status}";
         case 'glpi_problems.status':
             $status = Problem::getStatus($data[$NAME . $num]);
             return "<img src=\"" . Problem::getStatusIconURL($data[$NAME . $num]) . "\"\n                     alt=\"{$status}\" title=\"{$status}\">&nbsp;{$status}";
         case 'glpi_tickets.status':
             $status = Ticket::getStatus($data[$NAME . $num]);
             return "<img src=\"" . Ticket::getStatusIconURL($data[$NAME . $num]) . "\"\n                     alt=\"{$status}\" title=\"{$status}\">&nbsp;{$status}";
         case 'glpi_tickets.items_id':
             if (!empty($data[$NAME . $num . "_2"]) && ($item = getItemForItemtype($data[$NAME . $num . "_2"]))) {
                 if ($item->getFromDB($data[$NAME . $num])) {
                     return $item->getLink(array('comments' => true));
                 }
             }
             return '&nbsp;';
         case 'glpi_tickets.name':
             if (isset($searchopt[$ID]['forcegroupby']) && $searchopt[$ID]['forcegroupby']) {
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $out = '';
                 $link = Toolbox::getItemTypeFormURL('Ticket');
                 foreach ($split as $val) {
                     if (!empty($val)) {
                         $split2 = self::explodeWithID("\$\$", $val);
                         $out .= "<a id='ticket" . $split2[1] . "' href=\"" . $link;
                         $out .= strstr($link, '?') ? '&amp;' : '?';
                         $out .= 'id=' . $split2[1];
                         $out .= "\">";
                         $name = $split2[0];
                         if ($_SESSION["glpiis_ids_visible"] || empty($split2[0])) {
                             $name = sprintf(__('%1$s (%2$s)'), $name, $split2[1]);
                         }
                         $out .= $name . "</a><br>";
                     }
                 }
                 return $out;
             }
             $link = Toolbox::getItemTypeFormURL('Ticket');
             $out = "<a id='ticket" . $data[$NAME . $num . "_2"] . "' href=\"" . $link;
             $out .= strstr($link, '?') ? '&amp;' : '?';
             $out .= 'id=' . $data[$NAME . $num . "_2"];
             // Force solution tab if solved
             if ($data[$NAME . $num . "_4"] == CommonITILObject::SOLVED) {
                 $out .= "&amp;forcetab=Ticket\$2";
             }
             $out .= "\">";
             $name = $data[$NAME . $num];
             if ($_SESSION["glpiis_ids_visible"] || empty($data[$NAME . $num])) {
                 $name = sprintf(__('%1$s (%2$s)'), $name, $data[$NAME . $num . "_2"]);
             }
             $out .= $name . "</a>";
             $out = sprintf(__('%1$s %2$s'), $out, Html::showToolTip(nl2br($data[$NAME . $num . "_3"]), array('applyto' => 'ticket' . $data[$NAME . $num . "_2"], 'display' => false)));
             return $out;
         case 'glpi_ticketvalidations.status':
             $split = explode("\$\$\$\$", $data[$NAME . $num]);
             $out = '';
             foreach ($split as $val) {
                 if (!empty($val)) {
                     $split2 = self::explodeWithID("\$\$", $val);
                     $status = TicketValidation::getStatus($split2[0]);
                     $bgcolor = TicketValidation::getStatusColor($split2[0]);
                     $out .= (empty($out) ? '' : '<br>') . "<div style=\"background-color:" . $bgcolor . ";\">" . $status . '</div>';
                 }
             }
             return $out;
         case 'glpi_ticketsatisfactions.type':
             return TicketSatisfaction::getTypeInquestName($data[$NAME . $num]);
         case 'glpi_ticketsatisfactions.satisfaction':
             return TicketSatisfaction::displaySatisfaction($data[$NAME . $num]);
         case 'glpi_notimportedemails.reason':
             return NotImportedEmail::getReason($data[$NAME . $num]);
         case 'glpi_notimportedemails.messageid':
             $clean = array('<' => '', '>' => '');
             return strtr($data[$NAME . $num], $clean);
     }
     //// Default case
     // Link with plugin tables : need to know left join structure
     if (preg_match("/^glpi_plugin_([a-z0-9]+)/", $table . '.' . $field, $matches)) {
         if (count($matches) == 2) {
             $plug = $matches[1];
             $function = 'plugin_' . $plug . '_giveItem';
             if (function_exists($function)) {
                 $out = $function($itemtype, $ID, $data, $num);
                 if (!empty($out)) {
                     return $out;
                 }
             }
         }
     }
     $unit = '';
     if (isset($searchopt[$ID]['unit'])) {
         $unit = $searchopt[$ID]['unit'];
     }
     /// TODO try to use getvalueToDisplay instead of redefine display system
     // Preformat items
     if (isset($searchopt[$ID]["datatype"])) {
         switch ($searchopt[$ID]["datatype"]) {
             case "itemlink":
                 $linkitemtype = getItemTypeForTable($searchopt[$ID]["table"]);
                 if (isset($data[$NAME . $num . "_2"]) && strlen($data[$NAME . $num . "_2"])) {
                     $link = Toolbox::getItemTypeFormURL($linkitemtype);
                     $out = "<a id='" . $itemtype . "_" . $data[$NAME . $num . "_2"] . "' href=\"" . $link;
                     $out .= strstr($link, '?') ? '&amp;' : '?';
                     $out .= 'id=' . $data[$NAME . $num . "_2"];
                     if (isset($searchopt[$ID]['forcetab'])) {
                         $out .= "&amp;forcetab=" . $searchopt[$ID]['forcetab'];
                     }
                     $out .= "\">";
                     $name = Dropdown::getValueWithUnit($data[$NAME . $num], $unit);
                     if ($_SESSION["glpiis_ids_visible"] || empty($data[$NAME . $num])) {
                         $name = sprintf(__('%1$s (%2$s)'), $name, $data[$NAME . $num . "_2"]);
                     }
                     $out .= $name . "</a>";
                     return $out;
                 }
                 $out = "";
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $count_display = 0;
                 $separate = '<br>';
                 if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) {
                     $separate = '<hr>';
                 }
                 for ($k = 0; $k < count($split); $k++) {
                     if (strlen(trim($split[$k])) > 0) {
                         $split2 = self::explodeWithID("\$\$", $split[$k]);
                         if (isset($split2[1]) && $split2[1] > 0) {
                             if ($count_display) {
                                 $out .= $separate;
                             }
                             $count_display++;
                             $page = Toolbox::getItemTypeFormURL($linkitemtype);
                             $page .= strpos($page, '?') ? '&id' : '?id';
                             $name = Dropdown::getValueWithUnit($split2[0], $unit);
                             if ($_SESSION["glpiis_ids_visible"] || empty($split2[0])) {
                                 $name = sprintf(__('%1$s (%2$s)'), $name, $split2[1]);
                             }
                             $out .= "<a id='" . $linkitemtype . "_" . $data['id'] . "_" . $split2[1] . "' href='{$page}=" . $split2[1] . "'>" . $name . "</a>";
                         }
                     }
                 }
                 return $out;
             case "text":
                 $separate = '<br>';
                 if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) {
                     $separate = '<hr>';
                 }
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $out = '';
                 $count_display = 0;
                 foreach ($split as $val) {
                     if (strlen(trim($val)) > 0) {
                         $split2 = self::explodeWithID("\$\$", $val);
                         if ($count_display) {
                             $out .= $separate;
                         }
                         $count_display++;
                         if (isset($searchopt[$ID]['htmltext']) && $searchopt[$ID]['htmltext']) {
                             $text = Html::clean(Toolbox::unclean_cross_side_scripting_deep(nl2br($split2[0])));
                         } else {
                             $text = nl2br($split2[0]);
                         }
                         if (self::$output_type == self::HTML_OUTPUT && Toolbox::strlen($text) > $CFG_GLPI['cut']) {
                             $rand = mt_rand();
                             $out .= sprintf(__('%1$s %2$s'), "<span id='text{$rand}'>" . Html::resume_text($text, $CFG_GLPI['cut']) . '</span>', Html::showToolTip($text, array('applyto' => "text{$rand}", 'display' => false)));
                         } else {
                             $out .= $text;
                         }
                     }
                 }
                 return $out;
             case "date":
             case "date_delay":
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $out = '';
                 foreach ($split as $val) {
                     $out .= (empty($out) ? '' : '<br>') . Html::convDate($val);
                 }
                 return $out;
             case "datetime":
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $out = '';
                 foreach ($split as $val) {
                     $out .= (empty($out) ? '' : '<br>') . Html::convDateTime($val);
                 }
                 return $out;
             case "timestamp":
                 $withseconds = false;
                 if (isset($searchopt[$ID]['withseconds'])) {
                     $withseconds = $searchopt[$ID]['withseconds'];
                 }
                 $withdays = true;
                 if (isset($searchopt[$ID]['withdays'])) {
                     $withdays = $searchopt[$ID]['withdays'];
                 }
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $out = '';
                 foreach ($split as $val) {
                     $out .= (empty($out) ? '' : '<br>') . Html::timestampToString($val, $withseconds, $withdays);
                 }
                 return $out;
             case "email":
                 $split = explode('$$$$', $data[$NAME . $num]);
                 $out = '';
                 $count_display = 0;
                 foreach ($split as $val) {
                     $split2 = self::explodeWithID("\$\$", $val);
                     if ($count_display) {
                         $out .= "<br>";
                     }
                     $count_display++;
                     if (!empty($val)) {
                         $out .= empty($out) ? '' : '<br>';
                         $out .= "<a href='mailto:{$split2['0']}'>{$split2['0']}</a>";
                     }
                 }
                 return empty($out) ? "&nbsp;" : $out;
             case "weblink":
                 $orig_link = trim($data[$NAME . $num]);
                 if (!empty($orig_link)) {
                     // strip begin of link
                     $link = preg_replace('/https?:\\/\\/(www[^\\.]*\\.)?/', '', $orig_link);
                     $link = preg_replace('/\\/$/', '', $link);
                     if (Toolbox::strlen($link) > $CFG_GLPI["url_maxlength"]) {
                         $link = Toolbox::substr($link, 0, $CFG_GLPI["url_maxlength"]) . "...";
                     }
                     return "<a href=\"" . formatOutputWebLink($orig_link) . "\" target='_blank'>{$link}</a>";
                 }
                 return "&nbsp;";
             case "number":
                 if (isset($searchopt[$ID]['forcegroupby']) && $searchopt[$ID]['forcegroupby']) {
                     $out = "";
                     $split = explode("\$\$\$\$", $data[$NAME . $num]);
                     $count_display = 0;
                     for ($k = 0; $k < count($split); $k++) {
                         if (strlen(trim($split[$k])) > 0) {
                             $split2 = self::explodeWithID("\$\$", $split[$k]);
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             if (isset($searchopt[$ID]['toadd']) && isset($searchopt[$ID]['toadd'][$split2[0]])) {
                                 $out .= $searchopt[$ID]['toadd'][$split2[0]];
                             } else {
                                 $number = str_replace(' ', '&nbsp;', Html::formatNumber($split2[0], false, 0));
                                 $out .= Dropdown::getValueWithUnit($number, $unit);
                             }
                         }
                     }
                     return $out;
                 }
                 if (isset($searchopt[$ID]['toadd']) && isset($searchopt[$ID]['toadd'][$data[$NAME . $num]])) {
                     return $searchopt[$ID]['toadd'][$data[$NAME . $num]];
                 } else {
                     $number = str_replace(' ', '&nbsp;', Html::formatNumber($data[$NAME . $num], false, 0));
                     return Dropdown::getValueWithUnit($number, $unit);
                 }
             case "decimal":
                 if (isset($searchopt[$ID]['forcegroupby']) && $searchopt[$ID]['forcegroupby']) {
                     $out = "";
                     $split = explode("\$\$\$\$", $data[$NAME . $num]);
                     $count_display = 0;
                     for ($k = 0; $k < count($split); $k++) {
                         if (strlen(trim($split[$k])) > 0) {
                             $split2 = self::explodeWithID("\$\$", $split[$k]);
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             if (isset($searchopt[$ID]['toadd']) && isset($searchopt[$ID]['toadd'][$split2[0]])) {
                                 $out .= $searchopt[$ID]['toadd'][$split2[0]];
                             } else {
                                 $number = str_replace(' ', '&nbsp;', Html::formatNumber($split2[0]));
                                 $out .= Dropdown::getValueWithUnit($number, $unit);
                             }
                         }
                     }
                     return $out;
                 }
                 $number = str_replace(' ', '&nbsp;', Html::formatNumber($data[$NAME . $num]));
                 return Dropdown::getValueWithUnit($number, $unit);
             case "bool":
                 if (isset($searchopt[$ID]['forcegroupby']) && $searchopt[$ID]['forcegroupby']) {
                     $out = "";
                     $split = explode("\$\$\$\$", $data[$NAME . $num]);
                     $count_display = 0;
                     for ($k = 0; $k < count($split); $k++) {
                         if (strlen(trim($split[$k])) > 0) {
                             $split2 = self::explodeWithID("\$\$", $split[$k]);
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= Dropdown::getValueWithUnit(Dropdown::getYesNo($split2[0]), $unit);
                         }
                     }
                     return $out;
                 }
                 return Dropdown::getValueWithUnit(Dropdown::getYesNo($data[$NAME . $num]), $unit);
             case "right":
                 return Profile::getRightValue($data[$NAME . $num]);
             case "itemtypename":
                 if ($obj = getItemForItemtype($data[$NAME . $num])) {
                     return $obj->getTypeName();
                 }
                 return "";
             case "language":
                 if (isset($CFG_GLPI['languages'][$data[$NAME . $num]])) {
                     return $CFG_GLPI['languages'][$data[$NAME . $num]][0];
                 }
                 return __('Default value');
         }
     }
     // Manage items with need group by / group_concat
     if (isset($searchopt[$ID]['forcegroupby']) && $searchopt[$ID]['forcegroupby']) {
         $out = "";
         $split = explode("\$\$\$\$", $data[$NAME . $num]);
         $count_display = 0;
         $separate = '<br>';
         if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) {
             $separate = '<hr>';
         }
         for ($k = 0; $k < count($split); $k++) {
             if (strlen(trim($split[$k])) > 0) {
                 if ($count_display) {
                     $out .= $separate;
                 }
                 $withoutid = self::explodeWithID("\$\$", $split[$k]);
                 $count_display++;
                 // Get specific display if available
                 $itemtype = getItemTypeForTable($table);
                 if ($item = getItemForItemtype($itemtype)) {
                     $tmpdata = array($field => $withoutid[0]);
                     $specific = $item->getSpecificValueToDisplay($field, $tmpdata, array('html' => true));
                 }
                 if (!empty($specific)) {
                     $out .= $specific;
                 } else {
                     $out .= Dropdown::getValueWithUnit($withoutid[0], $unit);
                 }
             }
         }
         return $out;
     }
     // Get specific display if available
     $itemtype = getItemTypeForTable($table);
     if ($item = getItemForItemtype($itemtype)) {
         $tmpdata = array($field => $data[$NAME . $num]);
         if (isset($searchopt[$ID]['additionalfields']) && count($searchopt[$ID]['additionalfields'])) {
             foreach ($searchopt[$ID]['additionalfields'] as $key) {
                 $tmpdata[$key] = $data[$NAME . $num . '_' . $key];
             }
         }
         $specific = $item->getSpecificValueToDisplay($field, $tmpdata, array('html' => true));
         if (!empty($specific)) {
             return $specific;
         }
     }
     // Manage auto CONCAT id
     $split = self::explodeWithID('$$', $data[$NAME . $num]);
     $split[0] = trim($split[0]);
     if (isset($searchopt[$ID]['toadd']) && isset($searchopt[$ID]['toadd'][$split[0]])) {
         return $searchopt[$ID]['toadd'][$split[0]];
     }
     // Empty is 0 or empty
     if (empty($split[0]) && isset($searchopt[$ID]['emptylabel'])) {
         return $searchopt[$ID]['emptylabel'];
     }
     return Dropdown::getValueWithUnit($split[0], $unit);
 }
 function reconstrucTimeline()
 {
     global $DB;
     $query = "TRUNCATE `" . $this->getTable() . "`";
     $DB->query($query);
     $query = "SELECT id\n               FROM `glpi_tickets`";
     $result = $DB->query($query);
     while ($data = $DB->fetch_array($result)) {
         $queryGroup = "SELECT * FROM `glpi_logs`";
         $queryGroup .= " WHERE `itemtype_link` = 'Group'";
         $queryGroup .= " AND `items_id` = " . $data['id'];
         $queryGroup .= " AND `itemtype` = 'Ticket'";
         $queryGroup .= " ORDER BY date_mod ASC";
         $resultGroup = $DB->query($queryGroup);
         if ($resultGroup) {
             while ($dataGroup = $DB->fetch_array($resultGroup)) {
                 if ($dataGroup['new_value'] != null) {
                     $start = Toolbox::strpos($dataGroup['new_value'], "(");
                     $end = Toolbox::strpos($dataGroup['new_value'], ")");
                     $length = $end - $start;
                     $groups_id = Toolbox::substr($dataGroup['new_value'], $start + 1, $length - 1);
                     $group = new Group();
                     if ($group->getFromDB($groups_id)) {
                         if ($group->fields['is_requester'] == 0 && $group->fields['is_assign'] == 1) {
                             $ticket = new Ticket();
                             $ticket->getFromDB($data['id']);
                             $this->createGroup($ticket, $dataGroup['date_mod'], $groups_id, 'new');
                         }
                     }
                 } else {
                     if ($dataGroup['old_value'] != null) {
                         $start = Toolbox::strpos($dataGroup['old_value'], "(");
                         $end = Toolbox::strpos($dataGroup['old_value'], ")");
                         $length = $end - $start;
                         $groups_id = Toolbox::substr($dataGroup['old_value'], $start + 1, $length - 1);
                         $group = new Group();
                         if ($group->getFromDB($groups_id)) {
                             if ($group->fields['is_requester'] == 0 && $group->fields['is_assign'] == 1) {
                                 $ticket = new Ticket();
                                 $ticket->getFromDB($data['id']);
                                 $this->createGroup($ticket, $dataGroup['date_mod'], $groups_id, 'delete');
                             }
                         }
                     }
                 }
             }
         }
     }
 }
Example #11
0
 /**
  * Print out an HTML "<select>" for a dropdown with preselected value
  *
  * @param $itemtype        itemtype used for create dropdown
  * @param $options   array of possible options:
  *    - name                 : string / name of the select (default is depending itemtype)
  *    - value                : integer / preselected value (default -1)
  *    - comments             : boolean / is the comments displayed near the dropdown (default true)
  *    - toadd                : array / array of specific values to add at the begining
  *    - entity               : integer or array / restrict to a defined entity or array of entities
  *                                                (default -1 : no restriction)
  *    - entity_sons          : boolean / if entity restrict specified auto select its sons
  *                                       only available if entity is a single value not an array
  *                                       (default false)
  *    - toupdate             : array / Update a specific item on select change on dropdown
  *                                     (need value_fieldname, to_update,
  *                                      url (see Ajax::updateItemOnSelectEvent for information)
  *                                      and may have moreparams)
  *    - used                 : array / Already used items ID: not to display in dropdown
  *                                    (default empty)
  *    - on_change            : string / value to transmit to "onChange"
  *    - rand                 : integer / already computed rand value
  *    - condition            : string / aditional SQL condition to limit display
  *    - displaywith          : array / array of field to display with request
  *    - emptylabel           : Empty choice's label (default self::EMPTY_VALUE)
  *    - display_emptychoice  : Display emptychoice ? (default true)
  *    - display              : boolean / display or get string (default true)
  *    - width                : specific width needed (default 80%)
  *    - permit_select_parent : boolean / for tree dropdown permit to see parent items
  *                                       not available by default (default false)
  *    - specific_tags        : array of HTML5 tags to add the the field
  *
  * @return boolean : false if error and random id if OK
  **/
 static function show($itemtype, $options = array())
 {
     global $DB, $CFG_GLPI;
     if ($itemtype && !($item = getItemForItemtype($itemtype))) {
         return false;
     }
     $table = $item->getTable();
     $params['name'] = $item->getForeignKeyField();
     $params['value'] = $itemtype == 'Entity' ? $_SESSION['glpiactive_entity'] : '';
     $params['comments'] = true;
     $params['entity'] = -1;
     $params['entity_sons'] = false;
     $params['toupdate'] = '';
     $params['width'] = '80%';
     $params['used'] = array();
     $params['toadd'] = array();
     $params['on_change'] = '';
     $params['condition'] = '';
     $params['rand'] = mt_rand();
     $params['displaywith'] = array();
     //Parameters about choice 0
     //Empty choice's label
     $params['emptylabel'] = self::EMPTY_VALUE;
     //Display emptychoice ?
     $params['display_emptychoice'] = $itemtype != 'Entity';
     $params['display'] = true;
     $params['permit_select_parent'] = false;
     $params['addicon'] = true;
     $params['specific_tags'] = array();
     if (is_array($options) && count($options)) {
         foreach ($options as $key => $val) {
             $params[$key] = $val;
         }
     }
     $output = '';
     $name = $params['emptylabel'];
     $comment = "";
     $limit_length = $_SESSION["glpidropdown_chars_limit"];
     // Check default value for dropdown : need to be a numeric
     if (strlen($params['value']) == 0 || !is_numeric($params['value']) && $params['value'] != 'mygroups') {
         $params['value'] = 0;
     }
     if (isset($params['toadd'][$params['value']])) {
         $name = $params['toadd'][$params['value']];
     } else {
         if ($params['value'] > 0 || $itemtype == "Entity" && $params['value'] >= 0) {
             $tmpname = self::getDropdownName($table, $params['value'], 1);
             if ($tmpname["name"] != "&nbsp;") {
                 $name = $tmpname["name"];
                 $comment = $tmpname["comment"];
                 if (Toolbox::strlen($name) > $_SESSION["glpidropdown_chars_limit"]) {
                     if ($item instanceof CommonTreeDropdown) {
                         $pos = strrpos($name, ">");
                         $limit_length = max(Toolbox::strlen($name) - $pos, $_SESSION["glpidropdown_chars_limit"]);
                         if (Toolbox::strlen($name) > $limit_length) {
                             $name = "..." . Toolbox::substr($name, -$limit_length);
                         }
                     } else {
                         $limit_length = Toolbox::strlen($name);
                     }
                 } else {
                     $limit_length = $_SESSION["glpidropdown_chars_limit"];
                 }
             }
         }
     }
     // Manage entity_sons
     if (!($params['entity'] < 0) && $params['entity_sons']) {
         if (is_array($params['entity'])) {
             // translation not needed - only for debug
             $output .= "entity_sons options is not available with entity option as array";
         } else {
             $params['entity'] = getSonsOf('glpi_entities', $params['entity']);
         }
     }
     $field_id = Html::cleanId("dropdown_" . $params['name'] . $params['rand']);
     // Manage condition
     if (!empty($params['condition'])) {
         $params['condition'] = static::addNewCondition($params['condition']);
     }
     if (!$item instanceof CommonTreeDropdown) {
         $name = Toolbox::unclean_cross_side_scripting_deep($name);
     }
     $p = array('value' => $params['value'], 'valuename' => $name, 'width' => $params['width'], 'itemtype' => $itemtype, 'display_emptychoice' => $params['display_emptychoice'], 'displaywith' => $params['displaywith'], 'emptylabel' => $params['emptylabel'], 'condition' => $params['condition'], 'used' => $params['used'], 'toadd' => $params['toadd'], 'entity_restrict' => is_array($params['entity']) ? json_encode(array_values($params['entity'])) : $params['entity'], 'limit' => $limit_length, 'on_change' => $params['on_change'], 'permit_select_parent' => $params['permit_select_parent'], 'specific_tags' => $params['specific_tags']);
     $output = Html::jsAjaxDropdown($params['name'], $field_id, $CFG_GLPI['root_doc'] . "/ajax/getDropdownValue.php", $p);
     // Display comment
     if ($params['comments']) {
         $comment_id = Html::cleanId("comment_" . $params['name'] . $params['rand']);
         $link_id = Html::cleanId("comment_link_" . $params['name'] . $params['rand']);
         $options_tooltip = array('contentid' => $comment_id, 'linkid' => $link_id, 'display' => false);
         if ($item->canView()) {
             if ($params['value'] && $item->getFromDB($params['value']) && $item->canViewItem()) {
                 $options_tooltip['link'] = $item->getLinkURL();
             } else {
                 $options_tooltip['link'] = $item->getSearchURL();
             }
             $options_tooltip['linktarget'] = '_blank';
         }
         $output .= "&nbsp;" . Html::showToolTip($comment, $options_tooltip);
         if ($item instanceof CommonDropdown && $item->canCreate() && !isset($_REQUEST['_in_modal']) && $params['addicon']) {
             $output .= "<img alt='' title=\"" . __s('Add') . "\" src='" . $CFG_GLPI["root_doc"] . "/pics/add_dropdown.png' style='cursor:pointer; margin-left:2px;'\n                            onClick=\"" . Html::jsGetElementbyID('add_dropdown' . $params['rand']) . ".dialog('open');\">";
             $output .= Ajax::createIframeModalWindow('add_dropdown' . $params['rand'], $item->getFormURL(), array('display' => false));
         }
         // Display specific Links
         if ($itemtype == "Supplier") {
             if ($item->getFromDB($params['value'])) {
                 $output .= $item->getLinks();
             }
         }
         if ($itemtype == 'ITILCategory' && Session::haveRight('knowbase', READ)) {
             if ($params['value'] && $item->getFromDB($params['value'])) {
                 $output .= '&nbsp;' . $item->getLinks();
             }
         }
         $paramscomment = array('value' => '__VALUE__', 'table' => $table);
         if ($item->canView()) {
             $paramscomment['withlink'] = $link_id;
         }
         $output .= Ajax::updateItemOnSelectEvent($field_id, $comment_id, $CFG_GLPI["root_doc"] . "/ajax/comments.php", $paramscomment, false);
     }
     $output .= Ajax::commonDropdownUpdateItem($params, false);
     if ($params['display']) {
         echo $output;
         return $params['rand'];
     }
     return $output;
 }
Example #12
0
 /**
  * Print out an HTML "<select>" for a dropdown with preselected value
  *
  * @param $itemtype        itemtype used for create dropdown
  * @param $options   array of possible options:
  *    - name                : string / name of the select (default is depending itemtype)
  *    - value               : integer / preselected value (default -1)
  *    - comments            : boolean / is the comments displayed near the dropdown (default true)
  *    - toadd               : array / array of specific values to add at the begining
  *    - entity              : integer or array / restrict to a defined entity or array of entities
  *                                               (default -1 : no restriction)
  *    - entity_sons         : boolean / if entity restrict specified auto select its sons
  *                                      only available if entity is a single value not an array
  *                                      (default false)
  *    - toupdate            : array / Update a specific item on select change on dropdown
  *                                    (need value_fieldname, to_update,
  *                                     url (see Ajax::updateItemOnSelectEvent for information)
  *                                     and may have moreparams)
  *    - used                : array / Already used items ID: not to display in dropdown
  *                                    (default empty)
  *    - on_change           : string / value to transmit to "onChange"
  *    - rand                : integer / already computed rand value
  *    - condition           : string / aditional SQL condition to limit display
  *    - displaywith         : array / array of field to display with request
  *    - emptylabel          : Empty choice's label (default self::EMPTY_VALUE)
  *    - display_emptychoice : Display emptychoice ? (default true)
  *    - display             : boolean / display or get string (default true)
  *    - permit_select_parent : boolean / for tree dropdown permit to see parent items not available by default (default false)
  *
  * @return boolean : false if error and random id if OK
  **/
 static function show($itemtype, $options = array())
 {
     global $DB, $CFG_GLPI;
     if ($itemtype && !($item = getItemForItemtype($itemtype))) {
         return false;
     }
     $table = $item->getTable();
     $params['name'] = $item->getForeignKeyField();
     $params['value'] = $itemtype == 'Entity' ? $_SESSION['glpiactive_entity'] : '';
     $params['comments'] = true;
     $params['entity'] = -1;
     $params['entity_sons'] = false;
     $params['toupdate'] = '';
     $params['used'] = array();
     $params['toadd'] = array();
     $params['on_change'] = '';
     $params['condition'] = '';
     $params['rand'] = mt_rand();
     $params['displaywith'] = array();
     //Parameters about choice 0
     //Empty choice's label
     $params['emptylabel'] = self::EMPTY_VALUE;
     //Display emptychoice ?
     $params['display_emptychoice'] = $itemtype != 'Entity';
     $params['display'] = true;
     $params['permit_select_parent'] = false;
     if (is_array($options) && count($options)) {
         foreach ($options as $key => $val) {
             $params[$key] = $val;
         }
     }
     $output = '';
     $name = $params['emptylabel'];
     $comment = "";
     $limit_length = $_SESSION["glpidropdown_chars_limit"];
     // Check default value for dropdown : need to be a numeric
     if (strlen($params['value']) == 0 || !is_numeric($params['value'])) {
         $params['value'] = 0;
     }
     if ($params['value'] > 0 || $itemtype == "Entity" && $params['value'] >= 0) {
         $tmpname = self::getDropdownName($table, $params['value'], 1);
         if ($tmpname["name"] != "&nbsp;") {
             $name = $tmpname["name"];
             $comment = $tmpname["comment"];
             if (Toolbox::strlen($name) > $_SESSION["glpidropdown_chars_limit"]) {
                 if ($item instanceof CommonTreeDropdown) {
                     $pos = strrpos($name, ">");
                     $limit_length = max(Toolbox::strlen($name) - $pos, $_SESSION["glpidropdown_chars_limit"]);
                     if (Toolbox::strlen($name) > $limit_length) {
                         $name = "&hellip;" . Toolbox::substr($name, -$limit_length);
                     }
                 } else {
                     $limit_length = Toolbox::strlen($name);
                 }
             } else {
                 $limit_length = $_SESSION["glpidropdown_chars_limit"];
             }
         }
     }
     // Manage entity_sons
     if (!($params['entity'] < 0) && $params['entity_sons']) {
         if (is_array($params['entity'])) {
             // translation not needed - only for debug
             $output .= "entity_sons options is not available with entity option as array";
         } else {
             $params['entity'] = getSonsOf('glpi_entities', $params['entity']);
         }
     }
     $use_ajax = false;
     if ($CFG_GLPI["use_ajax"]) {
         $nb = 0;
         if ($item->isEntityAssign()) {
             if (!($params['entity'] < 0)) {
                 $nb = countElementsInTableForEntity($table, $params['entity'], $params['condition']);
             } else {
                 $nb = countElementsInTableForMyEntities($table, $params['condition']);
             }
         } else {
             $nb = countElementsInTable($table, $params['condition']);
         }
         $nb -= count($params['used']);
         if ($nb > $CFG_GLPI["ajax_limit_count"]) {
             $use_ajax = true;
         }
     }
     $param = array('searchText' => '__VALUE__', 'value' => $params['value'], 'itemtype' => $itemtype, 'myname' => $params['name'], 'limit' => $limit_length, 'toadd' => $params['toadd'], 'comment' => $params['comments'], 'rand' => $params['rand'], 'entity_restrict' => $params['entity'], 'update_item' => $params['toupdate'], 'used' => $params['used'], 'on_change' => $params['on_change'], 'condition' => $params['condition'], 'emptylabel' => $params['emptylabel'], 'display_emptychoice' => $params['display_emptychoice'], 'displaywith' => $params['displaywith'], 'display' => false, 'permit_select_parent' => $params['permit_select_parent']);
     if ($item->canView()) {
         $param['update_link'] = 1;
     }
     $default = "<select name='" . $params['name'] . "' id='dropdown_" . $params['name'] . $params['rand'] . "'>";
     $default .= "<option value='" . $params['value'] . "'>{$name}</option></select>";
     $output .= Ajax::dropdown($use_ajax, "/ajax/dropdownValue.php", $param, $default, $params['rand'], false);
     // Display comment
     if ($params['comments']) {
         $options_tooltip = array('contentid' => "comment_" . $params['name'] . $params['rand'], 'display' => false);
         if ($item->canView()) {
             if ($params['value'] && $item->getFromDB($params['value']) && $item->canViewItem()) {
                 $options_tooltip['link'] = $item->getLinkURL();
             } else {
                 $options_tooltip['link'] = $item->getSearchURL();
             }
             $options_tooltip['linkid'] = "comment_link_" . $params['name'] . $params['rand'];
             $options_tooltip['linktarget'] = '_blank';
         }
         $output .= Html::showToolTip($comment, $options_tooltip);
         if ($item instanceof CommonDropdown && $item->canCreate() && !isset($_GET['popup'])) {
             $output .= "<img alt='' title=\"" . __s('Add') . "\" src='" . $CFG_GLPI["root_doc"] . "/pics/add_dropdown.png' style='cursor:pointer; margin-left:2px;'\n                            onClick=\"var w = window.open('" . $item->getFormURL() . "?popup=1&amp;rand=" . $params['rand'] . "' ,'glpipopup', 'height=400, " . "width=1000, top=100, left=100, scrollbars=yes' );w.focus();\">";
         }
         // Display specific Links
         if ($itemtype == "Supplier") {
             if ($item->getFromDB($params['value'])) {
                 $output .= $item->getLinks();
             }
         }
         if ($itemtype == 'ITILCategory' && Session::haveRight('knowbase', 'r')) {
             if ($params['value'] && $item->getFromDB($params['value'])) {
                 $output .= '&nbsp;' . $item->getLinks();
             }
         }
     }
     if ($params['display']) {
         echo $output;
         return $params['rand'];
     } else {
         return $output;
     }
 }
Example #13
0
 /**
  * display a field using standard system
  *
  * @since version 0.83
  *
  * @param $field_id_or_search_options  integer/string/array id of the search option field
  *                                                             or field name
  *                                                             or search option array
  * @param $values                                           mixed value to display
  * @param $options                     array                of possible options:
  * Parameters which could be used in options array :
  *    - comments : boolean / is the comments displayed near the value (default false)
  *    - any others options passed to specific display method
  *
  * @return return the string to display
  **/
 function getValueToDisplay($field_id_or_search_options, $values, $options = array())
 {
     global $CFG_GLPI;
     $param['comments'] = false;
     $param['html'] = false;
     foreach ($param as $key => $val) {
         if (!isset($options[$key])) {
             $options[$key] = $val;
         }
     }
     $searchoptions = array();
     if (is_array($field_id_or_search_options)) {
         $searchoptions = $field_id_or_search_options;
     } else {
         $searchopt = $this->getSearchOptions();
         // Get if id of search option is passed
         if (is_numeric($field_id_or_search_options)) {
             if (isset($searchopt[$field_id_or_search_options])) {
                 $searchoptions = $searchopt[$field_id_or_search_options];
             }
         } else {
             // Get if field name is passed
             $searchoptions = $this->getSearchOptionByField('field', $field_id_or_search_options, $this->getTable());
         }
     }
     if (count($searchoptions)) {
         $field = $searchoptions['field'];
         // Normalize option
         if (is_array($values)) {
             $value = $values[$field];
         } else {
             $value = $values;
             $values = array($field => $value);
         }
         if (isset($searchoptions['datatype'])) {
             $unit = '';
             if (isset($searchoptions['unit'])) {
                 $unit = $searchoptions['unit'];
             }
             switch ($searchoptions['datatype']) {
                 case "count":
                 case "number":
                     if (isset($searchoptions['toadd']) && isset($searchoptions['toadd'][$value])) {
                         return $searchoptions['toadd'][$value];
                     }
                     if ($options['html']) {
                         return Dropdown::getValueWithUnit(Html::formatNumber($value, false, 0), $unit);
                     }
                     return $value;
                 case "decimal":
                     if ($options['html']) {
                         return Dropdown::getValueWithUnit(Html::formatNumber($value), $unit);
                     }
                     return $value;
                 case "string":
                 case "mac":
                 case "ip":
                     return $value;
                 case "text":
                     if ($options['html']) {
                         $text = nl2br($value);
                     } else {
                         $text = $value;
                     }
                     if (isset($searchoptions['htmltext']) && $searchoptions['htmltext']) {
                         $text = Html::clean(Toolbox::unclean_cross_side_scripting_deep($text));
                     }
                     return $text;
                 case "bool":
                     return Dropdown::getYesNo($value);
                 case "date":
                 case "date_delay":
                     if (isset($options['relative_dates']) && $options['relative_dates']) {
                         $dates = Html::getGenericDateTimeSearchItems(array('with_time' => true, 'with_future' => true));
                         return $dates[$value];
                     }
                     return Html::convDate(Html::computeGenericDateTimeSearch($value, true));
                 case "datetime":
                     if (isset($options['relative_dates']) && $options['relative_dates']) {
                         $dates = Html::getGenericDateTimeSearchItems(array('with_time' => true, 'with_future' => true));
                         return $dates[$value];
                     }
                     return Html::convDateTime(Html::computeGenericDateTimeSearch($value, false));
                 case "timestamp":
                     if ($value == 0 && isset($searchoptions['emptylabel'])) {
                         return $searchoptions['emptylabel'];
                     }
                     $withseconds = false;
                     if (isset($searchoptions['withseconds'])) {
                         $withseconds = $searchoptions['withseconds'];
                     }
                     return Html::timestampToString($value, $withseconds);
                 case "email":
                     if ($options['html']) {
                         return "<a href='mailto:{$value}'>{$value}</a>";
                     }
                     return $value;
                 case "weblink":
                     $orig_link = trim($value);
                     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 "&nbsp;";
                 case "itemlink":
                     if ($searchoptions['table'] == $this->getTable()) {
                         break;
                     }
                 case "dropdown":
                     if (isset($searchoptions['toadd']) && isset($searchoptions['toadd'][$value])) {
                         return $searchoptions['toadd'][$value];
                     }
                     if (!is_numeric($value)) {
                         return $value;
                     }
                     if ($value == 0 && isset($searchoptions['emptylabel'])) {
                         return $searchoptions['emptylabel'];
                     }
                     if ($searchoptions['table'] == 'glpi_users') {
                         if ($param['comments']) {
                             $tmp = getUserName($value, 2);
                             return $tmp['name'] . '&nbsp;' . Html::showToolTip($tmp['comment'], array('display' => false));
                         }
                         return getUserName($value);
                     }
                     if ($param['comments']) {
                         $tmp = Dropdown::getDropdownName($searchoptions['table'], $value, 1);
                         return $tmp['name'] . '&nbsp;' . Html::showToolTip($tmp['comment'], array('display' => false));
                     }
                     return Dropdown::getDropdownName($searchoptions['table'], $value);
                 case "itemtypename":
                     if ($obj = getItemForItemtype($value)) {
                         return $obj->getTypeName(1);
                     }
                     break;
                 case "language":
                     if (isset($CFG_GLPI['languages'][$value])) {
                         return $CFG_GLPI['languages'][$value][0];
                     }
                     return __('Default value');
             }
         }
         // Get specific display if available
         $itemtype = getItemTypeForTable($searchoptions['table']);
         if ($item = getItemForItemtype($itemtype)) {
             $options['searchopt'] = $searchoptions;
             $specific = $item->getSpecificValueToDisplay($field, $values, $options);
             if (!empty($specific)) {
                 return $specific;
             }
         }
     }
     return $value;
 }
/**
 * Create a new name using a autoname field defined in a template
 *
 * @param $objectName      autoname template
 * @param $field           field to autoname
 * @param $isTemplate      true if create an object from a template
 * @param $itemtype        item type
 * @param $entities_id     limit generation to an entity (default -1)
 *
 * @return new auto string
**/
function autoName($objectName, $field, $isTemplate, $itemtype, $entities_id = -1)
{
    global $DB, $CFG_GLPI;
    $len = Toolbox::strlen($objectName);
    if ($isTemplate && $len > 8 && Toolbox::substr($objectName, 0, 4) === '&lt;' && Toolbox::substr($objectName, $len - 4, 4) === '&gt;') {
        $autoNum = Toolbox::substr($objectName, 4, $len - 8);
        $mask = '';
        if (preg_match("/\\#{1,10}/", $autoNum, $mask)) {
            $global = strpos($autoNum, '\\g') !== false && $itemtype != 'Infocom' ? 1 : 0;
            $autoNum = str_replace(array('\\y', '\\Y', '\\m', '\\d', '_', '%', '\\g'), array(date('y'), date('Y'), date('m'), date('d'), '\\_', '\\%', ''), $autoNum);
            $mask = $mask[0];
            $pos = strpos($autoNum, $mask) + 1;
            $len = Toolbox::strlen($mask);
            $like = str_replace('#', '_', $autoNum);
            if ($global == 1) {
                $query = "";
                $first = 1;
                $types = array('Computer', 'Monitor', 'NetworkEquipment', 'Peripheral', 'Phone', 'Printer');
                foreach ($types as $t) {
                    $table = getTableForItemType($t);
                    $query .= ($first ? "SELECT " : " UNION SELECT  ") . " {$field} AS code\n                         FROM `{$table}`\n                         WHERE `{$field}` LIKE '{$like}'\n                               AND `is_deleted` = '0'\n                               AND `is_template` = '0'";
                    if ($CFG_GLPI["use_autoname_by_entity"] && $entities_id >= 0) {
                        $query .= " AND `entities_id` = '{$entities_id}' ";
                    }
                    $first = 0;
                }
                $query = "SELECT CAST(SUBSTRING(code, {$pos}, {$len}) AS unsigned) AS no\n                      FROM ({$query}) AS codes";
            } else {
                $table = getTableForItemType($itemtype);
                $query = "SELECT CAST(SUBSTRING({$field}, {$pos}, {$len}) AS unsigned) AS no\n                      FROM `{$table}`\n                      WHERE `{$field}` LIKE '{$like}' ";
                if ($itemtype != 'Infocom') {
                    $query .= " AND `is_deleted` = '0'\n                           AND `is_template` = '0'";
                    if ($CFG_GLPI["use_autoname_by_entity"] && $entities_id >= 0) {
                        $query .= " AND `entities_id` = '{$entities_id}' ";
                    }
                }
            }
            $query = "SELECT MAX(Num.no) AS lastNo\n                   FROM (" . $query . ") AS Num";
            $resultNo = $DB->query($query);
            if ($DB->numrows($resultNo) > 0) {
                $data = $DB->fetch_assoc($resultNo);
                $newNo = $data['lastNo'] + 1;
            } else {
                $newNo = 0;
            }
            $objectName = str_replace(array($mask, '\\_', '\\%'), array(Toolbox::str_pad($newNo, $len, '0', STR_PAD_LEFT), '_', '%'), $autoNum);
        }
    }
    return $objectName;
}
Example #15
0
 function showTabs($options = array())
 {
     global $CFG_GLPI;
     // for objects not in table like central
     $ID = 0;
     if (isset($this->fields['id'])) {
         $ID = $this->fields['id'];
     }
     $target = $_SERVER['PHP_SELF'];
     $extraparamhtml = "";
     $extraparam = "";
     $withtemplate = "";
     if (is_array($options) && count($options)) {
         if (isset($options['withtemplate'])) {
             $withtemplate = $options['withtemplate'];
         }
         foreach ($options as $key => $val) {
             $extraparamhtml .= "&amp;{$key}={$val}";
             $extraparam .= "&{$key}={$val}";
         }
     }
     if (empty($withtemplate) && $ID && $this->getType() && $this->displaylist) {
         $glpilistitems =& $_SESSION['glpilistitems'][$this->getType()];
         $glpilisttitle =& $_SESSION['glpilisttitle'][$this->getType()];
         $glpilisturl =& $_SESSION['glpilisturl'][$this->getType()];
         if (empty($glpilisturl)) {
             $glpilisturl = $this->getSearchURL();
         }
         echo "<div id='menu_navigate'>";
         $next = $prev = $first = $last = -1;
         $current = false;
         if (is_array($glpilistitems)) {
             $current = array_search($ID, $glpilistitems);
             if ($current !== false) {
                 if (isset($glpilistitems[$current + 1])) {
                     $next = $glpilistitems[$current + 1];
                 }
                 if (isset($glpilistitems[$current - 1])) {
                     $prev = $glpilistitems[$current - 1];
                 }
                 $first = $glpilistitems[0];
                 if ($first == $ID) {
                     $first = -1;
                 }
                 $last = $glpilistitems[count($glpilistitems) - 1];
                 if ($last == $ID) {
                     $last = -1;
                 }
             }
         }
         $cleantarget = Html::cleanParametersURL($target);
         echo "<ul>";
         echo "<li><a href=\"javascript:showHideDiv('tabsbody','tabsbodyimg','" . $CFG_GLPI["root_doc"] . "/pics/deplier_down.png','" . $CFG_GLPI["root_doc"] . "/pics/deplier_up.png')\">";
         echo "<img alt='' name='tabsbodyimg' src=\"" . $CFG_GLPI["root_doc"] . "/pics/deplier_up.png\">";
         echo "</a></li>";
         echo "<li><a href=\"" . $glpilisturl . "\">";
         if ($glpilisttitle) {
             if (Toolbox::strlen($glpilisttitle) > $_SESSION['glpidropdown_chars_limit']) {
                 $glpilisttitle = Toolbox::substr($glpilisttitle, 0, $_SESSION['glpidropdown_chars_limit']) . "&hellip;";
             }
             echo $glpilisttitle;
         } else {
             echo __('List');
         }
         echo "</a>&nbsp;:&nbsp;</li>";
         if ($first > 0) {
             echo "<li><a href='{$cleantarget}?id={$first}{$extraparamhtml}'><img src='" . $CFG_GLPI["root_doc"] . "/pics/first.png' alt=\"" . __('First') . "\" title=\"" . __('First') . "\"></a></li>";
         } else {
             echo "<li><img src='" . $CFG_GLPI["root_doc"] . "/pics/first_off.png' alt=\"" . __('First') . "\" title=\"" . __('First') . "\"></li>";
         }
         if ($prev > 0) {
             echo "<li><a href='{$cleantarget}?id={$prev}{$extraparamhtml}'><img src='" . $CFG_GLPI["root_doc"] . "/pics/left.png' alt=\"" . __('Previous') . "\" title=\"" . __('Previous') . "\"></a></li>";
         } else {
             echo "<li><img src='" . $CFG_GLPI["root_doc"] . "/pics/left_off.png' alt=\"" . __('Previous') . "\" title=\"" . __('Previous') . "\"></li>";
         }
         if ($current !== false) {
             echo "<li>" . ($current + 1) . "/" . count($glpilistitems) . "</li>";
         }
         if ($next > 0) {
             echo "<li><a href='{$cleantarget}?id={$next}{$extraparamhtml}'><img src='" . $CFG_GLPI["root_doc"] . "/pics/right.png' alt=\"" . __('Next') . "\" title=\"" . __('Next') . "\"></a></li>";
         } else {
             echo "<li><img src='" . $CFG_GLPI["root_doc"] . "/pics/right_off.png' alt=\"" . __('Next') . "\" title=\"" . __('Next') . "\"></li>";
         }
         if ($last > 0) {
             echo "<li><a href='{$cleantarget}?id={$last}{$extraparamhtml}'><img src=\"" . $CFG_GLPI["root_doc"] . "/pics/last.png\" alt=\"" . __('Last') . "\" title=\"" . __('Last') . "\"></a></li>";
         } else {
             echo "<li><img src='" . $CFG_GLPI["root_doc"] . "/pics/last_off.png' alt=\"" . __('Last') . "\" title=\"" . __('Last') . "\"></li>";
         }
         echo "</ul></div>";
         echo "<div class='sep'></div>";
     }
     echo "<div id='tabspanel' class='center-h'></div>";
     $onglets = $this->defineTabs($options);
     $display_all = true;
     if (isset($onglets['no_all_tab'])) {
         $display_all = false;
         unset($onglets['no_all_tab']);
     }
     $class = $this->getType();
     if ($_SESSION['glpi_use_mode'] == Session::DEBUG_MODE && ($ID > 0 || $this->showdebug) && (method_exists($class, 'showDebug') || in_array($class, $CFG_GLPI["infocom_types"]) || in_array($class, $CFG_GLPI["reservation_types"]))) {
         $onglets[-2] = __('Debug');
     }
     if (count($onglets)) {
         $tabpage = $this->getTabsURL();
         $tabs = array();
         foreach ($onglets as $key => $val) {
             $tabs[$key] = array('title' => $val, 'url' => $tabpage, 'params' => "target={$target}&itemtype=" . $this->getType() . "&glpi_tab={$key}&id={$ID}{$extraparam}");
         }
         $plug_tabs = Plugin::getTabs($target, $this, $withtemplate);
         $tabs += $plug_tabs;
         // Not all tab for templates and if only 1 tab
         if ($display_all && empty($withtemplate) && count($tabs) > 1) {
             $tabs[-1] = array('title' => __('All'), 'url' => $tabpage, 'params' => "target={$target}&itemtype=" . $this->getType() . "&glpi_tab=-1&id={$ID}{$extraparam}");
         }
         Ajax::createTabs('tabspanel', 'tabcontent', $tabs, $this->getType(), "'100%'");
     }
 }
Example #16
0
                $ID = $data['id'];
                $addcomment = "";
                $title = $outputval;
                if (isset($data["comment"])) {
                    $title = sprintf(__('%1$s - %2$s'), $title, $data["comment"]);
                }
                if ($_SESSION["glpiis_ids_visible"] || strlen($outputval) == 0) {
                    //TRANS: %1$s is the name, %2$s the ID
                    $outputval = sprintf(__('%1$s (%2$s)'), $outputval, $ID);
                }
                if ($multi && $data["entities_id"] != $prev) {
                    if ($prev >= 0) {
                        echo "</optgroup>";
                    }
                    $prev = $data["entities_id"];
                    echo "<optgroup label=\"" . Dropdown::getDropdownName("glpi_entities", $prev) . "\">";
                }
                echo "<option value='{$ID}' title=\"" . Html::cleanInputText($title) . "\">" . Toolbox::substr($outputval, 0, $_POST["limit"]) . "</option>";
            }
            if ($multi) {
                echo "</optgroup>";
            }
        }
        echo "</select>";
    }
}
if (isset($_POST["comment"]) && $_POST["comment"]) {
    $paramscomment = array('value' => '__VALUE__', 'table' => $table);
    Ajax::updateItemOnSelectEvent("dropdown_" . $_POST["myname"] . $_POST["rand"], "comment_" . $_POST["myname"] . $_POST["rand"], $CFG_GLPI["root_doc"] . "/ajax/comments.php", $paramscomment);
}
Ajax::commonDropdownUpdateItem($_POST);
if (strlen($_POST['searchText']) > 0 && $_POST['searchText'] != $CFG_GLPI["ajax_wildcard"]) {
    $search = Search::makeTextSearch($_POST['searchText']);
    $where .= " AND (`name` " . $search . "\n                    OR `id` = '" . $_POST['searchText'] . "'";
    $where .= ")";
}
$NBMAX = $CFG_GLPI["dropdown_max"];
$LIMIT = "LIMIT 0, {$NBMAX}";
if ($_POST['searchText'] == $CFG_GLPI["ajax_wildcard"]) {
    $LIMIT = "";
}
$query = "SELECT *\n          FROM `" . $_POST['table'] . "`\n          {$where}\n          ORDER BY `name`\n          {$LIMIT}";
$result = $DB->query($query);
echo "<select name='" . $_POST['myname'] . "' id='" . $_POST['myname'] . "' size='1'>";
if ($_POST['searchText'] != $CFG_GLPI["ajax_wildcard"] && $DB->numrows($result) == $NBMAX) {
    echo "<option value='0'>--" . __('Limited view') . "--</option>";
}
echo "<option value='0'>" . Dropdown::EMPTY_VALUE . "</option>";
if ($DB->numrows($result)) {
    while ($data = $DB->fetch_array($result)) {
        $output = $data['name'];
        if (empty($output) || $_SESSION['glpiis_ids_visible']) {
            $output .= " (" . $data['id'] . ")";
        }
        $selected = "";
        if ($data['id'] == $_POST['value']) {
            $selected = "selected='selected'";
        }
        echo "<option value='" . $data['id'] . "' {$selected} title=\"" . Html::cleanInputText($output) . "\">" . Toolbox::substr($output, 0, $_SESSION["glpidropdown_chars_limit"]) . "</option>";
    }
}
echo "</select>";
Example #18
0
 function prepareInputForAdd($input)
 {
     if (!isset($input['url']) || !isset($input['type'])) {
         return false;
     }
     $taburl = parse_url(rawurldecode($input['url']));
     $index = strpos($taburl["path"], "plugins");
     if (!$index) {
         $index = strpos($taburl["path"], "front");
     }
     $input['path'] = Toolbox::substr($taburl["path"], $index, Toolbox::strlen($taburl["path"]) - $index);
     $query_tab = array();
     if (isset($taburl["query"])) {
         parse_str($taburl["query"], $query_tab);
     }
     $input['query'] = Toolbox::append_params($this->prepareQueryToStore($input['type'], $query_tab, $input['itemtype']));
     return $input;
 }
Example #19
0
 /**
  * Print generic search form
  *
  *@param $itemtype type to display the form
  *@param $params parameters array may include field, contains, sort, is_deleted, link, link2, contains2, field2, type2
  *
  *@return nothing (displays)
  *
  **/
 function showGenericSearch($params)
 {
     global $CFG_GLPI;
     $itemtype = "PluginResourcesDirectory";
     $itemtable = $this->table;
     // Default values of parameters
     $p['link'] = array();
     //
     $p['field'] = array();
     $p['contains'] = array();
     $p['searchtype'] = array();
     $p['sort'] = '';
     $p['is_deleted'] = 0;
     $p['link2'] = '';
     //
     $p['contains2'] = '';
     $p['field2'] = '';
     $p['itemtype2'] = '';
     $p['searchtype2'] = '';
     foreach ($params as $key => $val) {
         $p[$key] = $val;
     }
     $options = Search::getCleanedOptions("PluginResourcesDirectory");
     $target = $CFG_GLPI["root_doc"] . "/plugins/resources/front/directory.php";
     // Instanciate an object to access method
     $item = NULL;
     if (class_exists($itemtype)) {
         $item = new $itemtype();
     }
     $linked = Search::getMetaItemtypeAvailable($itemtype);
     echo "<form name='searchform{$itemtype}' method='get' action=\"{$target}\">";
     echo "<table class='tab_cadre_fixe' >";
     echo "<tr class='tab_bg_1'>";
     echo "<td>";
     echo "<table>";
     // Display normal search parameters
     for ($i = 0; $i < $_SESSION["glpisearchcount"][$itemtype]; $i++) {
         echo "<tr><td class='left' width='50%'>";
         // First line display add / delete images for normal and meta search items
         if ($i == 0) {
             echo "<input type='hidden' disabled  id='add_search_count' name='add_search_count' value='1'>";
             echo "<a href='#' onClick = \"document.getElementById('add_search_count').disabled=false;document.forms['searchform{$itemtype}'].submit();\">";
             echo "<img src=\"" . $CFG_GLPI["root_doc"] . "/pics/plus.png\" alt='+' title='" . __s('Add a search criterion') . "'></a>&nbsp;&nbsp;&nbsp;&nbsp;";
             if ($_SESSION["glpisearchcount"][$itemtype] > 1) {
                 echo "<input type='hidden' disabled  id='delete_search_count' name='delete_search_count' value='1'>";
                 echo "<a href='#' onClick = \"document.getElementById('delete_search_count').disabled=false;document.forms['searchform{$itemtype}'].submit();\">";
                 echo "<img src=\"" . $CFG_GLPI["root_doc"] . "/pics/moins.png\" alt='-' title='" . __s('Delete a search criterion') . "'></a>&nbsp;&nbsp;&nbsp;&nbsp;";
             }
             if (is_array($linked) && count($linked) > 0) {
                 echo "<input type='hidden' disabled id='add_search_count2' name='add_search_count2' value='1'>";
                 echo "<a href='#' onClick = \"document.getElementById('add_search_count2').disabled=false;document.forms['searchform{$itemtype}'].submit();\">";
                 echo "<img src=\"" . $CFG_GLPI["root_doc"] . "/pics/meta_plus.png\" alt='+' title='" . __s('Add a global search criterion') . "'></a>&nbsp;&nbsp;&nbsp;&nbsp;";
                 if ($_SESSION["glpisearchcount2"][$itemtype] > 0) {
                     echo "<input type='hidden' disabled  id='delete_search_count2' name='delete_search_count2' value='1'>";
                     echo "<a href='#' onClick = \"document.getElementById('delete_search_count2').disabled=false;document.forms['searchform{$itemtype}'].submit();\">";
                     echo "<img src=\"" . $CFG_GLPI["root_doc"] . "/pics/meta_moins.png\" alt='-' title='" . __s('Delete a global search criterion') . "'></a>&nbsp;&nbsp;&nbsp;&nbsp;";
                 }
             }
             $itemtable = getTableForItemType($itemtype);
         }
         // Display link item
         if ($i > 0) {
             echo "<select name='link[{$i}]'>";
             echo "<option value='AND' ";
             if (is_array($p["link"]) && isset($p["link"][$i]) && $p["link"][$i] == "AND") {
                 echo "selected";
             }
             echo ">AND</option>\n";
             echo "<option value='OR' ";
             if (is_array($p["link"]) && isset($p["link"][$i]) && $p["link"][$i] == "OR") {
                 echo "selected";
             }
             echo ">OR</option>\n";
             echo "<option value='AND NOT' ";
             if (is_array($p["link"]) && isset($p["link"][$i]) && $p["link"][$i] == "AND NOT") {
                 echo "selected";
             }
             echo ">AND NOT</option>\n";
             echo "<option value='OR NOT' ";
             if (is_array($p["link"]) && isset($p["link"][$i]) && $p["link"][$i] == "OR NOT") {
                 echo "selected";
             }
             echo ">OR NOT</option>";
             echo "</select>&nbsp;";
         }
         // display select box to define serach item
         echo "<select id='Search{$itemtype}{$i}' name=\"field[{$i}]\" size='1'>";
         echo "<option value='view' ";
         if (is_array($p['field']) && isset($p['field'][$i]) && $p['field'][$i] == "view") {
             echo "selected";
         }
         echo ">" . __('Items seen') . "</option>\n";
         reset($options);
         $first_group = true;
         $selected = 'view';
         foreach ($options as $key => $val) {
             // print groups
             if (!is_array($val)) {
                 if (!$first_group) {
                     echo "</optgroup>\n";
                 } else {
                     $first_group = false;
                 }
                 echo "<optgroup label='{$val}'>";
             } else {
                 if (!isset($val['nosearch']) || $val['nosearch'] == false) {
                     echo "<option title=\"" . Html::cleanInputText($val["name"]) . "\" value='{$key}'";
                     if (is_array($p['field']) && isset($p['field'][$i]) && $key == $p['field'][$i]) {
                         echo "selected";
                         $selected = $key;
                     }
                     echo ">" . Toolbox::substr($val["name"], 0, 28) . "</option>\n";
                 }
             }
         }
         if (!$first_group) {
             echo "</optgroup>\n";
         }
         echo "<option value='all' ";
         if (is_array($p['field']) && isset($p['field'][$i]) && $p['field'][$i] == "all") {
             echo "selected";
         }
         echo ">" . __('All') . "</option>";
         echo "</select>&nbsp;\n";
         echo "</td><td class='left'>";
         echo "<div id='SearchSpan{$itemtype}{$i}'>\n";
         $_POST['itemtype'] = $itemtype;
         $_POST['num'] = $i;
         $_POST['field'] = $selected;
         $_POST['searchtype'] = is_array($p['searchtype']) && isset($p['searchtype'][$i]) ? $p['searchtype'][$i] : "";
         $_POST['value'] = is_array($p['contains']) && isset($p['contains'][$i]) ? stripslashes($p['contains'][$i]) : "";
         include GLPI_ROOT . "/ajax/searchoption.php";
         echo "</div>\n";
         $params = array('field' => '__VALUE__', 'itemtype' => $itemtype, 'num' => $i, 'value' => $_POST["value"], 'searchtype' => $_POST["searchtype"]);
         Ajax::updateItemOnSelectEvent("Search{$itemtype}{$i}", "SearchSpan{$itemtype}{$i}", $CFG_GLPI["root_doc"] . "/ajax/searchoption.php", $params, false);
         echo "</td></tr>\n";
     }
     $metanames = array();
     if (is_array($linked) && count($linked) > 0) {
         for ($i = 0; $i < $_SESSION["glpisearchcount2"][$itemtype]; $i++) {
             echo "<tr><td class='left'>";
             $rand = mt_rand();
             // Display link item (not for the first item)
             echo "<select name='link2[{$i}]'>";
             echo "<option value='AND' ";
             if (is_array($p['link2']) && isset($p['link2'][$i]) && $p['link2'][$i] == "AND") {
                 echo "selected";
             }
             echo ">AND</option>\n";
             echo "<option value='OR' ";
             if (is_array($p['link2']) && isset($p['link2'][$i]) && $p['link2'][$i] == "OR") {
                 echo "selected";
             }
             echo ">OR</option>\n";
             echo "<option value='AND NOT' ";
             if (is_array($p['link2']) && isset($p['link2'][$i]) && $p['link2'][$i] == "AND NOT") {
                 echo "selected";
             }
             echo ">AND NOT</option>\n";
             echo "<option value='OR NOT' ";
             if (is_array($p['link2']) && isset($p['link2'][$i]) && $p['link2'][$i] == "OR NOT") {
                 echo "selected";
             }
             echo ">OR NOT</option>\n";
             echo "</select>&nbsp;";
             // Display select of the linked item type available
             echo "<select name='itemtype2[{$i}]' id='itemtype2_" . $itemtype . "_" . $i . "_{$rand}'>";
             echo "<option value=''>" . Dropdown::EMPTY_VALUE . "</option>";
             foreach ($linked as $key) {
                 if (!isset($metanames[$key])) {
                     $linkitem = new $key();
                     $metanames[$key] = $linkitem->getTypeName();
                 }
                 echo "<option value='{$key}'>" . Toolbox::substr($metanames[$key], 0, 20) . "</option>\n";
             }
             echo "</select>&nbsp;";
             echo "</td><td>";
             // Ajax script for display search met& item
             echo "<span id='show_" . $itemtype . "_" . $i . "_{$rand}'>&nbsp;</span>\n";
             $params = array('itemtype' => '__VALUE__', 'num' => $i, 'field' => is_array($p['field2']) && isset($p['field2'][$i]) ? $p['field2'][$i] : "", 'value' => is_array($p['contains2']) && isset($p['contains2'][$i]) ? $p['contains2'][$i] : "", 'searchtype2' => is_array($p['searchtype2']) && isset($p['searchtype2'][$i]) ? $p['searchtype2'][$i] : "");
             Ajax::updateItemOnSelectEvent("itemtype2_" . $itemtype . "_" . $i . "_{$rand}", "show_" . $itemtype . "_" . $i . "_{$rand}", $CFG_GLPI["root_doc"] . "/ajax/updateMetaSearch.php", $params, false);
             if (is_array($p['itemtype2']) && isset($p['itemtype2'][$i]) && !empty($p['itemtype2'][$i])) {
                 $params['itemtype'] = $p['itemtype2'][$i];
                 Ajax::updateItem("show_" . $itemtype . "_" . $i . "_{$rand}", $CFG_GLPI["root_doc"] . "/ajax/updateMetaSearch.php", $params, false);
                 echo "<script type='text/javascript' >";
                 echo "window.document.getElementById('itemtype2_" . $itemtype . "_" . $i . "_{$rand}').value='" . $p['itemtype2'][$i] . "';";
                 echo "</script>\n";
             }
             echo "</td></tr></table>";
             echo "</td></tr>\n";
         }
     }
     echo "</table>\n";
     echo "</td>\n";
     echo "<td width='150px'>";
     echo "<table width='100%'>";
     // Display deleted selection
     echo "<tr>";
     // Display submit button
     echo "<td width='80' class='center'>";
     echo "<input type='submit' value=\"" . _sx('button', 'Search') . "\" class='submit' >";
     echo "</td><td>";
     Bookmark::showSaveButton(Bookmark::SEARCH, $itemtype);
     echo "<a href='{$target}?reset=reset' >";
     echo "&nbsp;&nbsp;<img title=\"" . __s('Blank') . "\" alt=\"" . __s('Blank') . "\" src='" . $CFG_GLPI["root_doc"] . "/templates/infotel/pics/reset.png' class='calendrier'></a>";
     echo "</td></tr></table>\n";
     echo "</td></tr>";
     echo "</table>\n";
     // For dropdown
     echo "<input type='hidden' name='itemtype' value='{$itemtype}'>";
     // Reset to start when submit new search
     echo "<input type='hidden' name='start' value='0'>";
     Html::closeForm();
 }
Example #20
0
 /**
  * Show tabs
  *
  * @since version 0.85
  * @param $options array of parameters to add to URLs and ajax
  *     - withtemplate is a template view ?
  * @deprecated  Only for compatibility usage
  * @return Nothing ()
  **/
 function showNavigationHeaderOld($options = array())
 {
     global $CFG_GLPI;
     // for objects not in table like central
     if (isset($this->fields['id'])) {
         $ID = $this->fields['id'];
     } else {
         $ID = 0;
     }
     $target = $_SERVER['PHP_SELF'];
     $extraparamhtml = "";
     $extraparam = "";
     $withtemplate = "";
     if (is_array($options) && count($options)) {
         if (isset($options['withtemplate'])) {
             $withtemplate = $options['withtemplate'];
         }
         foreach ($options as $key => $val) {
             // Do not include id options
             if ($key[0] != '_' && $key != 'id') {
                 $extraparamhtml .= "&amp;{$key}={$val}";
                 $extraparam .= "&{$key}={$val}";
             }
         }
     }
     if (empty($withtemplate) && !$this->isNewID($ID) && $this->getType() && $this->displaylist) {
         $glpilistitems =& $_SESSION['glpilistitems'][$this->getType()];
         $glpilisttitle =& $_SESSION['glpilisttitle'][$this->getType()];
         $glpilisturl =& $_SESSION['glpilisturl'][$this->getType()];
         if (empty($glpilisturl)) {
             $glpilisturl = $this->getSearchURL();
         }
         echo "<div id='menu_navigate'>";
         $next = $prev = $first = $last = -1;
         $current = false;
         if (is_array($glpilistitems)) {
             $current = array_search($ID, $glpilistitems);
             if ($current !== false) {
                 if (isset($glpilistitems[$current + 1])) {
                     $next = $glpilistitems[$current + 1];
                 }
                 if (isset($glpilistitems[$current - 1])) {
                     $prev = $glpilistitems[$current - 1];
                 }
                 $first = $glpilistitems[0];
                 if ($first == $ID) {
                     $first = -1;
                 }
                 $last = $glpilistitems[count($glpilistitems) - 1];
                 if ($last == $ID) {
                     $last = -1;
                 }
             }
         }
         $cleantarget = HTML::cleanParametersURL($target);
         echo "<ul>";
         //          echo "<li><a href=\"javascript:showHideDiv('tabsbody','tabsbodyimg','".$CFG_GLPI["root_doc"].
         //                     "/pics/deplier_down.png','".$CFG_GLPI["root_doc"]."/pics/deplier_up.png')\">";
         //          echo "<img alt='' name='tabsbodyimg' src=\"".$CFG_GLPI["root_doc"]."/pics/deplier_up.png\">";
         //          echo "</a></li>";
         echo "<li><a href=\"javascript:toggleTableDisplay('mainformtable','tabsbodyimg','" . $CFG_GLPI["root_doc"] . "/pics/deplier_down.png','" . $CFG_GLPI["root_doc"] . "/pics/deplier_up.png')\">";
         echo "<img alt='' name='tabsbodyimg' src=\"" . $CFG_GLPI["root_doc"] . "/pics/deplier_up.png\" class='pointer'>";
         echo "</a></li>";
         echo "<li><a href=\"" . $glpilisturl . "\">";
         if ($glpilisttitle) {
             if (Toolbox::strlen($glpilisttitle) > $_SESSION['glpidropdown_chars_limit']) {
                 $glpilisttitle = Toolbox::substr($glpilisttitle, 0, $_SESSION['glpidropdown_chars_limit']) . "&hellip;";
             }
             echo $glpilisttitle;
         } else {
             _e('List');
         }
         echo "</a></li>";
         if ($first >= 0) {
             echo "<li><a href='{$cleantarget}?id={$first}{$extraparamhtml}'><img src='" . $CFG_GLPI["root_doc"] . "/pics/first.png' alt=\"" . __s('First') . "\" title=\"" . __s('First') . "\" class='pointer'></a></li>";
         } else {
             echo "<li><img src='" . $CFG_GLPI["root_doc"] . "/pics/first_off.png' alt=\"" . __s('First') . "\" title=\"" . __s('First') . "\" class='pointer'></li>";
         }
         if ($prev >= 0) {
             echo "<li><a href='{$cleantarget}?id={$prev}{$extraparamhtml}'><img src='" . $CFG_GLPI["root_doc"] . "/pics/left.png' alt=\"" . __s('Previous') . "\" title=\"" . __s('Previous') . "\" class='pointer'></a></li>";
         } else {
             echo "<li><img src='" . $CFG_GLPI["root_doc"] . "/pics/left_off.png' alt=\"" . __s('Previous') . "\" title=\"" . __s('Previous') . "\" class='pointer'></li>";
         }
         if ($current !== false) {
             echo "<li>" . ($current + 1) . "/" . count($glpilistitems) . "</li>";
         }
         if ($next >= 0) {
             echo "<li><a href='{$cleantarget}?id={$next}{$extraparamhtml}'><img src='" . $CFG_GLPI["root_doc"] . "/pics/right.png' alt=\"" . __s('Next') . "\" title=\"" . __s('Next') . "\" class='pointer'></a></li>";
         } else {
             echo "<li><img src='" . $CFG_GLPI["root_doc"] . "/pics/right_off.png' alt=\"" . __s('Next') . "\" title=\"" . __s('Next') . "\" class='pointer'></li>";
         }
         if ($last >= 0) {
             echo "<li><a href='{$cleantarget}?id={$last}{$extraparamhtml}'><img src=\"" . $CFG_GLPI["root_doc"] . "/pics/last.png\" alt=\"" . __s('Last') . "\" title=\"" . __s('Last') . "\" class='pointer'></a></li>";
         } else {
             echo "<li><img src='" . $CFG_GLPI["root_doc"] . "/pics/last_off.png' alt=\"" . __s('Last') . "\" title=\"" . __s('Last') . "\" class='pointer'></li>";
         }
         echo "</ul></div>";
         echo "<div class='sep'></div>";
     }
 }
Example #21
0
 /**
  * Make a select box for Ticket my devices
  *
  * @param $userID          User ID for my device section (default 0)
  * @param $entity_restrict restrict to a specific entity (default -1)
  * @param $itemtype        of selected item (default 0)
  * @param $items_id        of selected item (default 0)
  *
  * @return nothing (print out an HTML select box)
  **/
 static function dropdownMyDevices($userID = 0, $entity_restrict = -1, $itemtype = 0, $items_id = 0)
 {
     global $DB, $CFG_GLPI;
     if ($userID == 0) {
         $userID = Session::getLoginUserID();
     }
     $rand = mt_rand();
     $already_add = array();
     if ($_SESSION["glpiactiveprofile"]["helpdesk_hardware"] & pow(2, self::HELPDESK_MY_HARDWARE)) {
         $my_devices = "";
         $my_item = $itemtype . '_' . $items_id;
         // My items
         foreach ($CFG_GLPI["linkuser_types"] as $itemtype) {
             if (($item = getItemForItemtype($itemtype)) && parent::isPossibleToAssignType($itemtype)) {
                 $itemtable = getTableForItemType($itemtype);
                 $query = "SELECT *\n                             FROM `{$itemtable}`\n                             WHERE `users_id` = '{$userID}'";
                 if ($item->maybeDeleted()) {
                     $query .= " AND `is_deleted` = '0' ";
                 }
                 if ($item->maybeTemplate()) {
                     $query .= " AND `is_template` = '0' ";
                 }
                 if (in_array($itemtype, $CFG_GLPI["helpdesk_visible_types"])) {
                     $query .= " AND `is_helpdesk_visible` = '1' ";
                 }
                 $query .= getEntitiesRestrictRequest("AND", $itemtable, "", $entity_restrict, $item->maybeRecursive()) . "\n                         ORDER BY `name` ";
                 $result = $DB->query($query);
                 $nb = $DB->numrows($result);
                 if ($DB->numrows($result) > 0) {
                     $type_name = $item->getTypeName($nb);
                     while ($data = $DB->fetch_assoc($result)) {
                         $output = $data["name"];
                         if (empty($output) || $_SESSION["glpiis_ids_visible"]) {
                             $output = sprintf(__('%1$s (%2$s)'), $output, $data['id']);
                         }
                         $output = sprintf(__('%1$s - %2$s'), $type_name, $output);
                         if ($itemtype != 'Software') {
                             if (!empty($data['serial'])) {
                                 $output = sprintf(__('%1$s - %2$s'), $output, $data['serial']);
                             }
                             if (!empty($data['otherserial'])) {
                                 $output = sprintf(__('%1$s - %2$s'), $output, $data['otherserial']);
                             }
                         }
                         $my_devices .= "<option title=\"{$output}\" value='" . $itemtype . "_" . $data["id"] . "' " . ($my_item == $itemtype . "_" . $data["id"] ? "selected" : "") . ">" . Toolbox::substr($output, 0, $_SESSION["glpidropdown_chars_limit"]) . "</option>";
                         $already_add[$itemtype][] = $data["id"];
                     }
                 }
             }
         }
         if (!empty($my_devices)) {
             $my_devices = "<optgroup label=\"" . __s('My devices') . "\">" . $my_devices . "</optgroup>";
         }
         // My group items
         if (Session::haveRight("show_group_hardware", "1")) {
             $group_where = "";
             $query = "SELECT `glpi_groups_users`.`groups_id`, `glpi_groups`.`name`\n                            FROM `glpi_groups_users`\n                            LEFT JOIN `glpi_groups`\n                              ON (`glpi_groups`.`id` = `glpi_groups_users`.`groups_id`)\n                            WHERE `glpi_groups_users`.`users_id` = '{$userID}' " . getEntitiesRestrictRequest("AND", "glpi_groups", "", $entity_restrict, true);
             $result = $DB->query($query);
             $first = true;
             if ($DB->numrows($result) > 0) {
                 while ($data = $DB->fetch_assoc($result)) {
                     if ($first) {
                         $first = false;
                     } else {
                         $group_where .= " OR ";
                     }
                     $a_groups = getAncestorsOf("glpi_groups", $data["groups_id"]);
                     $a_groups[$data["groups_id"]] = $data["groups_id"];
                     $group_where .= " `groups_id` IN (" . implode(',', $a_groups) . ") ";
                 }
                 $tmp_device = "";
                 foreach ($CFG_GLPI["linkgroup_types"] as $itemtype) {
                     if (($item = getItemForItemtype($itemtype)) && parent::isPossibleToAssignType($itemtype)) {
                         $itemtable = getTableForItemType($itemtype);
                         $query = "SELECT *\n                                    FROM `{$itemtable}`\n                                    WHERE ({$group_where}) " . getEntitiesRestrictRequest("AND", $itemtable, "", $entity_restrict, $item->maybeRecursive());
                         if ($item->maybeDeleted()) {
                             $query .= " AND `is_deleted` = '0' ";
                         }
                         if ($item->maybeTemplate()) {
                             $query .= " AND `is_template` = '0' ";
                         }
                         $result = $DB->query($query);
                         if ($DB->numrows($result) > 0) {
                             $type_name = $item->getTypeName();
                             if (!isset($already_add[$itemtype])) {
                                 $already_add[$itemtype] = array();
                             }
                             while ($data = $DB->fetch_assoc($result)) {
                                 if (!in_array($data["id"], $already_add[$itemtype])) {
                                     $output = '';
                                     if (isset($data["name"])) {
                                         $output = $data["name"];
                                     }
                                     if (empty($output) || $_SESSION["glpiis_ids_visible"]) {
                                         $output = sprintf(__('%1$s (%2$s)'), $output, $data['id']);
                                     }
                                     $output = sprintf(__('%1$s - %2$s'), $type_name, $output);
                                     if (isset($data['serial'])) {
                                         $output = sprintf(__('%1$s - %2$s'), $output, $data['serial']);
                                     }
                                     if (isset($data['otherserial'])) {
                                         $output = sprintf(__('%1$s - %2$s'), $output, $data['otherserial']);
                                     }
                                     $tmp_device .= "<option title=\"{$output}\" value='" . $itemtype . "_" . $data["id"] . "' " . ($my_item == $itemtype . "_" . $data["id"] ? "selected" : "") . ">" . Toolbox::substr($output, 0, $_SESSION["glpidropdown_chars_limit"]) . "</option>";
                                     $already_add[$itemtype][] = $data["id"];
                                 }
                             }
                         }
                     }
                 }
                 if (!empty($tmp_device)) {
                     $my_devices .= "<optgroup label=\"" . __s('Devices own by my groups') . "\">" . $tmp_device . "</optgroup>";
                 }
             }
         }
         // Get linked items to computers
         if (isset($already_add['Computer']) && count($already_add['Computer'])) {
             $search_computer = " XXXX IN (" . implode(',', $already_add['Computer']) . ') ';
             $tmp_device = "";
             // Direct Connection
             $types = array('Monitor', 'Peripheral', 'Phone', 'Printer');
             foreach ($types as $itemtype) {
                 if (in_array($itemtype, $_SESSION["glpiactiveprofile"]["helpdesk_item_type"]) && ($item = getItemForItemtype($itemtype))) {
                     $itemtable = getTableForItemType($itemtype);
                     if (!isset($already_add[$itemtype])) {
                         $already_add[$itemtype] = array();
                     }
                     $query = "SELECT DISTINCT `{$itemtable}`.*\n                            FROM `glpi_computers_items`\n                            LEFT JOIN `{$itemtable}`\n                                 ON (`glpi_computers_items`.`items_id` = `{$itemtable}`.`id`)\n                            WHERE `glpi_computers_items`.`itemtype` = '{$itemtype}'\n                                  AND  " . str_replace("XXXX", "`glpi_computers_items`.`computers_id`", $search_computer);
                     if ($item->maybeDeleted()) {
                         $query .= " AND `{$itemtable}`.`is_deleted` = '0' ";
                     }
                     if ($item->maybeTemplate()) {
                         $query .= " AND `{$itemtable}`.`is_template` = '0' ";
                     }
                     $query .= getEntitiesRestrictRequest("AND", $itemtable, "", $entity_restrict) . "\n                            ORDER BY `{$itemtable}`.`name`";
                     $result = $DB->query($query);
                     if ($DB->numrows($result) > 0) {
                         $type_name = $item->getTypeName();
                         while ($data = $DB->fetch_assoc($result)) {
                             if (!in_array($data["id"], $already_add[$itemtype])) {
                                 $output = $data["name"];
                                 if (empty($output) || $_SESSION["glpiis_ids_visible"]) {
                                     $output = sprintf(__('%1$s (%2$s)'), $output, $data['id']);
                                 }
                                 $output = sprintf(__('%1$s - %2$s'), $type_name, $output);
                                 if ($itemtype != 'Software') {
                                     $output = sprintf(__('%1$s - %2$s'), $output, $data['otherserial']);
                                 }
                                 $tmp_device .= "<option title=\"{$output}\" value='" . $itemtype . "_" . $data["id"] . "' " . ($my_item == $itemtype . "_" . $data["id"] ? "selected" : "") . ">" . Toolbox::substr($output, 0, $_SESSION["glpidropdown_chars_limit"]) . "</option>";
                                 $already_add[$itemtype][] = $data["id"];
                             }
                         }
                     }
                 }
             }
             if (!empty($tmp_device)) {
                 $my_devices .= "<optgroup label=\"" . __s('Connected devices') . "\">" . $tmp_device . "</optgroup>";
             }
             // Software
             if (in_array('Software', $_SESSION["glpiactiveprofile"]["helpdesk_item_type"])) {
                 $query = "SELECT DISTINCT `glpi_softwareversions`.`name` AS version,\n                                `glpi_softwares`.`name` AS name, `glpi_softwares`.`id`\n                         FROM `glpi_computers_softwareversions`, `glpi_softwares`,\n                              `glpi_softwareversions`\n                         WHERE `glpi_computers_softwareversions`.`softwareversions_id` =\n                                   `glpi_softwareversions`.`id`\n                               AND `glpi_softwareversions`.`softwares_id` = `glpi_softwares`.`id`\n                               AND " . str_replace("XXXX", "`glpi_computers_softwareversions`.`computers_id`", $search_computer) . "\n                               AND `glpi_softwares`.`is_helpdesk_visible` = '1' " . getEntitiesRestrictRequest("AND", "glpi_softwares", "", $entity_restrict) . "\n                         ORDER BY `glpi_softwares`.`name`";
                 $result = $DB->query($query);
                 if ($DB->numrows($result) > 0) {
                     $tmp_device = "";
                     $item = new Software();
                     $type_name = $item->getTypeName();
                     if (!isset($already_add['Software'])) {
                         $already_add['Software'] = array();
                     }
                     while ($data = $DB->fetch_assoc($result)) {
                         if (!in_array($data["id"], $already_add['Software'])) {
                             $output = sprintf(__('%1$s - %2$s'), $type_name, $data["name"]);
                             $output = sprintf(__('%1$s (%2$s)'), $output, sprintf(__('%1$s: %2$s'), __('version'), $data["version"]));
                             if ($_SESSION["glpiis_ids_visible"]) {
                                 $output = sprintf(__('%1$s (%2$s)'), $output, $data["id"]);
                             }
                             $tmp_device .= "<option title=\"{$output}\" value='Software_" . $data["id"] . "' " . ($my_item == 'Software' . "_" . $data["id"] ? "selected" : "") . ">" . Toolbox::substr($output, 0, $_SESSION["glpidropdown_chars_limit"]) . "</option>";
                             $already_add['Software'][] = $data["id"];
                         }
                     }
                     if (!empty($tmp_device)) {
                         $my_devices .= "<optgroup label=\"" . _sn('Installed software', 'Installed software', 2) . "\">";
                         $my_devices .= $tmp_device . "</optgroup>";
                     }
                 }
             }
         }
         echo "<div id='tracking_my_devices'>";
         echo "<select id='my_items' name='_my_items'>";
         echo "<option value=''>--- ";
         echo __('General') . " ---</option>{$my_devices}</select></div>";
         // Auto update summary of active or just solved tickets
         $params = array('my_items' => '__VALUE__');
         Ajax::updateItemOnSelectEvent("my_items", "item_ticket_selection_information", $CFG_GLPI["root_doc"] . "/ajax/ticketiteminformation.php", $params);
     }
 }
 /**
  * Show webapplications associated to an item
  *
  * @since version 0.84
  *
  * @param $item            Supplier object for which associated webapplications must be displayed
  * @param $withtemplate    (default '')
  **/
 static function showForSupplier(Supplier $item, $withtemplate = '')
 {
     global $DB, $CFG_GLPI;
     $ID = $item->getField('id');
     if ($item->isNewID($ID)) {
         return false;
     }
     if (!Session::haveRight("plugin_webapplications", READ)) {
         return false;
     }
     if (!$item->can($item->fields['id'], READ)) {
         return false;
     }
     if (empty($withtemplate)) {
         $withtemplate = 0;
     }
     $rand = mt_rand();
     $is_recursive = $item->isRecursive();
     $query = "SELECT `glpi_entities`.`id` AS entity,\n                        `glpi_plugin_webapplications_webapplications`.`id` AS assocID,\n                       `glpi_plugin_webapplications_webapplications`.`name` AS assocName,\n                       `glpi_plugin_webapplications_webapplications`.*\n                FROM `glpi_plugin_webapplications_webapplications`\n                LEFT JOIN `glpi_entities` ON (`glpi_plugin_webapplications_webapplications`.`entities_id`=`glpi_entities`.`id`)\n                WHERE `glpi_plugin_webapplications_webapplications`.`suppliers_id` = '{$ID}' ";
     $query .= getEntitiesRestrictRequest(" AND", "glpi_plugin_webapplications_webapplications", '', '', true);
     $query .= " ORDER BY `assocName`";
     $result = $DB->query($query);
     $number = $DB->numrows($result);
     $i = 0;
     $webs = array();
     if ($numrows = $DB->numrows($result)) {
         while ($data = $DB->fetch_assoc($result)) {
             $webs[$data['assocID']] = $data;
         }
     }
     echo "<div class='spaced'>";
     echo "<table class='tab_cadre_fixe'>";
     echo "<tr>";
     echo "<th>" . __('Name') . "</th>";
     if (Session::isMultiEntitiesMode()) {
         echo "<th>" . __('Entity') . "</th>";
     }
     echo "<th>" . PluginWebapplicationsWebapplicationType::getTypeName(1) . "</th>";
     echo "<th>" . __('URL') . "</th>";
     echo "<th>" . __('Server') . "</th>";
     echo "<th>" . __('Language') . "</th>";
     echo "<th>" . __('Version') . "</th>";
     echo "<th>" . __('Comments') . "</th>";
     echo "</tr>";
     $used = array();
     if ($number) {
         Session::initNavigateListItems('PluginWebapplicationsWebapplication', sprintf(__('%1$s = %2$s'), $item->getTypeName(1), $item->getName()));
         $web = new PluginWebapplicationsWebapplication();
         foreach ($webs as $data) {
             $webID = $data["id"];
             $link = NOT_AVAILABLE;
             if ($web->getFromDB($webID)) {
                 $link = $web->getLink();
             }
             Session::addToNavigateListItems('PluginWebapplicationsWebapplication', $webID);
             $assocID = $data["assocID"];
             echo "<tr class='tab_bg_1" . ($data["is_deleted"] ? "_2" : "") . "'>";
             echo "<td class='center'>{$link}</td>";
             if (Session::isMultiEntitiesMode()) {
                 echo "<td class='center'>" . Dropdown::getDropdownName("glpi_entities", $data['entities_id']) . "</td>";
             }
             echo "<td>" . Dropdown::getDropdownName("glpi_plugin_webapplications_webapplicationtypes", $data["plugin_webapplications_webapplicationtypes_id"]) . "</td>";
             $link = Toolbox::substr($data["address"], 0, 30) . "...";
             echo "<td class='center'>" . "<a href=\"" . str_replace("&", "&amp;", $data["address"]) . "\" target=\"_blank\">" . "<u>" . $link . "</u></a></td>";
             echo "<td>" . Dropdown::getDropdownName("glpi_plugin_webapplications_webapplicationservertypes", $data["plugin_webapplications_webapplicationservertypes_id"]) . "</td>";
             echo "<td>" . Dropdown::getDropdownName("glpi_plugin_webapplications_webapplicationtechnics", $data["plugin_webapplications_webapplicationtechnics_id"]) . "</td>";
             echo "<td>" . $data["version"] . "</td>";
             echo "<td>" . $data["comment"] . "</td>";
             echo "</tr>";
             $i++;
         }
     }
     echo "</table>";
     echo "</div>";
 }
Example #23
0
 /**
  * Add a log message for a running task
  *
  * @param $content
  **/
 function log($content)
 {
     if (!isset($this->fields['id'])) {
         return false;
     }
     $log = new CronTaskLog();
     $content = Toolbox::substr($content, 0, 200);
     return $log->add(array('crontasks_id' => $this->fields['id'], 'date' => $_SESSION['glpi_currenttime'], 'content' => addslashes($content), 'crontasklogs_id' => $this->startlog, 'state' => CronTaskLog::STATE_RUN, 'volume' => $this->volume, 'elapsed' => microtime(true) - $this->timer));
 }
Example #24
0
 /**
  * Permet l'affichage dynamique d'une liste d�roulante imbriquee
  *
  * @static
  * @param array ($itemtype,$options)
  */
 public static function dropdownReferencesByEnterprise($itemtype, $options = array())
 {
     global $DB, $CFG_GLPI;
     $item = getItemForItemtype($itemtype);
     if ($itemtype && !($item = getItemForItemtype($itemtype))) {
         return false;
     }
     $table = $item->getTable();
     $params['comments'] = true;
     $params['condition'] = '';
     $params['entity'] = -1;
     $params['name'] = "reference";
     $params['value'] = 0;
     $params['entity_sons'] = false;
     $params['rand'] = mt_rand();
     $params['used'] = array();
     $params['table'] = $table;
     $params['emptylabel'] = Dropdown::EMPTY_VALUE;
     //specific
     $params['action'] = "";
     $params['itemtype'] = "";
     $params['span'] = "";
     $params['orders_id'] = 0;
     $params['suppliers_id'] = 0;
     if (is_array($options) && count($options)) {
         foreach ($options as $key => $val) {
             $params[$key] = $val;
         }
     }
     $name = $params['emptylabel'];
     $comment = "";
     $limit_length = $_SESSION["glpidropdown_chars_limit"];
     if (strlen($params['value']) == 0 || !is_numeric($params['value'])) {
         $params['value'] = 0;
     }
     if ($params['value'] > 0) {
         $tmpname = Dropdown::getDropdownName($table, $params['value'], 1);
         if ($tmpname["name"] != "&nbsp;") {
             $name = $tmpname["name"];
             $comment = $tmpname["comment"];
             if (Toolbox::strlen($name) > $_SESSION["glpidropdown_chars_limit"]) {
                 if ($item instanceof CommonTreeDropdown) {
                     $pos = strrpos($name, ">");
                     $limit_length = max(Toolbox::strlen($name) - $pos, $_SESSION["glpidropdown_chars_limit"]);
                     if (Toolbox::strlen($name) > $limit_length) {
                         $name = "&hellip;" . Toolbox::substr($name, -$limit_length);
                     }
                 } else {
                     $limit_length = Toolbox::strlen($name);
                 }
             } else {
                 $limit_length = $_SESSION["glpidropdown_chars_limit"];
             }
         }
     }
     // Manage entity_sons
     if (!($params['entity'] < 0) && $params['entity_sons']) {
         if (is_array($params['entity'])) {
             echo "entity_sons options is not available with array of entity";
         } else {
             $params['entity'] = getSonsOf('glpi_entities', $params['entity']);
         }
     }
     $use_ajax = false;
     if ($CFG_GLPI["use_ajax_autocompletion"]) {
         $nb = 0;
         $query = "SELECT COUNT(*) AS cpt\n                   FROM `{$table}` as t\n                   LEFT JOIN `glpi_plugin_order_references_suppliers` as s\n                      ON (`t`.`id` = `s`.`plugin_order_references_id`)\n                   WHERE `s`.`suppliers_id` = '{$params['suppliers_id']}'\n                   AND `t`.`itemtype` = '{$params['itemtype']}'";
         if ($item->isEntityAssign()) {
             if (!($params['entity'] < 0)) {
                 $query .= getEntitiesRestrictRequest("AND", 't', '', $params['entity'], true);
             } else {
                 $query .= getEntitiesRestrictRequest("AND", 't', '', '', true);
             }
         }
         $result = $DB->query($query);
         if ($DB->numrows($result) == 1) {
             $nb = $DB->result($result, 0, "cpt");
         }
         $nb -= count($params['used']);
         if ($nb > $CFG_GLPI["ajax_limit_count"]) {
             $use_ajax = true;
         }
     }
     $param = array('searchText' => '__VALUE__', 'value' => $params['value'], 'itemtype' => $params['itemtype'], 'myname' => $params['name'], 'limit' => $limit_length, 'comment' => $params['comments'], 'rand' => $params['rand'], 'entity_restrict' => $params['entity'], 'used' => $params['used'], 'condition' => $params['condition'], 'table' => $params['table'], 'action' => $params['action'], 'span' => $params['span'], 'orders_id' => $params['orders_id'], 'suppliers_id' => $params['suppliers_id']);
     $default = "<select name='" . $params['name'] . "' id='dropdown_" . $params['name'] . $params['rand'] . "'>";
     $default .= "<option value='" . $params['value'] . "'>{$name}</option></select>";
     Ajax::Dropdown($use_ajax, "/plugins/order/ajax/dropdownValue.php", $param, $default, $params['rand']);
     // Display comment
     if ($params['comments']) {
         $options_tooltip = array('contentid' => "comment_" . $param['myname'] . $params['rand']);
         if ($params['value'] && $item->getFromDB($params['value'])) {
             $options_tooltip['link'] = $item->getLinkURL();
             $options_tooltip['linktarget'] = '_blank';
         }
         Html::showToolTip($comment, $options_tooltip);
         if ($itemtype::canCreate() && !isset($_GET['popup'])) {
             echo "<img alt='' title=\"" . __("Add") . "\" src='" . $CFG_GLPI["root_doc"] . "\n               /pics/add_dropdown.png' style='cursor:pointer; margin-left:2px;'\n               onClick=\"var w = window . open('" . $item->getFormURL() . "?popup=1&amp;rand=" . $params['rand'] . "&amp;itemtype=" . $params['itemtype'] . "&amp;entities_id=" . $params['entity'] . "', " . "'glpipopup', 'height=400,width=1000, top=100, left=100,\n               scrollbars=yes' );w.focus();\">";
         }
     }
     return $params['rand'];
 }
 function prepareInputForAdd($input)
 {
     global $CFG_GLPI;
     // Set default status to avoid notice
     if (!isset($input["status"])) {
         $input["status"] = self::INCOMING;
     }
     if (!isset($input["urgency"]) || !($CFG_GLPI['urgency_mask'] & 1 << $input["urgency"])) {
         $input["urgency"] = 3;
     }
     if (!isset($input["impact"]) || !($CFG_GLPI['impact_mask'] & 1 << $input["impact"])) {
         $input["impact"] = 3;
     }
     if (!isset($input["priority"])) {
         $input["priority"] = $this->computePriority($input["urgency"], $input["impact"]);
     }
     // set last updater if interactive user
     if (!Session::isCron() && ($last_updater = Session::getLoginUserID(true))) {
         $input['users_id_lastupdater'] = $last_updater;
     }
     // No Auto set Import for external source
     if (!isset($input['_auto_import'])) {
         if (!isset($input["_users_id_requester"])) {
             if ($uid = Session::getLoginUserID()) {
                 $input["_users_id_requester"] = $uid;
             }
         }
     }
     // No Auto set Import for external source
     if (($uid = Session::getLoginUserID()) && !isset($input['_auto_import'])) {
         $input["users_id_recipient"] = $uid;
     } else {
         if (isset($input["_users_id_requester"]) && $input["_users_id_requester"]) {
             $input["users_id_recipient"] = $input["_users_id_requester"];
         }
     }
     // No name set name
     $input["name"] = ltrim($input["name"]);
     $input['content'] = ltrim($input['content']);
     if (empty($input["name"])) {
         $input['name'] = Html::clean(Html::entity_decode_deep($input['content']));
         $input["name"] = preg_replace('/\\r\\n/', ' ', $input['name']);
         $input["name"] = preg_replace('/\\n/', ' ', $input['name']);
         // For mailcollector
         $input["name"] = preg_replace('/\\\\r\\\\n/', ' ', $input['name']);
         $input["name"] = preg_replace('/\\\\n/', ' ', $input['name']);
         $input['name'] = Toolbox::stripslashes_deep($input['name']);
         $input["name"] = Toolbox::substr($input['name'], 0, 70);
         $input['name'] = Toolbox::addslashes_deep($input['name']);
     }
     // Set default dropdown
     $dropdown_fields = array('entities_id', 'itilcategories_id');
     foreach ($dropdown_fields as $field) {
         if (!isset($input[$field])) {
             $input[$field] = 0;
         }
     }
     $input = $this->computeDefaultValuesForAdd($input);
     return $input;
 }
Example #26
0
 /**
  * Log history
  *
  * @param $items_id
  * @param $itemtype
  * @param $changes
  * @param $itemtype_link   (default '')
  * @param $linked_action   (default '0')
  *
  * @return boolean success
  **/
 static function history($items_id, $itemtype, $changes, $itemtype_link = '', $linked_action = '0')
 {
     global $DB;
     $date_mod = $_SESSION["glpi_currenttime"];
     if (empty($changes)) {
         return false;
     }
     // create a query to insert history
     $id_search_option = $changes[0];
     $old_value = $changes[1];
     $new_value = $changes[2];
     if ($uid = Session::getLoginUserID(false)) {
         if (is_numeric($uid)) {
             $username = sprintf(__('%1$s (%2$s)'), getUserName($uid), $uid);
         } else {
             // For cron management
             $username = $uid;
         }
     } else {
         $username = "";
     }
     $old_value = $DB->escape(Toolbox::substr(stripslashes($old_value), 0, 180));
     $new_value = $DB->escape(Toolbox::substr(stripslashes($new_value), 0, 180));
     // Security to be sure that values do not pass over the max length
     if (Toolbox::strlen($old_value) > 255) {
         $old_value = Toolbox::substr($old_value, 0, 250);
     }
     if (Toolbox::strlen($new_value) > 255) {
         $new_value = Toolbox::substr($new_value, 0, 250);
     }
     // Build query
     $query = "INSERT INTO `glpi_logs`\n                       (`items_id`, `itemtype`, `itemtype_link`, `linked_action`, `user_name`,\n                        `date_mod`, `id_search_option`, `old_value`, `new_value`)\n                VALUES ('{$items_id}', '{$itemtype}', '{$itemtype_link}', '{$linked_action}',\n                        '" . addslashes($username) . "', '{$date_mod}', '{$id_search_option}',\n                        '{$old_value}', '{$new_value}')";
     if ($DB->query($query)) {
         return $_SESSION['glpi_maxhistory'] = $DB->insert_id();
     }
     return false;
 }
Example #27
0
 function dropdownVlan($used = array())
 {
     global $DB;
     $limit = $_SESSION["glpidropdown_chars_limit"];
     $where = "";
     if (count($used)) {
         $where = "WHERE `id` NOT IN (0";
         foreach ($used as $ID) {
             $where .= ",{$ID}";
         }
         $where .= ")";
     }
     $query = "SELECT *\n                FROM `glpi_vlans`\n                {$where}\n                ORDER BY `name`";
     $result = $DB->query($query);
     $number = $DB->numrows($result);
     if ($number != "0") {
         echo "<select name='vlans_id'>\n";
         echo "<option value='0'>" . Dropdown::EMPTY_VALUE . "</option>\n";
         echo "<option value='-1'>" . __('All VLANs', 'archires') . "</option>\n";
         while ($data = $DB->fetch_array($result)) {
             $output = $data["name"];
             if (Toolbox::strlen($output) > $limit) {
                 $output = Toolbox::substr($output, 0, $limit) . "&hellip;";
             }
             echo "<option value='" . $data["id"] . "'>" . $output . "</option>";
         }
         echo "</select>";
     }
 }
 /**
  * Get download link for a document
  *
  * @param $params    additonal parameters to be added to the link (default '')
  * @param $len       maximum length of displayed string (default 20)
  *
  **/
 function getDownloadLink($params = '', $len = 20)
 {
     global $DB, $CFG_GLPI;
     $splitter = explode("/", $this->fields['filename']);
     if (count($splitter) == 2) {
         // Old documents in EXT/filename
         $fileout = $splitter[1];
     } else {
         // New document
         $fileout = $this->fields['filename'];
     }
     $initfileout = $fileout;
     if (Toolbox::strlen($fileout) > $len) {
         $fileout = Toolbox::substr($fileout, 0, $len) . "&hellip;";
     }
     $out = '';
     $open = '';
     $close = '';
     if (self::canView() || self::canViewFile(array('tickets_id' => $this->fields['tickets_id']))) {
         $open = "<a href='" . $CFG_GLPI["root_doc"] . "/front/document.send.php?docid=" . $this->fields['id'] . $params . "' alt=\"" . $initfileout . "\"\n                    title=\"" . $initfileout . "\"target='_blank'>";
         $close = "</a>";
     }
     $splitter = explode("/", $this->fields['filepath']);
     if (count($splitter)) {
         $query = "SELECT *\n                   FROM `glpi_documenttypes`\n                   WHERE `ext` LIKE '" . $splitter[0] . "'\n                         AND `icon` <> ''";
         if ($result = $DB->query($query)) {
             if ($DB->numrows($result) > 0) {
                 $icon = $DB->result($result, 0, 'icon');
                 $out .= "&nbsp;<img class='middle' style='margin-left:3px; margin-right:6px;' alt=\"" . $initfileout . "\" title=\"" . $initfileout . "\" src='" . $CFG_GLPI["typedoc_icon_dir"] . "/{$icon}'>";
             }
         }
     }
     $out .= "{$open}<span class='b'>{$fileout}</span>{$close}";
     return $out;
 }
 function showGenericSearch($itemtype, $params)
 {
     global $CFG_GLPI;
     // Default values of parameters
     $p = array();
     $p['link'] = array();
     //
     $p['field'] = array();
     $p['contains'] = array();
     $p['searchtype'] = array();
     $p['sort'] = '';
     $p['is_deleted'] = 0;
     $p['link2'] = '';
     //
     $p['contains2'] = '';
     $p['field2'] = '';
     $p['itemtype2'] = '';
     $p['searchtype2'] = '';
     foreach ($params as $key => $val) {
         $p[$key] = $val;
     }
     $options = Search::getCleanedOptions($itemtype);
     //      $target  = Toolbox::getItemTypeSearchURL($itemtype);
     // Instanciate an object to access method
     $item = NULL;
     if ($itemtype != 'States' && class_exists($itemtype)) {
         $item = new $itemtype();
     }
     $linked = Search::getMetaItemtypeAvailable($itemtype);
     if (!isset($_GET['id']) || strstr($_SERVER['REQUEST_URI'], 'displayview_rule.form.php')) {
         $item->getEmpty();
     } else {
         $item->getFromDB($_GET['id']);
     }
     if (strstr($_SERVER['REQUEST_URI'], 'displayview_rule.form.php')) {
         echo "<form name='searchform{$itemtype}' method='get' action=\"" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/displayview_rule.form.php\">";
     } else {
         echo "<form name='searchform{$itemtype}' method='get' action=\"" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/componentscatalog_rule.form.php\">";
     }
     $item->showFormHeader();
     //      echo "<form name='searchform$itemtype' method='get' action=\"".
     //              $CFG_GLPI['root_doc']."/plugins/monitoring/front/componentscatalog_rule.form.php\">";
     //      echo "<table class='tab_cadre_fixe'>";
     echo "<tr class='tab_bg_1'>";
     echo "<td>";
     echo __('Name') . "&nbsp;:";
     echo "</td>";
     echo "<td>";
     echo "<input type='text' name='name' value='" . $_GET['name'] . "'/>";
     echo "</td>";
     echo "<td>";
     echo __('Status') . "&nbsp;:";
     echo "</td>";
     echo "<td>";
     echo $_GET['itemtype'];
     echo "</td>";
     echo "</tr>";
     if (isset($_GET['itemtype'])) {
         echo "<tr class='tab_bg_1'>";
         echo "<td colspan='3'>";
         echo "<table>";
         // Display normal search parameters
         for ($i = 0; $i < $_SESSION["glpisearchcount"][$itemtype]; $i++) {
             echo "<tr><td class='left' width='50%'>";
             // First line display add / delete images for normal and meta search items
             if ($i == 0) {
                 echo "<input type='hidden' disabled id='add_search_count' name='add_search_count'\n                   value='1'>";
                 echo "<a href='#' onClick = \"document.getElementById('add_search_count').disabled=false;\n                   document.forms['searchform{$itemtype}'].submit();\">";
                 echo "<img src=\"" . $CFG_GLPI["root_doc"] . "/pics/plus.png\" alt='+' title=\"" . __s('Add a search criterion') . "\"></a>&nbsp;&nbsp;&nbsp;&nbsp;";
                 if ($_SESSION["glpisearchcount"][$itemtype] > 1) {
                     echo "<input type='hidden' disabled id='delete_search_count'\n                      name='delete_search_count' value='1'>";
                     echo "<a href='#' onClick = \"document.getElementById('delete_search_count').disabled=false;\n                      document.forms['searchform{$itemtype}'].submit();\">";
                     echo "<img src=\"" . $CFG_GLPI["root_doc"] . "/pics/moins.png\" alt='-' title=\"" . __s('Delete a search criterion') . "\"></a>&nbsp;&nbsp;&nbsp;&nbsp;";
                 }
                 if (is_array($linked) && count($linked) > 0) {
                     echo "<input type='hidden' disabled id='add_search_count2' name='add_search_count2'\n                      value='1'>";
                     echo "<a href='#' onClick=\"document.getElementById('add_search_count2').disabled=false;\n                      document.forms['searchform{$itemtype}'].submit();\">";
                     echo "<img src=\"" . $CFG_GLPI["root_doc"] . "/pics/meta_plus.png\" alt='+' title=\"" . __s('Add a global search criterion') . "\"></a>&nbsp;&nbsp;&nbsp;&nbsp;";
                     if ($_SESSION["glpisearchcount2"][$itemtype] > 0) {
                         echo "<input type='hidden' disabled id='delete_search_count2'\n                         name='delete_search_count2' value='1'>";
                         echo "<a href='#' onClick=\"document.getElementById('delete_search_count2').disabled=false;\n                         document.forms['searchform{$itemtype}'].submit();\">";
                         echo "<img src=\"" . $CFG_GLPI["root_doc"] . "/pics/meta_moins.png\" alt='-' title=\"" . __s('Delete a global search criterion') . "\"></a>&nbsp;&nbsp;&nbsp;&nbsp;";
                     }
                 }
                 //            $itemtable = getTableForItemType($itemtype);
                 //            if ($item && $item->maybeDeleted()) {
                 //               echo "<input type='hidden' id='is_deleted' name='is_deleted' value='".
                 //                      $p['is_deleted']."'>";
                 //               echo "<a href='#' onClick = \"toogle('is_deleted','','','');
                 //                      document.forms['searchform$itemtype'].submit();\">
                 //                      <img src=\"".$CFG_GLPI["root_doc"]."/pics/showdeleted".
                 //                       (!$p['is_deleted']?'_no':'').".png\" name='img_deleted'  alt=\"".
                 //                       (!$p['is_deleted']?$LANG['common'][3]:$LANG['common'][81])."\" title=\"".
                 //                       (!$p['is_deleted']?$LANG['common'][3]:$LANG['common'][81])."\" ></a>";
                 //               // Dropdown::showYesNo("is_deleted",$p['is_deleted']);
                 //               echo '&nbsp;&nbsp;';
                 //            }
             }
             // Display link item
             if ($i > 0) {
                 echo "<select name='link[{$i}]'>";
                 echo "<option value = 'AND' ";
                 if (is_array($p["link"]) && isset($p["link"][$i]) && $p["link"][$i] == "AND") {
                     echo "selected";
                 }
                 echo ">AND</option>\n";
                 echo "<option value='OR' ";
                 if (is_array($p["link"]) && isset($p["link"][$i]) && $p["link"][$i] == "OR") {
                     echo "selected";
                 }
                 echo ">OR</option>\n";
                 echo "<option value='AND NOT' ";
                 if (is_array($p["link"]) && isset($p["link"][$i]) && $p["link"][$i] == "AND NOT") {
                     echo "selected";
                 }
                 echo ">AND NOT</option>\n";
                 echo "<option value='OR NOT' ";
                 if (is_array($p["link"]) && isset($p["link"][$i]) && $p["link"][$i] == "OR NOT") {
                     echo "selected";
                 }
                 echo ">OR NOT</option>";
                 echo "</select>&nbsp;";
             }
             // display select box to define search item
             echo "<select id='Search{$itemtype}{$i}' name=\"field[{$i}]\" size='1'>";
             echo "<option value='view' ";
             if (is_array($p['field']) && isset($p['field'][$i]) && $p['field'][$i] == "view") {
                 echo "selected";
             }
             echo ">" . __('Items seen') . "</option>\n";
             reset($options);
             $first_group = true;
             $selected = 'view';
             $str_limit = 28;
             $nb_in_group = 0;
             $group = '';
             foreach ($options as $key => $val) {
                 // print groups
                 if (!is_array($val)) {
                     if (!$first_group) {
                         $group .= "</optgroup>\n";
                     } else {
                         $first_group = false;
                     }
                     if ($nb_in_group) {
                         echo $group;
                     }
                     $group = '';
                     $nb_in_group = 0;
                     $group .= "<optgroup label=\"" . Toolbox::substr($val, 0, $str_limit) . "\">";
                 } else {
                     if (!isset($val['nosearch']) || $val['nosearch'] == false) {
                         $nb_in_group++;
                         $group .= "<option title=\"" . Html::cleanInputText($val["name"]) . "\" value='{$key}'";
                         if (is_array($p['field']) && isset($p['field'][$i]) && $key == $p['field'][$i]) {
                             $group .= "selected";
                             $selected = $key;
                         }
                         $group .= ">" . Toolbox::substr($val["name"], 0, $str_limit) . "</option>\n";
                     }
                 }
             }
             if (!$first_group) {
                 $group .= "</optgroup>\n";
             }
             if ($nb_in_group) {
                 echo $group;
             }
             echo "<option value='all' ";
             if (is_array($p['field']) && isset($p['field'][$i]) && $p['field'][$i] == "all") {
                 echo "selected";
             }
             echo ">" . __('All') . "</option>";
             echo "</select>\n";
             echo "</td><td class='left'>";
             echo "<div id='SearchSpan{$itemtype}{$i}'>\n";
             $_POST['itemtype'] = $itemtype;
             $_POST['num'] = $i;
             $_POST['field'] = $selected;
             $_POST['searchtype'] = is_array($p['searchtype']) && isset($p['searchtype'][$i]) ? $p['searchtype'][$i] : "";
             $_POST['value'] = is_array($p['contains']) && isset($p['contains'][$i]) ? stripslashes($p['contains'][$i]) : "";
             include GLPI_ROOT . "/ajax/searchoption.php";
             echo "</div>\n";
             $params = array('field' => '__VALUE__', 'itemtype' => $itemtype, 'num' => $i, 'value' => $_POST["value"], 'searchtype' => $_POST["searchtype"]);
             Ajax::updateItemOnSelectEvent("Search{$itemtype}{$i}", "SearchSpan{$itemtype}{$i}", $CFG_GLPI["root_doc"] . "/ajax/searchoption.php", $params, false);
             echo "</td></tr>\n";
         }
         $metanames = array();
         if (is_array($linked) && count($linked) > 0) {
             for ($i = 0; $i < $_SESSION["glpisearchcount2"][$itemtype]; $i++) {
                 echo "<tr><td class='left' colspan='2'>";
                 $rand = mt_rand();
                 echo "<table width='100%'><tr class='left'><td width='35%'>";
                 // Display link item (not for the first item)
                 echo "<select name='link2[{$i}]'>";
                 echo "<option value='AND' ";
                 if (is_array($p['link2']) && isset($p['link2'][$i]) && $p['link2'][$i] == "AND") {
                     echo "selected";
                 }
                 echo ">AND</option>\n";
                 echo "<option value='OR' ";
                 if (is_array($p['link2']) && isset($p['link2'][$i]) && $p['link2'][$i] == "OR") {
                     echo "selected";
                 }
                 echo ">OR</option>\n";
                 echo "<option value='AND NOT' ";
                 if (is_array($p['link2']) && isset($p['link2'][$i]) && $p['link2'][$i] == "AND NOT") {
                     echo "selected";
                 }
                 echo ">AND NOT</option>\n";
                 echo "<option value='OR NOT' ";
                 if (is_array($p['link2']) && isset($p['link2'][$i]) && $p['link2'][$i] == "OR NOT") {
                     echo "selected";
                 }
                 echo ">OR NOT</option>\n";
                 echo "</select>&nbsp;";
                 // Display select of the linked item type available
                 echo "<select name='itemtype2[{$i}]' id='itemtype2_" . $itemtype . "_" . $i . "_{$rand}'>";
                 echo "<option value=''>" . Dropdown::EMPTY_VALUE . "</option>";
                 foreach ($linked as $key) {
                     if (!isset($metanames[$key])) {
                         $linkitem = new $key();
                         $metanames[$key] = $linkitem->getTypeName();
                     }
                     echo "<option value='{$key}'>" . Toolbox::substr($metanames[$key], 0, 20) . "</option>\n";
                 }
                 echo "</select>&nbsp;";
                 echo "</td><td>";
                 // Ajax script for display search met& item
                 echo "<span id='show_" . $itemtype . "_" . $i . "_{$rand}'>&nbsp;</span>\n";
                 $params = array('itemtype' => '__VALUE__', 'num' => $i, 'field' => is_array($p['field2']) && isset($p['field2'][$i]) ? $p['field2'][$i] : "", 'value' => is_array($p['contains2']) && isset($p['contains2'][$i]) ? $p['contains2'][$i] : "", 'searchtype2' => is_array($p['searchtype2']) && isset($p['searchtype2'][$i]) ? $p['searchtype2'][$i] : "");
                 Ajax::updateItemOnSelectEvent("itemtype2_" . $itemtype . "_" . $i . "_{$rand}", "show_" . $itemtype . "_" . $i . "_{$rand}", $CFG_GLPI["root_doc"] . "/ajax/updateMetaSearch.php", $params, false);
                 if (is_array($p['itemtype2']) && isset($p['itemtype2'][$i]) && !empty($p['itemtype2'][$i])) {
                     $params['itemtype'] = $p['itemtype2'][$i];
                     Ajax::updateItem("show_" . $itemtype . "_" . $i . "_{$rand}", $CFG_GLPI["root_doc"] . "/ajax/updateMetaSearch.php", $params, false);
                     echo "<script type='text/javascript' >";
                     echo "window.document.getElementById('itemtype2_" . $itemtype . "_" . $i . "_{$rand}').value='" . $p['itemtype2'][$i] . "';";
                     echo "</script>\n";
                 }
                 echo "</td></tr></table>";
                 echo "</td></tr>\n";
             }
         }
         echo "</table>\n";
         echo "</td>\n";
         echo "<td width='150px'>";
         echo "<table width='100%'>";
         // Display sort selection
         /*      echo "<tr><td colspan='2'>".$LANG['search'][4];
               echo "&nbsp;<select name='sort' size='1'>";
               reset($options);
               $first_group=true;
               foreach ($options as $key => $val) {
                  if (!is_array($val)) {
                     if (!$first_group) {
                        echo "</optgroup>\n";
                     } else {
                        $first_group=false;
                     }
                     echo "<optgroup label=\"$val\">";
                  } else {
                     echo "<option value='$key'";
                     if ($key == $p['sort']) {
                        echo " selected";
                     }
                     echo ">".Toolbox::substr($val["name"],0,20)."</option>\n";
                  }
               }
               if (!$first_group) {
                  echo "</optgroup>\n";
               }
               echo "</select> ";
               echo "</td></tr>\n";
         */
         // Display deleted selection
         echo "<tr>";
         // Display submit button
         echo "<td width='80' class='center'>";
         echo "<input type='submit' value=\"" . _sx('button', 'Search') . "\" class='submit' >";
         echo "</td><td>";
         //      Bookmark::showSaveButton(Bookmark::SEARCH,$itemtype);
         if (strstr($_SERVER['REQUEST_URI'], 'displayview_rule.form.php')) {
             echo "<a href='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/displayview_rule.form.php?" . "reset=reset" . "&name=" . $_GET['name'] . "&plugin_monitoring_displayviews_id=" . $_GET['plugin_monitoring_displayviews_id'] . "&itemtype=" . $_GET['itemtype'] . "' >";
         } else {
             echo "<a href='" . $CFG_GLPI['root_doc'] . "/plugins/monitoring/front/componentscatalog_rule.form.php?" . "reset=reset" . "&name=" . $_GET['name'] . "&plugin_monitoring_componentscalalog_id=" . $_GET['plugin_monitoring_componentscalalog_id'] . "&itemtype=" . $_GET['itemtype'] . "' >";
         }
         echo "&nbsp;&nbsp;<img title=\"" . __s('Blank') . "\" alt=\"" . __s('Blank') . "\" src='" . $CFG_GLPI["root_doc"] . "/pics/reset.png' class='calendrier'></a>";
         echo "</td></tr>";
         echo "</table>\n";
         echo "</td></tr>";
         echo "<tr>";
     }
     if (isset($_GET['id'])) {
         echo "<td colspan='2' class='center'>";
         if (strstr($_SERVER['REQUEST_URI'], 'displayview_rule.form.php')) {
             echo "<input type='hidden' name='plugin_monitoring_displayviews_id' value='" . $_GET['plugin_monitoring_displayviews_id'] . "' >";
         } else {
             echo "<input type='hidden' name='plugin_monitoring_componentscalalog_id' value='" . $_GET['plugin_monitoring_componentscalalog_id'] . "' >";
         }
         echo "<input type='hidden' name='id' value='" . $_GET['id'] . "' >";
         echo "<input type='submit' name='updaterule' value=\"Update this rule\" class='submit' >";
         echo "</td>";
         echo "<td colspan='2' class='center'>";
         echo "<input type='submit' name='deleterule' value=\"Delete this rule\" class='submit' >";
     } else {
         echo "<td colspan='4' class='center'>";
         echo "<input type='hidden' name='plugin_monitoring_componentscalalog_id' value='" . $_GET['plugin_monitoring_componentscalalog_id'] . "' >";
         echo "<input type='submit' name='addrule' value=\"Add this rule\" class='submit' >";
     }
     echo "</td>";
     echo "</tr>";
     echo "</table>\n";
     // For dropdown
     echo "<input type='hidden' name='itemtype' value='{$itemtype}'>";
     // Reset to start when submit new search
     echo "<input type='hidden' name='start' value='0'>";
     Html::closeForm();
 }
    echo "<br>";
    echo "<select name='" . $_POST['myname'] . "' size='1'>";
    echo "<option value='0'>" . Dropdown::EMPTY_VALUE . "</option>";
    if ($DB->numrows($result)) {
        while ($data = $DB->fetch_assoc($result)) {
            // Device name + port name
            $output = $output_long = $data['cname'];
            if (!empty($data['nname'])) {
                $output = sprintf(__('%1$s - %2$s'), $output, $data['nname']);
                //TRANS: %1$s is device name, %2$s is port name
                $output_long = sprintf(__('%1$s - The port %2$s'), $output_long, $data['nname']);
            }
            // display netpoint (which will be copied)
            if (!empty($data['npname'])) {
                $output = sprintf(__('%1$s - %2$s'), $output, $data['npname']);
                //TRANS: %1$s is a string (device name - port name...), %2$s is network outlet name
                $output_long = sprintf(__('%1$s - Network outlet %2$s'), $output_long, $data['npname']);
            }
            $ID = $data['did'];
            if ($_SESSION["glpiis_ids_visible"] || empty($output) || empty($output_long)) {
                $output = sprintf(__('%1$s (%2$s)'), $output, $ID);
                $output_long = sprintf(__('%1$s (%2$s)'), $output_long, $ID);
            }
            $output = Toolbox::substr($output, 0, $_SESSION["glpidropdown_chars_limit"]);
            echo "<option value='{$ID}' title=\"" . Html::cleanInputText($output_long) . "\">" . $output;
            echo "</option>";
        }
    }
    echo "</select>";
    //    echo "<input type='submit' name='connect' value=\"".__s('Connect')."\" class='submit'>";
}