entities_deep() static public method

Recursivly execute htmlentities on an Array
static public entities_deep ( $value ) : array
$value string or array
return array of value (same struct as input)
Example #1
0
 /**
  * Display a Warning
  *
  * @param $msg    string
  * @param $red    boolean (false by default)
  **/
 function displayWarning($msg, $red = false)
 {
     echo ($red ? "<div class='red'><p>" : "<p><span class='b'>") . Html::entities_deep($msg) . ($red ? "</p></div>" : "</span></p>");
     $this->log($msg, true);
 }
Example #2
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 (isset($data[$num][$k]['name']) && 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":
             case "glpi_tickets.time_to_own":
                 // Due date + progress
                 if ($ID == 151 || $ID == 158) {
                     $out = Html::convDateTime($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;
                     $sltField = 'slts_id';
                     switch ($table . '.' . $field) {
                         // If ticket has been taken into account : no progression display
                         case "glpi_tickets.time_to_own":
                             if ($item->fields['takeintoaccount_delay_stat'] > 0) {
                                 return $out;
                             }
                             break;
                     }
                     if ($item->isField($sltField) && $item->fields[$sltField] != 0) {
                         // Have SLT
                         $slt = new SLT();
                         $slt->getFromDB($item->fields[$sltField]);
                         $currenttime = $slt->getActiveTimeBetween($item->fields['date'], date('Y-m-d H:i:s'));
                         $totaltime = $slt->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:" . Html::entities_deep($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 #3
0
 /**
  * Convert tag to image
  *
  * @since version 0.85
  *
  * @param $content_text         text content of input
  * @param $force_update         force update of content in item (false by default
  * @param $doc_data       array of filenames and tags
  *
  * @return nothing
  **/
 function convertTagToImage($content_text, $force_update = false, $doc_data = array())
 {
     global $CFG_GLPI;
     $matches = array();
     // If no doc data available we match all tags in content
     if (!count($doc_data)) {
         $doc = new Document();
         preg_match_all('/' . Document::getImageTag('(([a-z0-9]+|[\\.\\-]?)+)') . '/', $content_text, $matches, PREG_PATTERN_ORDER);
         if (isset($matches[1]) && count($matches[1])) {
             $doc_data = $doc->find("`tag` IN('" . implode("','", array_unique($matches[1])) . "')");
         }
     }
     if (count($doc_data)) {
         foreach ($doc_data as $id => $image) {
             // Add only image files : try to detect mime type
             $ok = false;
             $mime = '';
             if (isset($image['filepath'])) {
                 $fullpath = GLPI_DOC_DIR . "/" . $image['filepath'];
                 $mime = Toolbox::getMime($fullpath);
                 $ok = Toolbox::getMime($fullpath, 'image');
             }
             if (isset($image['tag'])) {
                 if ($ok || empty($mime)) {
                     // Replace tags by image in textarea
                     $img = "<img alt='" . $image['tag'] . "' src='" . $CFG_GLPI['root_doc'] . "/front/document.send.php?docid=" . $id . "&tickets_id=" . $this->fields['id'] . "'/>";
                     // Replace tag by the image
                     $content_text = preg_replace('/' . Document::getImageTag($image['tag']) . '/', Html::entities_deep($img), $content_text);
                     // Replace <br> TinyMce bug
                     $content_text = str_replace(array('&gt;rn&lt;', '&gt;\\r\\n&lt;', '&gt;\\r&lt;', '&gt;\\n&lt;'), '&gt;&lt;', $content_text);
                     // If the tag is from another ticket : link document to ticket
                     // TODO : comment maybe not used
                     // if($image['tickets_id'] != $this->fields['id']){
                     //    $docitem = new Document_Item();
                     //    $docitem->add(array('documents_id'  => $image['id'],
                     //                        '_do_notif'     => false,
                     //                        '_disablenotif' => true,
                     //                        'itemtype'      => $this->getType(),
                     //                        'items_id'      => $this->fields['id']));
                     // }
                 } else {
                     // Remove tag
                     $content_text = preg_replace('/' . Document::getImageTag($image['tag']) . '/', '', $content_text);
                 }
             }
         }
     }
     if ($force_update) {
         $this->fields['content'] = $content_text;
         $this->updateInDB(array('content'));
     }
     return $content_text;
 }
Example #4
0
 /**
  * Display a Planning Item
  *
  * @param $itemtype  itemtype
  * @param $val       Array of the item to display
  * @param $who             ID of the user (0 if all)
  * @param $type            position of the item in the time block (in, through, begin or end)
  *                         (default '')
  * @param $complete        complete display (more details) (default 0)
  *
  * @return Nothing (display function)
  **/
 static function genericDisplayPlanningItem($itemtype, array $val, $who, $type = "", $complete = 0)
 {
     global $CFG_GLPI;
     $rand = mt_rand();
     $styleText = "";
     if (isset($val["state"])) {
         switch ($val["state"]) {
             case 2:
                 // Done
                 $styleText = "color:#747474;";
                 break;
         }
     }
     $parenttype = str_replace('Task', '', $itemtype);
     if ($parent = getItemForItemtype($parenttype)) {
         $parenttype_fk = $parent->getForeignKeyField();
     } else {
         return;
     }
     echo "<img src='" . $CFG_GLPI["root_doc"] . "/pics/rdv_interv.png' alt='' title=\"" . Html::entities_deep($parent->getTypeName(1)) . "\">&nbsp;&nbsp;";
     echo "<img src='" . $parent->getStatusIconURL($val["status"]) . "' alt='" . Html::entities_deep($parent->getStatus($val["status"])) . "' title=\"" . Html::entities_deep($parent->getStatus($val["status"])) . "\">";
     echo "&nbsp;<a id='content_tracking_" . $val["id"] . $rand . "'\n                   href='" . Toolbox::getItemTypeFormURL($parenttype) . "?id=" . $val[$parenttype_fk] . "'\n                   style='{$styleText}'>";
     switch ($type) {
         case "in":
             //TRANS: %1$s is the start time of a planned item, %2$s is the end
             printf(__('From %1$s to %2$s :'), date("H:i", strtotime($val["begin"])), date("H:i", strtotime($val["end"])));
             break;
         case "through":
             break;
         case "begin":
             //TRANS: %s is the start time of a planned item
             printf(__('Start at %s:'), date("H:i", strtotime($val["begin"])));
             break;
         case "end":
             //TRANS: %s is the end time of a planned item
             printf(__('End at %s:'), date("H:i", strtotime($val["end"])));
             break;
     }
     echo "<br>";
     //TRANS: %1$s is name of the item, %2$d is its ID
     printf(__('%1$s (#%2$d)'), Html::resume_text($val["name"], 80), $val[$parenttype_fk]);
     if (!empty($val["device"])) {
         echo "<br>" . $val["device"];
     }
     if ($who <= 0) {
         // show tech for "show all and show group"
         echo "<br>";
         //TRANS: %s is user name
         printf(__('By %s'), getUserName($val["users_id_tech"]));
     }
     echo "</a>";
     $recall = '';
     if (isset($val[getForeignKeyFieldForItemType($itemtype)]) && PlanningRecall::isAvailable()) {
         $pr = new PlanningRecall();
         if ($pr->getFromDBForItemAndUser($val['itemtype'], $val[getForeignKeyFieldForItemType($itemtype)], Session::getLoginUserID())) {
             $recall = "<br><span class='b'>" . sprintf(__('Recall on %s'), Html::convDateTime($pr->fields['when'])) . "<span>";
         }
     }
     if ($complete) {
         echo "<br><span class='b'>";
         if (isset($val["state"])) {
             echo Planning::getState($val["state"]) . "<br>";
         }
         echo sprintf(__('%1$s: %2$s'), __('Priority'), $parent->getPriorityName($val["priority"]));
         echo "<br>" . __('Description') . "</span><br>" . $val["content"];
         echo $recall;
     } else {
         $content = "<span class='b'>";
         if (isset($val["state"])) {
             $content .= Planning::getState($val["state"]) . "<br>";
         }
         $content .= sprintf(__('%1$s: %2$s'), __('Priority'), $parent->getPriorityName($val["priority"])) . "<br>" . __('Description') . "</span><br>" . $val["content"] . $recall;
         Html::showToolTip($content, array('applyto' => "content_tracking_" . $val["id"] . $rand));
     }
 }
 /**
  * Display a Planning Item
  *
  * @param $itemtype  itemtype
  * @param $val       Array of the item to display
  * @param $who             ID of the user (0 if all)
  * @param $type            position of the item in the time block (in, through, begin or end)
  *                         (default '')
  * @param $complete        complete display (more details) (default 0)
  *
  * @return Nothing (display function)
  **/
 static function genericDisplayPlanningItem($itemtype, array $val, $who, $type = "", $complete = 0)
 {
     global $CFG_GLPI;
     $html = "";
     $rand = mt_rand();
     $styleText = "";
     if (isset($val["state"])) {
         switch ($val["state"]) {
             case 2:
                 // Done
                 $styleText = "color:#747474;";
                 break;
         }
     }
     $parenttype = str_replace('Task', '', $itemtype);
     if ($parent = getItemForItemtype($parenttype)) {
         $parenttype_fk = $parent->getForeignKeyField();
     } else {
         return;
     }
     $html .= "<img src='" . $CFG_GLPI["root_doc"] . "/pics/rdv_interv.png' alt='' title=\"" . Html::entities_deep($parent->getTypeName(1)) . "\">&nbsp;&nbsp;";
     $html .= "<img src='" . $parent->getStatusIconURL($val["status"]) . "' alt='" . Html::entities_deep($parent->getStatus($val["status"])) . "' title=\"" . Html::entities_deep($parent->getStatus($val["status"])) . "\">";
     $html .= "&nbsp;<a id='content_tracking_" . $val["id"] . $rand . "'\n                   href='" . Toolbox::getItemTypeFormURL($parenttype) . "?id=" . $val[$parenttype_fk] . "'\n                   style='{$styleText}'>";
     if (!empty($val["device"])) {
         $html .= "<br>" . $val["device"];
     }
     if ($who <= 0) {
         // show tech for "show all and show group"
         $html .= "<br>";
         //TRANS: %s is user name
         $html .= sprintf(__('By %s'), getUserName($val["users_id_tech"]));
     }
     $html .= "</a>";
     $recall = '';
     if (isset($val[getForeignKeyFieldForItemType($itemtype)]) && PlanningRecall::isAvailable()) {
         $pr = new PlanningRecall();
         if ($pr->getFromDBForItemAndUser($val['itemtype'], $val[getForeignKeyFieldForItemType($itemtype)], Session::getLoginUserID())) {
             $recall = "<span class='b'>" . sprintf(__('Recall on %s'), Html::convDateTime($pr->fields['when'])) . "<span>";
         }
     }
     if (isset($val["state"])) {
         $html .= "<span>";
         $html .= Planning::getState($val["state"]);
         $html .= "</span>";
     }
     $html .= "<div>";
     $html .= sprintf(__('%1$s: %2$s'), __('Priority'), $parent->getPriorityName($val["priority"]));
     $html .= "</div>";
     $html .= "<div class='event-description'>" . html_entity_decode($val["content"]) . "</div>";
     $html .= $recall;
     return $html;
 }
Example #6
0
 /**
  * Dropdown of values in an array
  *
  * @param $name            select name
  * @param $elements  array of elements to display
  * @param $options   array of possible options:
  *    - value               : integer / preselected value (default 0)
  *    - used                : array / Already used items ID: not to display in dropdown (default empty)
  *    - readonly            : boolean / used as a readonly item (default false)
  *    - on_change           : string / value to transmit to "onChange"
  *    - multiple            : boolean / can select several values (default false)
  *    - size                : integer / number of rows for the select (default = 1)
  *    - display             : boolean / display or return string
  *    - other               : boolean or string if not false, then we can use an "other" value
  *                            if it is a string, then the default value will be this string
  *    - rand                : specific rand if needed (default is generated one)
  *    - width               : specific width needed (default not set)
  *    - emptylabel          : empty label if empty displayed (default self::EMPTY_VALUE)
  *    - display_emptychoice : display empty choice (default false)
  *    - tooltip             : string / message to add as tooltip on the dropdown (default '')
  *    - option_tooltips     : array / message to add as tooltip on the dropdown options. Use the same keys as for the $elements parameter, but none is mandotary. Missing keys will just be ignored and no tooltip will be added. To add a tooltip on an option group, is the '__optgroup_label' key inside the array describing option tooltips : 'optgroupname1' => array('__optgroup_label' => 'tooltip for option group') (default empty)
  *
  * Permit to use optgroup defining items in arrays
  * array('optgroupname'  => array('key1' => 'val1',
  *                                'key2' => 'val2'),
  *       'optgroupname2' => array('key3' => 'val3',
  *                                'key4' => 'val4'))
  **/
 static function showFromArray($name, array $elements, $options = array())
 {
     $param['value'] = '';
     $param['values'] = array('');
     $param['tooltip'] = '';
     $param['option_tooltips'] = array();
     $param['used'] = array();
     $param['readonly'] = false;
     $param['on_change'] = '';
     $param['width'] = '';
     $param['multiple'] = false;
     $param['size'] = 1;
     $param['display'] = true;
     $param['other'] = false;
     $param['rand'] = mt_rand();
     $param['emptylabel'] = self::EMPTY_VALUE;
     $param['display_emptychoice'] = false;
     if (is_array($options) && count($options)) {
         if (isset($options['value']) && strlen($options['value'])) {
             $options['values'] = array($options['value']);
             unset($options['value']);
         }
         foreach ($options as $key => $val) {
             $param[$key] = $val;
         }
     }
     if ($param['other'] !== false) {
         $other_select_option = $name . '_other_value';
         $param['on_change'] .= "displayOtherSelectOptions(this, \"{$other_select_option}\");";
         // If $param['other'] is a string, then we must highlight "other" option
         if (is_string($param['other'])) {
             if (!$param["multiple"]) {
                 $param['values'] = array($other_select_option);
             } else {
                 $param['values'][] = $other_select_option;
             }
         }
     }
     $param['option_tooltips'] = Html::entities_deep($param['option_tooltips']);
     if ($param["display_emptychoice"]) {
         $elements = array(0 => $param['emptylabel']) + $elements;
     }
     if ($param["multiple"]) {
         $field_name = $name . "[]";
     } else {
         $field_name = $name;
     }
     $output = '';
     // readonly mode
     $field_id = Html::cleanId("dropdown_" . $name . $param['rand']);
     if ($param['readonly']) {
         $to_display = array();
         foreach ($param['values'] as $value) {
             $output .= "<input type='hidden' name='{$field_name}' value='{$value}'>";
             if (isset($elements[$value])) {
                 $to_display[] = $elements[$value];
             }
         }
         $output .= implode('<br>', $to_display);
     } else {
         $output .= "<select name='{$field_name}' id='{$field_id}'";
         if ($param['tooltip']) {
             $output .= ' title="' . Html::entities_deep($param['tooltip']) . '"';
         }
         if (!empty($param["on_change"])) {
             $output .= " onChange='" . $param["on_change"] . "'";
         }
         if (is_int($param["size"]) && $param["size"] > 0) {
             $output .= " size='" . $param["size"] . "'";
         }
         if ($param["multiple"]) {
             $output .= " multiple";
         }
         $output .= '>';
         $max_option_size = 0;
         foreach ($elements as $key => $val) {
             // optgroup management
             if (is_array($val)) {
                 $opt_goup = Html::entities_deep($key);
                 if ($max_option_size < strlen($opt_goup)) {
                     $max_option_size = strlen($opt_goup);
                 }
                 $output .= "<optgroup label=\"{$opt_goup}\"";
                 $optgroup_tooltips = false;
                 if (isset($param['option_tooltips'][$key])) {
                     if (is_array($param['option_tooltips'][$key])) {
                         if (isset($param['option_tooltips'][$key]['__optgroup_label'])) {
                             $output .= ' title="' . $param['option_tooltips'][$key]['__optgroup_label'] . '"';
                         }
                         $optgroup_tooltips = $param['option_tooltips'][$key];
                     } else {
                         $output .= ' title="' . $param['option_tooltips'][$key] . '"';
                     }
                 }
                 $output .= ">";
                 foreach ($val as $key2 => $val2) {
                     if (!isset($param['used'][$key2])) {
                         $output .= "<option value='" . $key2 . "'";
                         // Do not use in_array : trouble with 0 and empty value
                         foreach ($param['values'] as $value) {
                             if (strcmp($key2, $value) === 0) {
                                 $output .= " selected";
                                 break;
                             }
                         }
                         if ($optgroup_tooltips && isset($optgroup_tooltips[$key2])) {
                             $output .= ' title="' . $optgroup_tooltips[$key2] . '"';
                         }
                         $output .= ">" . $val2 . "</option>";
                         if ($max_option_size < strlen($val2)) {
                             $max_option_size = strlen($val2);
                         }
                     }
                 }
                 $output .= "</optgroup>";
             } else {
                 if (!isset($param['used'][$key])) {
                     $output .= "<option value='" . $key . "'";
                     // Do not use in_array : trouble with 0 and empty value
                     foreach ($param['values'] as $value) {
                         if (strcmp($key, $value) === 0) {
                             $output .= " selected";
                             break;
                         }
                     }
                     if (isset($param['option_tooltips'][$key])) {
                         $output .= ' title="' . $param['option_tooltips'][$key] . '"';
                     }
                     $output .= ">" . $val . "</option>";
                     if ($max_option_size < strlen($val)) {
                         $max_option_size = strlen($val);
                     }
                 }
             }
         }
         if ($param['other'] !== false) {
             $output .= "<option value='{$other_select_option}'";
             if (is_string($param['other'])) {
                 $output .= " selected";
             }
             $output .= ">" . __('Other...') . "</option>";
         }
         $output .= "</select>";
         if ($param['other'] !== false) {
             $output .= "<input name='{$other_select_option}' id='{$other_select_option}' type='text'";
             if (is_string($param['other'])) {
                 $output .= " value=\"" . $param['other'] . "\"";
             } else {
                 $output .= " style=\"display: none\"";
             }
             $output .= ">";
         }
     }
     // Width set on select
     $output .= Html::jsAdaptDropdown($field_id, array('width' => $param["width"]));
     if ($param["multiple"]) {
         // Hack for All / None because select2 does not provide it
         $select = __('All');
         $deselect = __('None');
         $output .= "<div class='invisible' id='selectallbuttons_{$field_id}'>";
         $output .= "<div class='select2-actionable-menu'>";
         $output .= "<a class='vsubmit floatleft' " . "onclick=\"selectAll('{$field_id}');\$('#{$field_id}').select2('close');\">{$select}" . "</a> ";
         $output .= "<a class='vsubmit floatright' onclick=\"deselectAll('{$field_id}');\">{$deselect}" . "</a>";
         $output .= "</div></div>";
         $js = "\n         var multichecksappend{$field_id} = false;\n         \$('#{$field_id}').on('select2-open', function() {\n            if (!multichecksappend{$field_id}) {\n               \$('#select2-drop').append(\$('#selectallbuttons_{$field_id}').html());\n               multichecksappend{$field_id} = true;\n            }\n         });";
         $output .= Html::scriptBlock($js);
     }
     $output .= Ajax::commonDropdownUpdateItem($param, false);
     if ($param['display']) {
         echo $output;
         return $param['rand'];
     }
     return $output;
 }
Example #7
0
 /**
  * @param $target             NotificationTarget object
  * @param $user_infos   array
  * @param $event
  * @param $options      array
  *
  * @return id of the template in templates_by_languages / false if computation failed
  **/
 function getTemplateByLanguage(NotificationTarget $target, $user_infos = array(), $event, $options = array())
 {
     $lang = array();
     $language = $user_infos['language'];
     if (isset($user_infos['additionnaloption'])) {
         $additionnaloption = $user_infos['additionnaloption'];
     } else {
         $additionnaloption = array();
     }
     $tid = $language;
     $tid .= serialize($additionnaloption);
     $tid = sha1($tid);
     if (!isset($this->templates_by_languages[$tid])) {
         //Switch to the desired language
         $bak_dropdowntranslations = $_SESSION['glpi_dropdowntranslations'];
         $_SESSION['glpi_dropdowntranslations'] = DropdownTranslation::getAvailableTranslations($language);
         Session::loadLanguage($language);
         $bak_language = $_SESSION["glpilanguage"];
         $_SESSION["glpilanguage"] = $language;
         //If event is raised by a plugin, load it in order to get the language file available
         if ($plug = isPluginItemType(get_class($target->obj))) {
             Plugin::loadLang(strtolower($plug['plugin']), $language);
         }
         //Get template's language data for in this language
         $options['additionnaloption'] = $additionnaloption;
         $data =& $target->getForTemplate($event, $options);
         $footer_string = Html::entity_decode_deep(sprintf(__('Automatically generated by GLPI %s'), GLPI_VERSION));
         $add_header = Html::entity_decode_deep($target->getContentHeader());
         $add_footer = Html::entity_decode_deep($target->getContentFooter());
         //Restore default language
         $_SESSION["glpilanguage"] = $bak_language;
         Session::loadLanguage();
         $_SESSION['glpi_dropdowntranslations'] = $bak_dropdowntranslations;
         if ($plug = isPluginItemType(get_class($target->obj))) {
             Plugin::loadLang(strtolower($plug['plugin']));
         }
         if ($template_datas = $this->getByLanguage($language)) {
             //Template processing
             // Decode html chars to have clean text
             $template_datas['content_text'] = Html::entity_decode_deep($template_datas['content_text']);
             $save_data = $data;
             $data = Html::entity_decode_deep($data);
             $template_datas['subject'] = Html::entity_decode_deep($template_datas['subject']);
             $this->signature = Html::entity_decode_deep($this->signature);
             $lang['subject'] = $target->getSubjectPrefix($event) . self::process($template_datas['subject'], $data);
             $lang['content_html'] = '';
             //If no html content, then send only in text
             if (!empty($template_datas['content_html'])) {
                 // Encode in HTML all chars
                 $data_html = Html::entities_deep($data);
                 $data_html = Html::nl2br_deep($data_html);
                 // Restore HTML tags
                 if (count($target->html_tags)) {
                     foreach ($target->html_tags as $tag) {
                         if (isset($save_data[$tag])) {
                             $data_html[$tag] = $save_data[$tag];
                         }
                     }
                 }
                 $signature_html = Html::entities_deep($this->signature);
                 $signature_html = Html::nl2br_deep($signature_html);
                 $template_datas['content_html'] = self::process($template_datas['content_html'], $data_html);
                 $lang['content_html'] = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n                        'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>" . "<html>\n                        <head>\n                         <META http-equiv='Content-Type' content='text/html; charset=utf-8'>\n                         <title>" . Html::entities_deep($lang['subject']) . "</title>\n                         <style type='text/css'>\n                           " . $this->fields['css'] . "\n                         </style>\n                        </head>\n                        <body>\n" . (!empty($add_header) ? $add_header . "\n<br><br>" : '') . $template_datas['content_html'] . "<br><br>-- \n<br>" . $signature_html . "<br>{$footer_string}" . "<br><br>\n" . (!empty($add_footer) ? $add_footer . "\n<br><br>" : '') . "\n</body></html>";
             }
             $lang['content_text'] = (!empty($add_header) ? $add_header . "\n\n" : '') . Html::clean(self::process($template_datas['content_text'], $data) . "\n\n-- \n" . $this->signature . "\n" . Html::entity_decode_deep(sprintf(__('Automatically generated by GLPI %s'), GLPI_VERSION))) . "\n\n" . $add_footer;
             $this->templates_by_languages[$tid] = $lang;
         }
     }
     if (isset($this->templates_by_languages[$tid])) {
         return $tid;
     }
     return false;
 }
Example #8
0
 /** function buildTicket - Builds,and returns, the major structure of the ticket to be entered.
  *
  * @param $i                  mail ID
  * @param $options   array    of possible options
  *
  * @return ticket fields array
  */
 function buildTicket($i, $options = array())
 {
     global $CFG_GLPI;
     $play_rules = isset($options['play_rules']) && $options['play_rules'];
     $head = $this->getHeaders($i);
     // Get Header Info Return Array Of Headers
     // **Key Are (subject,to,toOth,toNameOth,from,fromName)
     $tkt = array();
     $tkt['_blacklisted'] = false;
     // For RuleTickets
     $tkt['_mailgate'] = $options['mailgates_id'];
     // Use mail date if it's defined
     if ($this->fields['use_mail_date']) {
         $tkt['date'] = $head['date'];
     }
     // Detect if it is a mail reply
     $glpi_message_match = "/GLPI-([0-9]+)\\.[0-9]+\\.[0-9]+@\\w*/";
     // Check if email not send by GLPI : if yes -> blacklist
     if (!isset($head['message_id']) || preg_match($glpi_message_match, $head['message_id'], $match)) {
         $tkt['_blacklisted'] = true;
         return $tkt;
     }
     // manage blacklist
     $blacklisted_emails = Blacklist::getEmails();
     // Add name of the mailcollector as blacklisted
     $blacklisted_emails[] = $this->fields['name'];
     if (Toolbox::inArrayCaseCompare($head['from'], $blacklisted_emails)) {
         $tkt['_blacklisted'] = true;
         return $tkt;
     }
     // max size = 0 : no import attachments
     if ($this->fields['filesize_max'] > 0) {
         if (is_writable(GLPI_TMP_DIR)) {
             $tkt['_filename'] = $this->getAttached($i, GLPI_TMP_DIR . "/", $this->fields['filesize_max']);
             $tkt['_tag'] = $this->tags;
         } else {
             //TRANS: %s is a directory
             Toolbox::logInFile('mailgate', sprintf(__('%s is not writable'), GLPI_TMP_DIR . "/"));
         }
     }
     //  Who is the user ?
     $tkt['_users_id_requester'] = User::getOrImportByEmail($head['from']);
     $tkt["_users_id_requester_notif"]['use_notification'][0] = 1;
     // Set alternative email if user not found / used if anonymous mail creation is enable
     if (!$tkt['_users_id_requester']) {
         $tkt["_users_id_requester_notif"]['alternative_email'][0] = $head['from'];
     }
     // Add to and cc as additional observer if user found
     if (count($head['ccs'])) {
         foreach ($head['ccs'] as $cc) {
             if ($cc != $head['from'] && !Toolbox::inArrayCaseCompare($cc, $blacklisted_emails) && ($tmp = User::getOrImportByEmail($cc)) > 0) {
                 $tkt['_additional_observers'][] = array('users_id' => $tmp, 'use_notification' => 1);
             }
         }
     }
     if (count($head['tos'])) {
         foreach ($head['tos'] as $to) {
             if ($to != $head['from'] && !Toolbox::inArrayCaseCompare($to, $blacklisted_emails) && ($tmp = User::getOrImportByEmail($to)) > 0) {
                 $tkt['_additional_observers'][] = array('users_id' => $tmp, 'use_notification' => 1);
             }
         }
     }
     // Auto_import
     $tkt['_auto_import'] = 1;
     // For followup : do not check users_id = login user
     $tkt['_do_not_check_users_id'] = 1;
     $body = $this->getBody($i);
     // Do it before using charset variable
     $head['subject'] = $this->decodeMimeString($head['subject']);
     $tkt['_head'] = $head;
     if (!empty($this->charset) && !$this->body_converted && mb_detect_encoding($body) != 'UTF-8') {
         $body = Toolbox::encodeInUtf8($body, $this->charset);
         $this->body_converted = true;
     }
     if (!Toolbox::seems_utf8($body)) {
         $tkt['content'] = Toolbox::encodeInUtf8($body);
     } else {
         $tkt['content'] = $body;
     }
     // See In-Reply-To field
     if (isset($head['in_reply_to'])) {
         if (preg_match($glpi_message_match, $head['in_reply_to'], $match)) {
             $tkt['tickets_id'] = intval($match[1]);
         }
     }
     // See in References
     if (!isset($tkt['tickets_id']) && isset($head['references'])) {
         if (preg_match($glpi_message_match, $head['references'], $match)) {
             $tkt['tickets_id'] = intval($match[1]);
         }
     }
     // See in title
     if (!isset($tkt['tickets_id']) && preg_match('/\\[.+#(\\d+)\\]/', $head['subject'], $match)) {
         $tkt['tickets_id'] = intval($match[1]);
     }
     // Double encoding for > and < char to avoid misinterpretations
     $tkt['content'] = str_replace(array('&lt;', '&gt;'), array('&amp;lt;', '&amp;gt;'), $tkt['content']);
     $is_html = false;
     //If files are present and content is html
     if (isset($this->files) && count($this->files) && $tkt['content'] != strip_tags($tkt['content']) && !isset($tkt['tickets_id'])) {
         $is_html = true;
         $tkt['content'] = Ticket::convertContentForTicket($tkt['content'], array_merge($this->files, $this->altfiles), $this->tags);
     }
     // Clean mail content
     $striptags = true;
     if ($CFG_GLPI["use_rich_text"] && !isset($tkt['tickets_id'])) {
         $striptags = false;
     }
     $tkt['content'] = $this->cleanMailContent(Html::entities_deep($tkt['content']), $striptags);
     if ($is_html && !isset($tkt['tickets_id'])) {
         $tkt['content'] = nl2br($tkt['content']);
     }
     $tkt['_supplier_email'] = false;
     // Found ticket link
     if (isset($tkt['tickets_id'])) {
         // it's a reply to a previous ticket
         $job = new Ticket();
         $tu = new Ticket_User();
         $st = new Supplier_Ticket();
         // Check if ticket  exists and users_id exists in GLPI
         /// TODO check if users_id have right to add a followup to the ticket
         if ($job->getFromDB($tkt['tickets_id']) && $job->fields['status'] != CommonITILObject::CLOSED && ($CFG_GLPI['use_anonymous_followups'] || $tkt['_users_id_requester'] > 0 || $tu->isAlternateEmailForITILObject($tkt['tickets_id'], $head['from']) || ($tkt['_supplier_email'] = $st->isSupplierEmail($tkt['tickets_id'], $head['from'])))) {
             if ($tkt['_supplier_email']) {
                 $tkt['content'] = sprintf(__('From %s'), $head['from']) . "\n\n" . $tkt['content'];
             }
             $content = explode("\n", $tkt['content']);
             $tkt['content'] = "";
             $to_keep = array();
             // Move requester to author of followup :
             $tkt['users_id'] = $tkt['_users_id_requester'];
             $begin_strip = -1;
             $end_strip = -1;
             $begin_match = "/" . NotificationTargetTicket::HEADERTAG . ".*" . NotificationTargetTicket::HEADERTAG . "/";
             $end_match = "/" . NotificationTargetTicket::FOOTERTAG . ".*" . NotificationTargetTicket::FOOTERTAG . "/";
             foreach ($content as $ID => $val) {
                 // Get first tag for begin
                 if ($begin_strip < 0) {
                     if (preg_match($begin_match, $val)) {
                         $begin_strip = $ID;
                     }
                 }
                 // Get last tag for end
                 if ($begin_strip >= 0) {
                     if (preg_match($end_match, $val)) {
                         $end_strip = $ID;
                         continue;
                     }
                 }
             }
             if ($begin_strip >= 0) {
                 // Clean first and last lines
                 $content[$begin_strip] = preg_replace($begin_match, '', $content[$begin_strip]);
             }
             if ($end_strip >= 0) {
                 // Clean first and last lines
                 $content[$end_strip] = preg_replace($end_match, '', $content[$end_strip]);
             }
             if ($begin_strip >= 0) {
                 $length = count($content);
                 // Use end strip if set
                 if ($end_strip >= 0 && $end_strip < $length) {
                     $length = $end_strip;
                 }
                 for ($i = $begin_strip + 1; $i < $length; $i++) {
                     unset($content[$i]);
                 }
             }
             $to_keep = array();
             // Aditional clean for thunderbird
             foreach ($content as $ID => $val) {
                 if (!isset($val[0]) || $val[0] != '>') {
                     $to_keep[$ID] = $ID;
                 }
             }
             $tkt['content'] = "";
             foreach ($to_keep as $ID) {
                 $tkt['content'] .= $content[$ID] . "\n";
             }
             // Do not play rules for followups : WRONG : play rules only for refuse options
             //$play_rules = false;
         } else {
             // => to handle link in Ticket->post_addItem()
             $tkt['_linkedto'] = $tkt['tickets_id'];
             unset($tkt['tickets_id']);
         }
     }
     // Add message from getAttached
     if ($this->addtobody) {
         $tkt['content'] .= $this->addtobody;
     }
     if (!Toolbox::seems_utf8($tkt['name'])) {
         $tkt['name'] = Toolbox::encodeInUtf8($tkt['name']);
     }
     $tkt['name'] = $this->textCleaner($head['subject']);
     if (!isset($tkt['tickets_id'])) {
         // Which entity ?
         //$tkt['entities_id']=$this->fields['entities_id'];
         //$tkt['Subject']= $head['subject'];   // not use for the moment
         // Medium
         $tkt['urgency'] = "3";
         // No hardware associated
         $tkt['itemtype'] = "";
         // Mail request type
     } else {
         // Reopen if needed
         $tkt['add_reopen'] = 1;
     }
     $tkt['requesttypes_id'] = RequestType::getDefault('mail');
     if ($play_rules) {
         $rule_options['ticket'] = $tkt;
         $rule_options['headers'] = $head;
         $rule_options['mailcollector'] = $options['mailgates_id'];
         $rule_options['_users_id_requester'] = $tkt['_users_id_requester'];
         $rulecollection = new RuleMailCollectorCollection();
         $output = $rulecollection->processAllRules(array(), array(), $rule_options);
         // New ticket : compute all
         if (!isset($tkt['tickets_id'])) {
             foreach ($output as $key => $value) {
                 $tkt[$key] = $value;
             }
         } else {
             // Followup only copy refuse data
             $tkt['requesttypes_id'] = RequestType::getDefault('mailfollowup');
             $tobecopied = array('_refuse_email_no_response', '_refuse_email_with_response');
             foreach ($tobecopied as $val) {
                 if (isset($output[$val])) {
                     $tkt[$val] = $output[$val];
                 }
             }
         }
     }
     $tkt = Toolbox::addslashes_deep($tkt);
     return $tkt;
 }
Example #9
0
 /**
  * Dropdown of values in an array
  *
  * @param $name            select name
  * @param $elements  array of elements to display
  * @param $options   array of possible options:
  *    - value           : integer / preselected value (default 0)
  *    - used            : array / Already used items ID: not to display in dropdown (default empty)
  *    - readonly        : boolean / used as a readonly item (default false)
  *    - on_change       : string / value to transmit to "onChange"
  *    - multiple        : boolean / can select several values (default false)
  *    - size            : integer / number of rows for the select (default = 1)
  *    - mark_unmark_all : add buttons to select or deselect all options (only for multiple)
  *    - display         : boolean / display or return string
  *    - other           : boolean or string if not false, then we can use an "other" value
  *                        if it is a string, then the default value will be this string
  *    - rand            : specific rand if needed (default is generated one)
  *
  * Permit to use optgroup defining items in arrays
  * array('optgroupname'  => array('key1' => 'val1',
  *                                'key2' => 'val2'),
  *       'optgroupname2' => array('key3' => 'val3',
  *                                'key4' => 'val4'))
  **/
 static function showFromArray($name, array $elements, $options = array())
 {
     $param['value'] = '';
     $param['values'] = array();
     $param['used'] = array();
     $param['readonly'] = false;
     $param['on_change'] = '';
     $param['multiple'] = false;
     $param['size'] = 1;
     $param['mark_unmark_all'] = false;
     $param['display'] = true;
     $param['other'] = false;
     $param['rand'] = mt_rand();
     if (is_array($options) && count($options)) {
         if (isset($options['value']) && strlen($options['value'])) {
             $options['values'] = array($options['value']);
             unset($options['value']);
         }
         foreach ($options as $key => $val) {
             $param[$key] = $val;
         }
     }
     if ($param['other'] !== false) {
         $other_select_option = $name . '_other_value';
         $param['on_change'] .= "displayOtherSelectOptions(this, \"{$other_select_option}\");";
         // If $param['other'] is a string, then we must highlight "other" option
         if (is_string($param['other'])) {
             if (!$param["multiple"]) {
                 $param['values'] = array($other_select_option);
             } else {
                 $param['values'][] = $other_select_option;
             }
         }
     }
     if ($param["multiple"]) {
         $field_name = $name . "[]";
     } else {
         $field_name = $name;
     }
     $output = '';
     // readonly mode
     if ($param['readonly']) {
         foreach ($param['values'] as $value) {
             $output .= "<input type='hidden' name='{$field_name}' value='{$value}'>";
             if (isset($elements[$value])) {
                 $output .= $elements[$value] . " ";
             }
         }
     } else {
         $field_id = "dropdown_" . $name . $param['rand'];
         $output .= "<select name='{$field_name}' id='{$field_id}'";
         if (!empty($param["on_change"])) {
             $output .= " onChange='" . $param["on_change"] . "'";
         }
         if (is_int($param["size"]) && $param["size"] > 0) {
             $output .= " size='" . $param["size"] . "'";
         }
         if ($param["multiple"]) {
             $output .= " multiple";
         }
         $output .= '>';
         $max_option_size = 0;
         foreach ($elements as $key => $val) {
             // optgroup management
             if (is_array($val)) {
                 $opt_goup = Html::entities_deep($key);
                 if ($max_option_size < strlen($opt_goup)) {
                     $max_option_size = strlen($opt_goup);
                 }
                 $output .= "<optgroup label=\"{$opt_goup}\">";
                 foreach ($val as $key2 => $val2) {
                     if (!isset($param['used'][$key2])) {
                         $output .= "<option value='" . $key2 . "'";
                         if (in_array($key2, $param['values'])) {
                             $output .= " selected";
                         }
                         $output .= ">" . $val2 . "</option>";
                         if ($max_option_size < strlen($val2)) {
                             $max_option_size = strlen($val2);
                         }
                     }
                 }
                 $output .= "</optgroup>";
             } else {
                 if (!isset($param['used'][$key])) {
                     $output .= "<option value='" . $key . "'";
                     if (in_array($key, $param['values'])) {
                         $output .= " selected";
                     }
                     $output .= ">" . $val . "</option>";
                     if ($max_option_size < strlen($val)) {
                         $max_option_size = strlen($val);
                     }
                 }
             }
         }
         if ($param['other'] !== false) {
             $output .= "<option value='{$other_select_option}'";
             if (is_string($param['other'])) {
                 $output .= " selected";
             }
             $output .= ">" . __('Other...') . "</option>";
         }
         $output .= "</select>";
         if ($param['other'] !== false) {
             $output .= "<input name='{$other_select_option}' id='{$other_select_option}' type='text'";
             if (is_string($param['other'])) {
                 $output .= " value=\"" . $param['other'] . "\"";
             } else {
                 $output .= " style=\"display: none\"";
             }
             $output .= ">";
         }
         if ($param['mark_unmark_all'] && $param['multiple']) {
             $select = __('Select all');
             $deselect = __('Deselect all');
             $size = strlen($select) + strlen($deselect);
             $select = "<input type='button' onclick=\"selectAllOptions('{$field_id}')\" value=\"{$select}\">";
             $deselect = "<input type='button' onclick=\"unselectAllOptions('{$field_id}')\" value=\"{$deselect}\">";
             if ($size > $max_option_size) {
                 $output = "<table><tr><td rowspan='2'>" . $output . "</td>";
                 $output .= "<td>";
                 $output .= $select;
                 $output .= "</td></tr><tr><td class='center'>";
                 $output .= $deselect;
             } else {
                 $output = "<table><tr><td colspan='2'>" . $output . "</td>";
                 $output .= "</tr><tr><td class='center'>";
                 $output .= $select;
                 $output .= "</td><td class='center'>";
                 $output .= $deselect;
             }
             $output .= "</td></tr></table>";
         }
     }
     if ($param['display']) {
         echo $output;
         return $param['rand'];
     }
     return $output;
 }
Example #10
0
 /**
  * Display a 2 columns Footer for Form buttons
  * Close the form is user can edit
  *
  * @param $options   array of possible options:
  *     - withtemplate : 1 for newtemplate, 2 for newobject from template
  *     - colspan for each column (default 2)
  *     - candel : set to false to hide "delete" button
  *     - canedit : set to false to hide all buttons
  *     - addbuttons : array of buttons to add
  **/
 function showFormButtons($options = array())
 {
     global $CFG_GLPI;
     // for single object like config
     if (isset($this->fields['id'])) {
         $ID = $this->fields['id'];
     } else {
         $ID = 1;
     }
     $params['colspan'] = 2;
     $params['withtemplate'] = '';
     $params['candel'] = true;
     $params['canedit'] = true;
     $params['addbuttons'] = array();
     if (is_array($options) && count($options)) {
         foreach ($options as $key => $val) {
             $params[$key] = $val;
         }
     }
     if (!$params['canedit'] || !$this->canEdit($ID)) {
         echo "</table></div>";
         // Form Header always open form
         if (!$params['canedit']) {
             Html::closeForm();
         }
         return false;
     }
     echo "<tr class='tab_bg_2'>";
     if ($params['withtemplate'] || $this->isNewID($ID)) {
         echo "<td class='center' colspan='" . $params['colspan'] * 2 . "'>";
         if ($ID <= 0 || $params['withtemplate'] == 2) {
             echo Html::submit(_x('button', 'Add'), array('name' => 'add'));
         } else {
             //TRANS : means update / actualize
             echo Html::submit(_x('button', 'Save'), array('name' => 'update'));
         }
     } else {
         if ($params['candel'] && !$this->can($ID, DELETE) && !$this->can($ID, PURGE)) {
             $params['candel'] = false;
         }
         if ($params['canedit'] && $this->can($ID, UPDATE)) {
             echo "<td class='center' colspan='" . $params['colspan'] * 2 . "'>\n";
             echo Html::submit(_x('button', 'Save'), array('name' => 'update'));
         }
         if ($params['candel']) {
             if ($params['canedit'] && $this->can($ID, UPDATE)) {
                 echo "</td></tr><tr class='tab_bg_2'>\n";
             }
             if ($this->isDeleted()) {
                 if ($this->can($ID, DELETE)) {
                     echo "<td class='right' colspan='" . $params['colspan'] * 2 . "' >\n";
                     echo Html::submit(_x('button', 'Restore'), array('name' => 'restore'));
                 }
                 if ($this->can($ID, PURGE)) {
                     echo "<span class='very_small_space'>";
                     if (in_array($this->getType(), Item_Devices::getConcernedItems())) {
                         Html::showToolTip(__('Check to keep the devices while deleting this item'));
                         echo "&nbsp;";
                         echo "<input type='checkbox' name='keep_devices' value='1'";
                         if (!empty($_SESSION['glpikeep_devices_when_purging_item'])) {
                             echo " checked";
                         }
                         echo ">&nbsp;";
                     }
                     echo Html::submit(_x('button', 'Delete permanently'), array('name' => 'purge'));
                     echo "</span>";
                 }
             } else {
                 echo "<td class='right' colspan='" . $params['colspan'] * 2 . "' >\n";
                 // If maybe dynamic : do not take into account  is_deleted  field
                 if (!$this->maybeDeleted() || $this->useDeletedToLockIfDynamic()) {
                     if ($this->can($ID, PURGE)) {
                         echo Html::submit(_x('button', 'Delete permanently'), array('name' => 'purge', 'confirm' => __('Confirm the final deletion?')));
                     }
                 } else {
                     if (!$this->isDeleted() && $this->can($ID, DELETE)) {
                         echo Html::submit(_x('button', 'Put in dustbin'), array('name' => 'delete'));
                     }
                 }
             }
         }
         if ($this->isField('date_mod')) {
             echo "<input type='hidden' name='_read_date_mod' value='" . $this->getField('date_mod') . "'>";
         }
     }
     if (!$this->isNewID($ID)) {
         echo "<input type='hidden' name='id' value='{$ID}'>";
     }
     echo "</td>";
     echo "</tr>\n";
     if ($params['canedit'] && count($params['addbuttons'])) {
         echo "<tr class='tab_bg_2'>";
         if ($params['colspan'] * 2 - count($params['addbuttons']) > 0) {
             echo "<td colspan='" . ($params['colspan'] * 2 - count($params['addbuttons'])) . "'>&nbsp;" . "</td>";
         }
         foreach ($params['addbuttons'] as $key => $val) {
             echo "<td><input class='submit' type='submit' name='{$key}' value=\"" . Html::entities_deep($val) . "\"></td>";
         }
         echo "</tr>";
     }
     // Close for Form
     echo "</table></div>";
     Html::closeForm();
 }
Example #11
0
 /**
  * @since version 0.85 (since 0.85 but param $id since 0.85)
  *
  * @param $canedit
  * @param $field_name
  * @param $id
  **/
 function showChildForItemForm($canedit, $field_name, $id)
 {
     if ($this->isNewID($this->getID())) {
         $value = '';
     } else {
         $value = Html::entities_deep($this->fields['email']);
     }
     $field_name = $field_name . "[{$id}]";
     echo "<input title='" . __s('Default email') . "' type='radio' name='_default_email'\n             value='" . $this->getID() . "'";
     if (!$canedit) {
         echo " disabled";
     }
     if ($this->fields['is_default']) {
         echo " checked";
     }
     echo ">&nbsp;";
     if (!$canedit || $this->fields['is_dynamic']) {
         echo "<input type='hidden' name='{$field_name}' value='{$value}'>";
         printf(__('%1$s %2$s'), $value, "<span class='b'>(" . __('D') . ")</span>");
     } else {
         echo "<input type='text' size=30 name='{$field_name}' value='{$value}' >";
     }
 }
Example #12
0
 /**
  * Display a 2 columns Footer for Form buttons
  * Close the form is user can edit
  *
  * @param $options   array of possible options:
  *     - withtemplate : 1 for newtemplate, 2 for newobject from template
  *     - colspan for each column (default 2)
  *     - candel : set to false to hide "delete" button
  *     - canedit : set to false to hide all buttons
  *     - addbuttons : array of buttons to add
  **/
 function showFormButtons($options = array())
 {
     // for single object like config
     if (isset($this->fields['id'])) {
         $ID = $this->fields['id'];
     } else {
         $ID = 1;
     }
     $params['colspan'] = 2;
     $params['withtemplate'] = '';
     $params['candel'] = true;
     $params['canedit'] = true;
     $params['addbuttons'] = array();
     if (is_array($options) && count($options)) {
         foreach ($options as $key => $val) {
             $params[$key] = $val;
         }
     }
     if (!$params['canedit'] || !$this->can($ID, 'w') && !$this->can($ID, 'd')) {
         echo "</table></div>";
         // Form Header always open form
         if (!$params['canedit']) {
             Html::closeForm();
         }
         return false;
     }
     echo "<tr class='tab_bg_2'>";
     if ($params['withtemplate'] || $this->isNewID($ID)) {
         echo "<td class='center' colspan='" . $params['colspan'] * 2 . "'>";
         if ($ID <= 0 || $params['withtemplate'] == 2) {
             echo "<input type='submit' name='add' value=\"" . _sx('button', 'Add') . "\" class='submit'>";
         } else {
             //TRANS : means update / actualize
             echo "<input type='submit' name='update' value=\"" . _sx('button', 'Save') . "\" class='submit'>";
         }
     } else {
         if ($params['candel'] && !$this->can($ID, 'd')) {
             $params['candel'] = false;
         }
         if ($params['candel']) {
             echo "<td class='center' colspan='" . $params['colspan'] * 2 . "'>\n";
             echo "<input type='submit' name='update' value=\"" . _sx('button', 'Save') . "\"\n                   class='submit'>";
             echo "</td></tr><tr class='tab_bg_2'>\n";
             if ($this->isDeleted()) {
                 echo "<td class='right' colspan='" . $params['colspan'] * 2 . "' >\n";
                 echo "<input type='submit' name='restore' value=\"" . _sx('button', 'Restore') . "\"\n                      class='submit'>";
                 echo "<span class='very_small_space'><input type='submit' name='purge' value=\"" . _sx('button', 'Delete permanently') . "\" class='submit'></span>";
             } else {
                 echo "<td class='right' colspan='" . $params['colspan'] * 2 . "' >\n";
                 // If maybe dynamic : do not take into account  is_deleted  field
                 if (!$this->maybeDeleted() || $this->useDeletedToLockIfDynamic()) {
                     echo "<input type='submit' name='delete' value=\"" . _sx('button', 'Delete permanently') . "\"\n                         class='submit' " . Html::addConfirmationOnAction(__('Confirm the final deletion?')) . ">";
                 } else {
                     echo "<input type='submit' name='delete' value='" . _sx('button', 'Put in dustbin') . "'\n                         class='submit'>";
                 }
             }
         } else {
             echo "<td class='center' colspan='" . $params['colspan'] * 2 . "'>\n";
             echo "<input type='submit' name='update' value=\"" . _sx('button', 'Save') . "\"\n                   class='submit'>";
         }
         if ($this->isField('date_mod')) {
             echo "<input type='hidden' name='_read_date_mod' value='" . $this->getField('date_mod') . "'>";
         }
     }
     if (!$this->isNewID($ID)) {
         echo "<input type='hidden' name='id' value='{$ID}'>";
     }
     echo "</td>";
     echo "</tr>\n";
     if ($params['canedit'] && count($params['addbuttons'])) {
         echo "<tr class='tab_bg_2'>";
         if ($params['colspan'] * 2 - count($params['addbuttons']) > 0) {
             echo "<td colspan='" . ($params['colspan'] * 2 - count($params['addbuttons'])) . "'>&nbsp;" . "</td>";
         }
         foreach ($params['addbuttons'] as $key => $val) {
             echo "<td><input class='submit' type='submit' name='{$key}' value=\"" . Html::entities_deep($val) . "\"></td>";
         }
         echo "</tr>";
     }
     // Close for Form
     echo "</table></div>";
     Html::closeForm();
 }