static function geTimelineItems(Ticket $ticket, $rand)
 {
     global $DB, $CFG_GLPI;
     $timeline = array();
     $user = new User();
     $group = new Group();
     $followup_obj = new TicketFollowup();
     $task_obj = new TicketTask();
     $document_item_obj = new Document_Item();
     $ticket_valitation_obj = new TicketValidation();
     //checks rights
     $showpublic = Session::haveRightsOr("followup", array(TicketFollowup::SEEPUBLIC, TicketFollowup::SEEPRIVATE)) && Session::haveRightsOr("task", array(TicketTask::SEEPUBLIC, TicketTask::SEEPRIVATE));
     $restrict_fup = $restrict_task = "";
     if (!Session::haveRight("ticket", TicketFollowup::SEEPRIVATE)) {
         $restrict_fup = " AND (`is_private` = '0'\n                            OR `users_id` ='" . Session::getLoginUserID() . "') ";
     }
     if (!Session::haveRight("ticket", TicketTask::SEEPRIVATE)) {
         $restrict_task = " AND (`is_private` = '0'\n                            OR `users_id` ='" . Session::getLoginUserID() . "') ";
     }
     if (!$showpublic) {
         $restrict = " AND 1 = 0";
     }
     //add ticket followups to timeline
     $followups = $followup_obj->find("tickets_id = " . $ticket->getID() . " {$restrict_fup}", 'date DESC');
     foreach ($followups as $followups_id => $followup) {
         $followup_obj->getFromDB($followups_id);
         $can_edit = $followup_obj->canUpdateItem();
         $followup['can_edit'] = $can_edit;
         $timeline[$followup['date'] . "_followup_" . $followups_id] = array('type' => 'TicketFollowup', 'item' => $followup);
     }
     //add ticket tasks to timeline
     $tasks = $task_obj->find("tickets_id = " . $ticket->getID() . " {$restrict_task}", 'date DESC');
     foreach ($tasks as $tasks_id => $task) {
         $task_obj->getFromDB($tasks_id);
         $can_edit = $task_obj->canUpdateItem();
         $task['can_edit'] = $can_edit;
         $timeline[$task['date'] . "_task_" . $tasks_id] = array('type' => 'TicketTask', 'item' => $task);
     }
     //add ticket documents to timeline
     $document_obj = new Document();
     $document_items = $document_item_obj->find("itemtype = 'Ticket' AND items_id = " . $ticket->getID());
     foreach ($document_items as $document_item) {
         $document_obj->getFromDB($document_item['documents_id']);
         $timeline[$document_obj->fields['date_mod'] . "_document_" . $document_item['documents_id']] = array('type' => 'Document_Item', 'item' => $document_obj->fields);
     }
     //add assign changes
     /*$log_obj = new Log;
           $gassign_items = $log_obj->find("itemtype = 'Ticket' AND items_id = ".$ticket->getID()." 
                                            AND itemtype_link = 'Group' AND linked_action = '15'");
     
           foreach ($gassign_items as $logs_id => $gassign) {
              //find group
              $group_name = preg_replace("#(.*)\s\([0-9]*\)#", "$1", $gassign['new_value']);
              $groups = $group->find("name = '$group_name'");
              $first_group = array_shift($groups);
              $group->getFromDB($first_group['id']);
              $content = __("Assigned to")." : ".
                         "<img src='".$CFG_GLPI['root_doc']."/plugins/talk/pics/group.png' class='group_assign' />".
                         "&nbsp;<strong>".$group->getLink()."</strong>";
     
              //find user
              $user_name = preg_replace("#(.*)\s\([0-9]*\)#", "$1", $gassign['user_name']);
              $users = $user->find("CONCAT(firstname, ' ', realname) = '$user_name'");
              $first_user = array_shift($users);
              if ($first_user == NULL) {
                 $first_user['id'] = false;
              }
     
              $timeline[$gassign['date_mod']."_assign_".$logs_id] = array('type' => 'Assign', 
                                                                          'item' => array(
                                                                             'date'     => $gassign['date_mod'],
                                                                             'content'  => $content,
                                                                             'can_edit' => false,
                                                                             'users_id' => $first_user['id']
                                                                          ));
           }*/
     //add existing solution
     if (!empty($ticket->fields['solution'])) {
         $users_id = 0;
         $solution_date = $ticket->fields['solvedate'];
         //search date and user of last solution in glpi_logs
         if ($res_solution = $DB->query("SELECT date_mod AS solution_date, user_name FROM glpi_logs\n                                     WHERE itemtype = 'Ticket' \n                                     AND items_id = " . $ticket->getID() . "\n                                     AND id_search_option = 24\n                                     ORDER BY id DESC\n                                     LIMIT 1")) {
             $data_solution = $DB->fetch_assoc($res_solution);
             if (!empty($data_solution['solution_date'])) {
                 $solution_date = $data_solution['solution_date'];
             }
             // find user
             if (!empty($data_solution['user_name'])) {
                 $users_id = addslashes(trim(preg_replace("/.*\\(([0-9]+)\\)/", "\$1", $data_solution['user_name'])));
             }
         }
         // fix trouble with html_entity_decode who skip accented characters (on windows browser)
         $solution_content = preg_replace_callback("/(&#[0-9]+;)/", function ($m) {
             return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES");
         }, $ticket->fields['solution']);
         $timeline[$solution_date . "_solution"] = array('type' => 'Solution', 'item' => array('id' => 0, 'content' => Html::clean(html_entity_decode($solution_content)), 'date' => $solution_date, 'users_id' => $users_id, 'solutiontypes_id' => $ticket->fields['solutiontypes_id'], 'can_edit' => Ticket::canUpdate() && $ticket->canSolve()));
     }
     // add ticket validation to timeline
     if ($ticket->fields['type'] == Ticket::DEMAND_TYPE && (Session::haveRight('ticketvalidation', TicketValidation::VALIDATEREQUEST) || Session::haveRight('ticketvalidation', TicketValidation::CREATEREQUEST)) || $ticket->fields['type'] == Ticket::INCIDENT_TYPE && (Session::haveRight('ticketvalidation', TicketValidation::VALIDATEINCIDENT) || Session::haveRight('ticketvalidation', TicketValidation::CREATEINCIDENT))) {
         $ticket_validations = $ticket_valitation_obj->find('tickets_id = ' . $ticket->getID());
         foreach ($ticket_validations as $validations_id => $validation) {
             $canedit = $ticket_valitation_obj->can($validations_id, UPDATE);
             $user->getFromDB($validation['users_id_validate']);
             $timeline[$validation['submission_date'] . "_validation_" . $validations_id] = array('type' => 'TicketValidation', 'item' => array('id' => $validations_id, 'date' => $validation['submission_date'], 'content' => __('Validation request') . " => " . $user->getlink() . "<br>" . $validation['comment_submission'], 'users_id' => $validation['users_id'], 'can_edit' => $canedit));
             if (!empty($validation['validation_date'])) {
                 $timeline[$validation['validation_date'] . "_validation_" . $validations_id] = array('type' => 'TicketValidation', 'item' => array('id' => $validations_id, 'date' => $validation['validation_date'], 'content' => __('Validation request answer') . " : " . _sx('status', ucfirst(TicketValidation::getStatus($validation['status']))) . "<br>" . $validation['comment_validation'], 'users_id' => $validation['users_id_validate'], 'status' => "status_" . $validation['status'], 'can_edit' => $canedit));
             }
         }
     }
     //reverse sort timeline items by key (date)
     krsort($timeline);
     return $timeline;
 }
 static function pdfForTicket(PluginPdfSimplePDF $pdf, Ticket $ticket)
 {
     global $CFG_GLPI, $DB;
     $pdf->setColumnsSize(100);
     $pdf->displayTitle("<b>" . __('Approvals for the ticket') . "</b>");
     if (!Session::haveRight('validate_request', 1) && !Session::haveRight('validate_incident', 1) && !Session::haveRight('create_incident_validation', 1) && !Session::haveRight('create_request_validation', 1)) {
         return false;
     }
     $ID = $ticket->getField('id');
     $query = "SELECT *\n                FROM `glpi_ticketvalidations`\n                WHERE `tickets_id` = '" . $ticket->getField('id') . "'\n                ORDER BY submission_date DESC";
     $result = $DB->query($query);
     $number = $DB->numrows($result);
     if ($number) {
         $pdf->setColumnsSize(20, 19, 21, 19, 21);
         $pdf->displayTitle(_x('item', 'State'), __('Request date'), __('Approval requester'), __('Approval date'), __('Approver'));
         while ($row = $DB->fetch_assoc($result)) {
             $pdf->setColumnsSize(20, 19, 21, 19, 21);
             $pdf->displayLine(TicketValidation::getStatus($row['status']), Html::convDateTime($row["submission_date"]), getUserName($row["users_id"]), Html::convDateTime($row["validation_date"]), getUserName($row["users_id_validate"]));
             $tmp = trim($row["comment_submission"]);
             $pdf->displayText("<b><i>" . sprintf(__('%1$s: %2$s'), __('Request comments') . "</i></b>", empty($tmp) ? __('None') : $tmp, 1));
             if ($row["validation_date"]) {
                 $tmp = trim($row["comment_validation"]);
                 $pdf->displayText("<b><i>" . sprintf(__('%1$s: %2$s'), __('Approval comments') . "</i></b>", empty($tmp) ? __('None') : $tmp, 1));
             }
         }
     } else {
         $pdf->displayLine(__('No item found'));
     }
     $pdf->displaySpace();
 }
示例#3
0
 function showForm($ID, $options = array())
 {
     global $DB, $CFG_GLPI, $LANG;
     $canupdate = haveRight('update_ticket', '1');
     $canpriority = haveRight('update_priority', '1');
     $showuserlink = 0;
     if (haveRight('user', 'r')) {
         $showuserlink = 1;
     }
     if ($ID > 0) {
         $this->check($ID, 'r');
     } else {
         // Create item
         $this->check(-1, 'w', $options);
     }
     $this->showTabs($options);
     $canupdate_descr = $canupdate || $this->fields['status'] == 'new' && $this->isUser(self::REQUESTER, getLoginUserID()) && $this->numberOfFollowups() == 0 && $this->numberOfTasks() == 0;
     if (!$ID) {
         //Get all the user's entities
         $all_entities = Profile_User::getUserEntities($options["_users_id_requester"], true);
         $this->userentities = array();
         //For each user's entity, check if the technician which creates the ticket have access to it
         foreach ($all_entities as $tmp => $ID_entity) {
             if (haveAccessToEntity($ID_entity)) {
                 $this->userentities[] = $ID_entity;
             }
         }
         $this->countentitiesforuser = count($this->userentities);
         if ($this->countentitiesforuser > 0 && !in_array($this->fields["entities_id"], $this->userentities)) {
             // If entity is not in the list of user's entities,
             // then use as default value the first value of the user's entites list
             $this->fields["entities_id"] = $this->userentities[0];
         }
     }
     echo "<form method='post' name='form_ticket' enctype='multipart/form-data' action='" . $CFG_GLPI["root_doc"] . "/front/ticket.form.php'>";
     echo "<div class='spaced' id='tabsbody'>";
     echo "<table class='tab_cadre_fixe'>";
     // Optional line
     $ismultientities = isMultiEntitiesMode();
     echo '<tr><th colspan="4">';
     if ($ID) {
         echo $this->getTypeName() . " - " . $LANG['common'][2] . " {$ID} ";
         if ($ismultientities) {
             echo "(" . Dropdown::getDropdownName('glpi_entities', $this->fields['entities_id']) . ")";
         }
     } else {
         if ($ismultientities) {
             echo $LANG['job'][46] . "&nbsp;:&nbsp;" . Dropdown::getDropdownName("glpi_entities", $this->fields['entities_id']);
         } else {
             echo $LANG['job'][13];
         }
     }
     echo '</th></tr>';
     echo "<tr>";
     echo "<th class='left' colspan='2'>";
     echo "<table>";
     echo "<tr>";
     echo "<td><span class='tracking_small'>" . $LANG['joblist'][11] . "&nbsp;: </span></td>";
     echo "<td>";
     $date = $this->fields["date"];
     if (!$ID) {
         $date = date("Y-m-d H:i:s");
     }
     if ($canupdate) {
         showDateTimeFormItem("date", $date, 1, false);
     } else {
         echo convDateTime($date);
     }
     echo "</td></tr>";
     if ($ID) {
         echo "<tr><td><span class='tracking_small'>" . $LANG['common'][95] . " &nbsp;:</span></td><td>";
         if ($canupdate) {
             User::dropdown(array('name' => 'users_id_recipient', 'value' => $this->fields["users_id_recipient"], 'entity' => $this->fields["entities_id"], 'right' => 'all'));
         } else {
             echo getUserName($this->fields["users_id_recipient"], $showuserlink);
         }
         echo "</td></tr>";
     }
     echo "</table>";
     echo "</th>";
     echo "<th class='left' colspan='2'>";
     echo "<table>";
     if ($ID) {
         echo "<tr><td><span class='tracking_small'>" . $LANG['common'][26] . "&nbsp;:</span></td>";
         echo "<td><span class='tracking_small'>" . convDateTime($this->fields["date_mod"]) . "\n";
         if ($this->fields['users_id_lastupdater'] > 0) {
             echo $LANG['common'][95] . "&nbsp;";
             echo getUserName($this->fields["users_id_lastupdater"], $showuserlink);
         }
         echo "</span>";
         echo "</td></tr>";
     }
     // SLA
     echo "<tr>";
     echo "<td><span class='tracking_small'>" . $LANG['sla'][5] . "&nbsp;: </span></td>";
     echo "<td>";
     if ($ID) {
         if ($this->fields["slas_id"] > 0) {
             echo "<span class='tracking_small'>&nbsp;";
             echo convDateTime($this->fields["due_date"]) . "</span>";
             echo "</td></tr><tr><td><span class='tracking_small'>" . $LANG['sla'][1] . "&nbsp;:</span></td>";
             echo "<td><span class='tracking_small'>";
             echo Dropdown::getDropdownName("glpi_slas", $this->fields["slas_id"]);
             $commentsla = "";
             $slalevel = new SlaLevel();
             if ($slalevel->getFromDB($this->fields['slalevels_id'])) {
                 $commentsla .= '<strong>' . $LANG['sla'][6] . "&nbsp;:&nbsp;</strong>" . $slalevel->getName() . '<br><br>';
             }
             $nextaction = new SlaLevel_Ticket();
             if ($nextaction->getFromDBForTicket($this->fields["id"])) {
                 $commentsla .= '<strong>' . $LANG['sla'][8] . "&nbsp;:&nbsp;</strong>" . convDateTime($nextaction->fields['date']) . '<br>';
                 if ($slalevel->getFromDB($nextaction->fields['slalevels_id'])) {
                     $commentsla .= '<strong>' . $LANG['sla'][6] . "&nbsp;:&nbsp;</strong>" . $slalevel->getName() . '<br>';
                 }
             }
             $slaoptions = array();
             if (haveRight('config', 'r')) {
             }
             $slaoptions['link'] = getItemTypeFormURL('SLA') . "?id=" . $this->fields["slas_id"];
             showToolTip($commentsla, $slaoptions);
             if ($canupdate) {
                 echo "&nbsp;<input type='submit' class='submit' name='sla_delete' value='" . $LANG['sla'][7] . "'>";
             }
             echo "</span>";
         } else {
             showDateTimeFormItem("due_date", $this->fields["due_date"], 1, false, $canupdate);
         }
     } else {
         // New Ticket
         if ($this->fields["due_date"] == 'NULL') {
             $this->fields["due_date"] = '';
         }
         showDateTimeFormItem("due_date", $this->fields["due_date"], 1, false, $canupdate);
         /*         echo $LANG['choice'][2]." ".$LANG['sla'][1]." : ";
                  Dropdown::show('Sla',array('entity' => $this->fields["entities_id"],
                                             'value' =>$this->fields["slas_id"]));*/
     }
     echo "</td></tr>";
     if ($ID) {
         switch ($this->fields["status"]) {
             case 'closed':
                 echo "<tr>";
                 echo "<td><span class='tracking_small'>" . $LANG['joblist'][12] . "&nbsp;: </span></td>";
                 echo "<td>";
                 showDateTimeFormItem("closedate", $this->fields["closedate"], 1, false, $canupdate);
                 echo "</td></tr>";
                 break;
             case 'solved':
                 echo "<tr>";
                 echo "<td><span class='tracking_small'>" . $LANG['joblist'][14] . "&nbsp;: </span></td>";
                 echo "<td>";
                 showDateTimeFormItem("solvedate", $this->fields["solvedate"], 1, false, $canupdate);
                 echo "</td></tr>";
                 break;
         }
     }
     echo "</table>";
     echo "</th></tr>";
     echo "</table>";
     if (!$ID) {
         $this->showActorsPartForm($ID, $options);
     }
     echo "<table  class='tab_cadre_fixe'>";
     echo "<tr class='tab_bg_1'>";
     echo "<th width='10%'>" . $LANG['joblist'][0] . "&nbsp;: </th>";
     echo "<td width='40%'>";
     if ($canupdate) {
         self::dropdownStatus("status", $this->fields["status"], 2);
         // Allowed status
     } else {
         echo self::getStatus($this->fields["status"]);
     }
     echo "</td>";
     echo "<th>" . $LANG['common'][17] . "&nbsp;: </th>";
     echo "<td >";
     // Permit to set type when creating ticket without update right
     if ($canupdate || !$ID) {
         self::dropdownType('type', $this->fields["type"]);
     } else {
         echo self::getTicketTypeName($this->fields["type"]);
     }
     echo "</td>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<th>" . $LANG['joblist'][29] . "&nbsp;: </th>";
     echo "<td>";
     if ($canupdate && $canpriority || !$ID || $canupdate_descr) {
         // Only change during creation OR when allowed to change priority OR when user is the creator
         $idurgency = self::dropdownUrgency("urgency", $this->fields["urgency"]);
     } else {
         $idurgency = "value_urgency" . mt_rand();
         echo "<input id='{$idurgency}' type='hidden' name='urgency' value='" . $this->fields["urgency"] . "'>";
         echo self::getUrgencyName($this->fields["urgency"]);
     }
     echo "</td>";
     echo "<th>" . $LANG['common'][36] . "&nbsp;: </th>";
     echo "<td >";
     // Permit to set category when creating ticket without update right
     if ($canupdate || !$ID || $canupdate_descr) {
         $opt = array('value' => $this->fields["ticketcategories_id"], 'entity' => $this->fields["entities_id"]);
         if ($_SESSION["glpiactiveprofile"]["interface"] == "helpdesk") {
             $opt['condition'] = '`is_helpdeskvisible`=1';
         }
         if ($ID && $CFG_GLPI["is_ticket_category_mandatory"]) {
             $opt['display_emptychoice'] = false;
         }
         Dropdown::show('TicketCategory', $opt);
     } else {
         echo Dropdown::getDropdownName("glpi_ticketcategories", $this->fields["ticketcategories_id"]);
     }
     echo "</td>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<th>" . $LANG['joblist'][30] . "&nbsp;: </th>";
     echo "<td>";
     if ($canupdate) {
         $idimpact = self::dropdownImpact("impact", $this->fields["impact"]);
     } else {
         echo self::getImpactName($this->fields["impact"]);
     }
     echo "</td>";
     echo "<th class='left' rowspan='2'>" . $LANG['document'][14] . "&nbsp;: </th>";
     echo "<td rowspan='2'>";
     // Select hardware on creation or if have update right
     if ($canupdate || !$ID || $canupdate_descr) {
         if ($ID) {
             if ($this->fields['itemtype'] && class_exists($this->fields['itemtype']) && $this->fields["items_id"]) {
                 $item = new $this->fields['itemtype']();
                 if ($item->can($this->fields["items_id"], 'r')) {
                     echo $item->getTypeName() . " - " . $item->getLink(true);
                 } else {
                     echo $item->getTypeName() . " " . $item->getNameID();
                 }
             }
         }
         $dev_user_id = 0;
         if (!$ID) {
             $dev_user_id = $options['_users_id_requester'];
         } else {
             if (isset($this->users[self::REQUESTER]) && count($this->users[self::REQUESTER]) == 1) {
                 foreach ($this->users[self::REQUESTER] as $user_id_single) {
                     $dev_user_id = $user_id_single['users_id'];
                 }
             }
         }
         if ($dev_user_id > 0) {
             self::dropdownMyDevices($dev_user_id, $this->fields["entities_id"], $this->fields["itemtype"], $this->fields["items_id"]);
         }
         self::dropdownAllDevices("itemtype", $this->fields["itemtype"], $this->fields["items_id"], 1, $this->fields["entities_id"]);
     } else {
         if ($ID && $this->fields['itemtype'] && class_exists($this->fields['itemtype'])) {
             $item = new $this->fields['itemtype']();
             $item->getFromDB($this->fields['items_id']);
             echo $item->getTypeName() . " - " . $item->getNameID();
         } else {
             echo $LANG['help'][30];
         }
     }
     echo "</td>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<th class='left'>" . $LANG['joblist'][2] . "&nbsp;: </th>";
     echo "<td>";
     if ($canupdate && $canpriority) {
         $idpriority = self::dropdownPriority("priority", $this->fields["priority"], false, true);
         $idajax = 'change_priority_' . mt_rand();
         echo "&nbsp;<span id='{$idajax}' style='display:none'></span>";
     } else {
         $idajax = 'change_priority_' . mt_rand();
         $idpriority = 0;
         echo "<span id='{$idajax}'>" . self::getPriorityName($this->fields["priority"]) . "</span>";
     }
     if ($canupdate) {
         $params = array('urgency' => '__VALUE0__', 'impact' => '__VALUE1__', 'priority' => $idpriority);
         ajaxUpdateItemOnSelectEvent(array($idurgency, $idimpact), $idajax, $CFG_GLPI["root_doc"] . "/ajax/priority.php", $params);
     }
     echo "</td>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<th class='left'>" . $LANG['job'][44] . "&nbsp;: </th>";
     echo "<td>";
     if ($canupdate) {
         Dropdown::show('RequestType', array('value' => $this->fields["requesttypes_id"]));
     } else {
         echo Dropdown::getDropdownName('glpi_requesttypes', $this->fields["requesttypes_id"]);
     }
     echo "</td>";
     // Display validation state
     echo "<th>";
     if (!$ID) {
         echo $LANG['validation'][26] . "&nbsp;:&nbsp;";
     } else {
         echo $LANG['validation'][0] . "&nbsp;:&nbsp;";
     }
     echo "</th>";
     echo "<td>";
     if (!$ID) {
         User::dropdown(array('name' => "_add_validation", 'entity' => $this->fields['entities_id'], 'right' => 'validate_ticket'));
     } else {
         if ($canupdate) {
             TicketValidation::dropdownStatus('global_validation', array('global' => true, 'value' => $this->fields['global_validation']));
         } else {
             echo TicketValidation::getStatus($this->fields['global_validation']);
         }
     }
     echo "</td></tr>";
     // Need comment right to add a followup with the actiontime
     if (!$ID && haveRight("global_add_followups", "1")) {
         echo "<tr class='tab_bg_1'>";
         echo "<th>" . $LANG['job'][20] . "&nbsp;: </th>";
         echo "<td class='left' colspan='3'>";
         Dropdown::showInteger('hour', $options['hour'], 0, 100);
         echo "&nbsp;" . $LANG['job'][21] . "&nbsp;&nbsp;";
         Dropdown::showInteger('minute', $options['minute'], 0, 59);
         echo "&nbsp;" . $LANG['job'][22] . "&nbsp;&nbsp;";
         echo "</td>";
         echo "</tr>";
     }
     echo '</table>';
     if ($ID) {
         $this->showActorsPartForm($ID, $options);
     }
     echo "<table  class='tab_cadre_fixe'>";
     $view_linked_tickets = $ID || $canupdate;
     echo "<tr class='tab_bg_1'>";
     echo "<th width='10%'>" . $LANG['common'][57] . "&nbsp;:</th>";
     echo "<td width='50%'>";
     if (!$ID || $canupdate_descr) {
         $rand = mt_rand();
         echo "<script type='text/javascript' >\n";
         echo "function showName{$rand}() {\n";
         echo "Ext.get('name{$rand}').setDisplayed('none');";
         $params = array('maxlength' => 250, 'size' => 60, 'name' => 'name', 'data' => rawurlencode($this->fields["name"]));
         ajaxUpdateItemJsCode("viewname{$rand}", $CFG_GLPI["root_doc"] . "/ajax/inputtext.php", $params, false);
         echo "}";
         echo "</script>\n";
         echo "<div id='name{$rand}' class='tracking left' onClick='showName{$rand}()'>\n";
         if (empty($this->fields["name"])) {
             echo $LANG['reminder'][15];
         } else {
             echo $this->fields["name"];
         }
         echo "</div>\n";
         echo "<div id='viewname{$rand}'>\n";
         echo "</div>\n";
         if (!$ID) {
             echo "<script type='text/javascript' >\n\n            showName{$rand}();\n            </script>";
         }
     } else {
         if (empty($this->fields["name"])) {
             echo $LANG['reminder'][15];
         } else {
             echo $this->fields["name"];
         }
     }
     echo "</td>";
     // Permit to add doc when creating a ticket
     if (!$ID) {
         echo "<th>" . $LANG['document'][2] . " (" . Document::getMaxUploadSize() . ")&nbsp;:";
         echo "<img src='" . $CFG_GLPI["root_doc"] . "/pics/aide.png' class='pointer' alt=\"" . $LANG['central'][7] . "\" onclick=\"window.open('" . $CFG_GLPI["root_doc"] . "/front/documenttype.list.php','Help','scrollbars=1,resizable=1,width=1000,height=800')\">";
         echo "</th>";
         echo "<td>";
         echo "<input type='file' name='filename' value=\"\" size='25'></td>";
     } else {
         echo "<th colspan='2'>";
         echo $LANG['document'][20] . '&nbsp;: ' . Document_Item::countForItem($this);
         echo "</th>";
     }
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<th width='10%'>" . $LANG['joblist'][6] . "&nbsp;:&nbsp;</th>";
     echo "<td width='50%'>";
     if (!$ID || $canupdate_descr) {
         // Admin =oui on autorise la modification de la description
         $rand = mt_rand();
         echo "<script type='text/javascript' >\n";
         echo "function showDesc{$rand}() {\n";
         echo "Ext.get('desc{$rand}').setDisplayed('none');";
         $params = array('rows' => 6, 'cols' => 60, 'name' => 'content', 'data' => rawurlencode($this->fields["content"]));
         ajaxUpdateItemJsCode("viewdesc{$rand}", $CFG_GLPI["root_doc"] . "/ajax/textarea.php", $params, false);
         echo "}";
         echo "</script>\n";
         echo "<div id='desc{$rand}' class='tracking' onClick='showDesc{$rand}()'>\n";
         if (!empty($this->fields["content"])) {
             echo nl2br($this->fields["content"]);
         } else {
             echo $LANG['job'][33];
         }
         echo "</div>\n";
         echo "<div id='viewdesc{$rand}'></div>\n";
         if (!$ID) {
             echo "<script type='text/javascript' >\n\n            showDesc{$rand}();\n            </script>";
         }
     } else {
         echo nl2br($this->fields["content"]);
     }
     echo "</td>";
     if ($view_linked_tickets) {
         echo "<th width='10%'>";
         echo $LANG['job'][55];
         if ($canupdate) {
             $rand_linked_ticket = mt_rand();
             echo "&nbsp;&nbsp;<a class='tracking'\n                  onClick=\"Ext.get('linkedticket{$rand_linked_ticket}').setDisplayed('block')\">\n";
             echo $LANG['buttons'][8];
             echo "</a>\n";
         }
         echo '</th>';
         echo "<td>";
         Ticket_Ticket::displayLinkedTicketsTo($ID);
         if ($canupdate) {
             echo "<div style='display:none' id='linkedticket{$rand_linked_ticket}'>";
             Ticket_Ticket::dropdownLinks('_link[link]');
             echo "&nbsp;" . $LANG['job'][38] . "&nbsp;" . $LANG['common'][2] . "&nbsp;:&nbsp;";
             echo "<input type='hidden' name='_link[tickets_id_1]' value='{$ID}'>\n";
             echo "<input type='text' name='_link[tickets_id_2]' value='' size='10'>\n";
             echo "&nbsp;";
             echo "</div>";
         }
         echo "</td>";
     }
     echo "</tr>";
     if (!$ID || $canupdate || $canupdate_descr || haveRight("assign_ticket", "1") || haveRight("steal_ticket", "1")) {
         echo "<tr class='tab_bg_1'>";
         if ($ID) {
             if (haveRight('delete_ticket', 1)) {
                 echo "<td class='tab_bg_2 center' colspan='2'>";
                 echo "<input type='submit' class='submit' name='update' value='" . $LANG['buttons'][7] . "'></td>";
                 echo "<td class='tab_bg_2 center' colspan='2'>";
                 echo "<input type='submit' class='submit' name='delete' value='" . $LANG['buttons'][22] . "'" . addConfirmationOnAction($LANG['common'][50]) . ">";
             } else {
                 echo "<td class='tab_bg_2 center' colspan='4'>";
                 echo "<input type='submit' class='submit' name='update' value='" . $LANG['buttons'][7] . "'>";
             }
         } else {
             echo "<td class='tab_bg_2 center' colspan='2'>";
             echo "<input type='submit' name='add' value=\"" . $LANG['buttons'][8] . "\" class='submit'>";
             echo "</td><td class='tab_bg_2 center' colspan='2'>";
             echo "<input type='button' value=\"" . $LANG['buttons'][16] . "\" class='submit'\n                   onclick=\"window.location='" . $CFG_GLPI["root_doc"] . "/front/ticket.form.php'\">";
         }
         echo "</td></tr>";
     }
     echo "</table>";
     echo "<input type='hidden' name='id' value='{$ID}'>";
     echo "</div>";
     echo "</form>";
     $this->addDivForTabs();
     return true;
 }
 /**
  * @see NotificationTargetCommonITILObject::getDatasForObject()
  **/
 function getDatasForObject(CommonDBTM $item, array $options, $simple = false)
 {
     global $CFG_GLPI;
     // Common ITIL datas
     $datas = parent::getDatasForObject($item, $options, $simple);
     $datas['##ticket.description##'] = Html::clean($datas['##ticket.description##']);
     $datas['##ticket.description##'] = $item->convertContentForNotification($datas['##ticket.description##'], $item);
     $datas['##ticket.content##'] = $datas['##ticket.description##'];
     // Specific datas
     $datas['##ticket.urlvalidation##'] = $this->formatURL($options['additionnaloption']['usertype'], "ticket_" . $item->getField("id") . "_TicketValidation\$1");
     $datas['##ticket.globalvalidation##'] = TicketValidation::getStatus($item->getField('global_validation'));
     $datas['##ticket.type##'] = Ticket::getTicketTypeName($item->getField('type'));
     $datas['##ticket.requesttype##'] = Dropdown::getDropdownName('glpi_requesttypes', $item->getField('requesttypes_id'));
     $autoclose_value = Entity::getUsedConfig('autoclose_delay', $this->getEntity(), '', Entity::CONFIG_NEVER);
     $datas['##ticket.autoclose##'] = __('Never');
     $datas['##lang.ticket.autoclosewarning##'] = "";
     if ($autoclose_value > 0) {
         $datas['##ticket.autoclose##'] = $autoclose_value;
         $datas['##lang.ticket.autoclosewarning##'] = sprintf(_n('Without a reply, the ticket will be automatically closed after %s day', 'Without a reply, the ticket will be automatically closed after %s days', $autoclose_value), $autoclose_value);
     }
     $datas['##ticket.sla##'] = '';
     if ($item->getField('slas_id')) {
         $datas['##ticket.sla##'] = Dropdown::getDropdownName('glpi_slas', $item->getField('slas_id'));
     }
     $datas['##ticket.location##'] = '';
     if ($item->getField('locations_id')) {
         $datas['##ticket.location##'] = Dropdown::getDropdownName('glpi_locations', $item->getField('locations_id'));
     }
     // is ticket deleted
     $datas['##ticket.isdeleted##'] = Dropdown::getYesNo($item->getField('is_deleted'));
     //Tags associated with the object linked to the ticket
     $datas['##ticket.itemtype##'] = '';
     $datas['##ticket.item.name##'] = '';
     $datas['##ticket.item.serial##'] = '';
     $datas['##ticket.item.otherserial##'] = '';
     $datas['##ticket.item.location##'] = '';
     $datas['##ticket.item.contact##'] = '';
     $datas['##ticket.item.contactnumber##'] = '';
     $datas['##ticket.item.user##'] = '';
     $datas['##ticket.item.group##'] = '';
     $datas['##ticket.item.model##'] = '';
     $item_ticket = new Item_Ticket();
     $items = $item_ticket->find("`tickets_id` = '" . $item->getField('id') . "'");
     $datas['items'] = array();
     if (count($items)) {
         foreach ($items as $val) {
             if (isset($val['itemtype']) && ($hardware = getItemForItemtype($val['itemtype'])) && isset($val["items_id"]) && $hardware->getFromDB($val["items_id"])) {
                 $tmp = array();
                 //Object type
                 $tmp['##ticket.itemtype##'] = $hardware->getTypeName();
                 //Object name
                 $tmp['##ticket.item.name##'] = $hardware->getField('name');
                 //Object serial
                 if ($hardware->isField('serial')) {
                     $tmp['##ticket.item.serial##'] = $hardware->getField('serial');
                 }
                 //Object contact
                 if ($hardware->isField('contact')) {
                     $tmp['##ticket.item.contact##'] = $hardware->getField('contact');
                 }
                 //Object contact num
                 if ($hardware->isField('contact_num')) {
                     $tmp['##ticket.item.contactnumber##'] = $hardware->getField('contact_num');
                 }
                 //Object otherserial
                 if ($hardware->isField('otherserial')) {
                     $tmp['##ticket.item.otherserial##'] = $hardware->getField('otherserial');
                 }
                 //Object location
                 if ($hardware->isField('locations_id')) {
                     $tmp['##ticket.item.location##'] = Dropdown::getDropdownName('glpi_locations', $hardware->getField('locations_id'));
                 }
                 //Object user
                 if ($hardware->getField('users_id')) {
                     $user_tmp = new User();
                     if ($user_tmp->getFromDB($hardware->getField('users_id'))) {
                         $tmp['##ticket.item.user##'] = $user_tmp->getName();
                     }
                 }
                 //Object group
                 if ($hardware->getField('groups_id')) {
                     $tmp['##ticket.item.group##'] = Dropdown::getDropdownName('glpi_groups', $hardware->getField('groups_id'));
                 }
                 $modeltable = getSingular($hardware->getTable()) . "models";
                 $modelfield = getForeignKeyFieldForTable($modeltable);
                 if ($hardware->isField($modelfield)) {
                     $tmp['##ticket.item.model##'] = Dropdown::getDropdownName($modeltable, $hardware->getField($modelfield));
                 }
                 $datas['items'][] = $tmp;
             }
         }
     }
     $datas['##ticket.numberofitems##'] = count($datas['items']);
     // Get followups, log, validation, satisfaction, linked tickets
     if (!$simple) {
         // Linked tickets
         $linked_tickets = Ticket_Ticket::getLinkedTicketsTo($item->getField('id'));
         $datas['linkedtickets'] = array();
         if (count($linked_tickets)) {
             $linkedticket = new Ticket();
             foreach ($linked_tickets as $data) {
                 if ($linkedticket->getFromDB($data['tickets_id'])) {
                     $tmp = array();
                     $tmp['##linkedticket.id##'] = $data['tickets_id'];
                     $tmp['##linkedticket.link##'] = Ticket_Ticket::getLinkName($data['link']);
                     $tmp['##linkedticket.url##'] = $this->formatURL($options['additionnaloption']['usertype'], "ticket_" . $data['tickets_id']);
                     $tmp['##linkedticket.title##'] = $linkedticket->getField('name');
                     $tmp['##linkedticket.content##'] = $linkedticket->getField('content');
                     $datas['linkedtickets'][] = $tmp;
                 }
             }
         }
         $datas['##ticket.numberoflinkedtickets##'] = count($datas['linkedtickets']);
         $restrict = "`tickets_id`='" . $item->getField('id') . "'";
         $problems = getAllDatasFromTable('glpi_problems_tickets', $restrict);
         $datas['problems'] = array();
         if (count($problems)) {
             $problem = new Problem();
             foreach ($problems as $data) {
                 if ($problem->getFromDB($data['problems_id'])) {
                     $tmp = array();
                     $tmp['##problem.id##'] = $data['problems_id'];
                     $tmp['##problem.date##'] = $problem->getField('date');
                     $tmp['##problem.title##'] = $problem->getField('name');
                     $tmp['##problem.url##'] = $this->formatURL($options['additionnaloption']['usertype'], "problem_" . $data['problems_id']);
                     $tmp['##problem.content##'] = $problem->getField('content');
                     $datas['problems'][] = $tmp;
                 }
             }
         }
         $datas['##ticket.numberofproblems##'] = count($datas['problems']);
         $restrict = "`tickets_id`='" . $item->getField('id') . "'";
         $changes = getAllDatasFromTable('glpi_changes_tickets', $restrict);
         $datas['changes'] = array();
         if (count($changes)) {
             $change = new Change();
             foreach ($changes as $data) {
                 if ($change->getFromDB($data['changes_id'])) {
                     $tmp = array();
                     $tmp['##change.id##'] = $data['changes_id'];
                     $tmp['##change.date##'] = $change->getField('date');
                     $tmp['##change.title##'] = $change->getField('name');
                     $tmp['##change.url##'] = $this->formatURL($options['additionnaloption']['usertype'], "change_" . $data['changes_id']);
                     $tmp['##change.content##'] = $change->getField('content');
                     $datas['changes'][] = $tmp;
                 }
             }
         }
         $datas['##ticket.numberofchanges##'] = count($datas['changes']);
         if (!isset($options['additionnaloption']['show_private']) || !$options['additionnaloption']['show_private']) {
             $restrict .= " AND `is_private` = '0'";
         }
         $restrict .= " ORDER BY `date` DESC, `id` ASC";
         //Followup infos
         $followups = getAllDatasFromTable('glpi_ticketfollowups', $restrict);
         $datas['followups'] = array();
         foreach ($followups as $followup) {
             $tmp = array();
             $tmp['##followup.isprivate##'] = Dropdown::getYesNo($followup['is_private']);
             $tmp['##followup.author##'] = Html::clean(getUserName($followup['users_id']));
             $tmp['##followup.requesttype##'] = Dropdown::getDropdownName('glpi_requesttypes', $followup['requesttypes_id']);
             $tmp['##followup.date##'] = Html::convDateTime($followup['date']);
             $tmp['##followup.description##'] = $followup['content'];
             $datas['followups'][] = $tmp;
         }
         $datas['##ticket.numberoffollowups##'] = count($datas['followups']);
         // Approbation of solution
         $restrict .= " LIMIT 1";
         $replysolved = getAllDatasFromTable('glpi_ticketfollowups', $restrict);
         $data = current($replysolved);
         $datas['##ticket.solution.approval.description##'] = $data['content'];
         $datas['##ticket.solution.approval.date##'] = Html::convDateTime($data['date']);
         $datas['##ticket.solution.approval.author##'] = Html::clean(getUserName($data['users_id']));
         //Validation infos
         $restrict = "`tickets_id`='" . $item->getField('id') . "'";
         if (isset($options['validation_id']) && $options['validation_id']) {
             $restrict .= " AND `glpi_ticketvalidations`.`id` = '" . $options['validation_id'] . "'";
         }
         $restrict .= " ORDER BY `submission_date` DESC, `id` ASC";
         $validations = getAllDatasFromTable('glpi_ticketvalidations', $restrict);
         $datas['validations'] = array();
         foreach ($validations as $validation) {
             $tmp = array();
             $tmp['##validation.submission.title##'] = sprintf(__('An approval request has been submitted by %s'), Html::clean(getUserName($validation['users_id'])));
             $tmp['##validation.answer.title##'] = sprintf(__('An answer to an an approval request was produced by %s'), Html::clean(getUserName($validation['users_id_validate'])));
             $tmp['##validation.author##'] = Html::clean(getUserName($validation['users_id']));
             $tmp['##validation.status##'] = TicketValidation::getStatus($validation['status']);
             $tmp['##validation.storestatus##'] = $validation['status'];
             $tmp['##validation.submissiondate##'] = Html::convDateTime($validation['submission_date']);
             $tmp['##validation.commentsubmission##'] = $validation['comment_submission'];
             $tmp['##validation.validationdate##'] = Html::convDateTime($validation['validation_date']);
             $tmp['##validation.validator##'] = Html::clean(getUserName($validation['users_id_validate']));
             $tmp['##validation.commentvalidation##'] = $validation['comment_validation'];
             $datas['validations'][] = $tmp;
         }
         // Ticket Satisfaction
         $inquest = new TicketSatisfaction();
         $datas['##satisfaction.type##'] = '';
         $datas['##satisfaction.datebegin##'] = '';
         $datas['##satisfaction.dateanswered##'] = '';
         $datas['##satisfaction.satisfaction##'] = '';
         $datas['##satisfaction.description##'] = '';
         if ($inquest->getFromDB($item->getField('id'))) {
             // internal inquest
             if ($inquest->fields['type'] == 1) {
                 $datas['##ticket.urlsatisfaction##'] = $this->formatURL($options['additionnaloption']['usertype'], "ticket_" . $item->getField("id") . '_Ticket$3');
                 // external inquest
             } else {
                 if ($inquest->fields['type'] == 2) {
                     $datas['##ticket.urlsatisfaction##'] = Entity::generateLinkSatisfaction($item);
                 }
             }
             $datas['##satisfaction.type##'] = $inquest->getTypeInquestName($inquest->getfield('type'));
             $datas['##satisfaction.datebegin##'] = Html::convDateTime($inquest->fields['date_begin']);
             $datas['##satisfaction.dateanswered##'] = Html::convDateTime($inquest->fields['date_answered']);
             $datas['##satisfaction.satisfaction##'] = $inquest->fields['satisfaction'];
             $datas['##satisfaction.description##'] = $inquest->fields['comment'];
         }
     }
     return $datas;
 }
 /**
  * Get a ticket information, with its followup
  * for an authenticated user
  *
  * @param $params    array of options (ticket, id2name)
  * @param $protocol        the communication protocol used
  *
  * @return array of hashtable
  **/
 static function methodGetTicket($params, $protocol)
 {
     global $DB, $CFG_GLPI;
     if (isset($params['help'])) {
         return array('ticket' => 'integer,mandatory', 'id2name' => 'bool,optional', 'help' => 'bool,optional');
     }
     if (!Session::getLoginUserID()) {
         return self::Error($protocol, WEBSERVICES_ERROR_NOTAUTHENTICATED);
     }
     $ticket = new Ticket();
     if (!isset($params['ticket'])) {
         return self::Error($protocol, WEBSERVICES_ERROR_MISSINGPARAMETER, '', 'ticket');
     }
     if (!is_numeric($params['ticket'])) {
         return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', 'ticket=' . $params['ticket']);
     }
     if (!$ticket->can($params['ticket'], 'r')) {
         return self::Error($protocol, WEBSERVICES_ERROR_NOTFOUND);
     }
     $resp = $ticket->fields;
     if ($resp['itemtype']) {
         $item = getItemForItemtype($resp['itemtype']);
     } else {
         $item = false;
     }
     $resp['solution'] = Html::clean(Toolbox::unclean_cross_side_scripting_deep($resp['solution']));
     $nextaction = new SlaLevel_Ticket();
     if ($ticket->fields['slas_id'] && $nextaction->getFromDBForTicket($ticket->fields['id'])) {
         $resp['slalevels_next_id'] = $nextaction->fields['slalevels_id'];
         $resp['slalevels_next_date'] = $nextaction->fields['date'];
     } else {
         $resp['slalevels_next_id'] = 0;
         $resp['slalevels_next_date'] = '';
     }
     if (isset($params['id2name'])) {
         $resp['users_name_recipient'] = Html::clean(getUserName($ticket->fields['users_id_recipient']));
         $resp['users_name_lastupdater'] = Html::clean(getUserName($ticket->fields['users_id_lastupdater']));
         $resp['ticketcategories_name'] = Html::clean(Dropdown::getDropdownName('glpi_itilcategories', $ticket->fields['itilcategories_id']));
         $resp['entities_name'] = Html::clean(Dropdown::getDropdownName('glpi_entities', $resp['entities_id']));
         $resp['status_name'] = Html::clean($ticket->getStatus($resp['status']));
         $resp['requesttypes_name'] = Html::clean(Dropdown::getDropdownName('glpi_requesttypes', $resp['requesttypes_id']));
         $resp['solutiontypes_name'] = Html::clean(Dropdown::getDropdownName('glpi_solutiontypes', $resp['solutiontypes_id']));
         $resp['slas_name'] = Html::clean(Dropdown::getDropdownName('glpi_slas', $resp['slas_id']));
         $resp['slalevels_name'] = Html::clean(Dropdown::getDropdownName('glpi_slalevels', $resp['slalevels_id']));
         $resp['slalevels_next_name'] = Html::clean(Dropdown::getDropdownName('glpi_slalevels', $resp['slalevels_next_id']));
         $resp['urgency_name'] = Ticket::getUrgencyName($resp['urgency']);
         $resp['impact_name'] = Ticket::getImpactName($resp['impact']);
         $resp['priority_name'] = Ticket::getPriorityName($resp['priority']);
         $resp['type_name'] = Ticket::getTicketTypeName($resp['type']);
         $resp['global_validation_name'] = TicketValidation::getStatus($resp['global_validation']);
         $resp['locations_name'] = Html::clean(Dropdown::getDropdownName('glpi_locations', $resp['locations_id']));
         if ($item && $item->getFromDB($resp['items_id'])) {
             $resp['items_name'] = Html::clean($item->getNameID());
             $resp['itemtype_name'] = Html::clean($item->getTypeName());
         } else {
             $resp['items_name'] = __('General');
             $resp['itemtype_name'] = '';
         }
     }
     $resp['users'] = array();
     $resp['groups'] = array();
     $resp['followups'] = array();
     $resp['tasks'] = array();
     $resp['documents'] = array();
     $resp['events'] = array();
     $resp['validations'] = array();
     $resp['satisfaction'] = array();
     if (Session::haveRight('observe_ticket', '1')) {
         // Followups
         $query = "SELECT *\n                   FROM `glpi_ticketfollowups`\n                   WHERE `tickets_id` = '" . $params['ticket'] . "' ";
         if (!Session::haveRight("show_full_ticket", "1")) {
             $query .= " AND (`is_private`='0'\n                             OR `users_id` ='" . Session::getLoginUserID() . "' ) ";
         }
         $query .= " ORDER BY `date` DESC";
         foreach ($DB->request($query) as $data) {
             if (isset($params['id2name'])) {
                 $data['users_name'] = Html::clean(getUserName($data['users_id']));
                 $data['requesttypes_name'] = Html::clean(Dropdown::getDropdownName('glpi_requesttypes', $data['requesttypes_id']));
             }
             $resp['followups'][] = $data;
         }
         // Tasks
         $query = "SELECT *\n                   FROM `glpi_tickettasks`\n                   WHERE `tickets_id` = '" . $params['ticket'] . "' ";
         if (!Session::haveRight("show_full_ticket", "1")) {
             $query .= " AND (`is_private`='0'\n                             OR `users_id` ='" . Session::getLoginUserID() . "' ) ";
         }
         $query .= " ORDER BY `date` DESC";
         foreach ($DB->request($query) as $data) {
             if (isset($params['id2name'])) {
                 $data['users_name'] = Html::clean(getUserName($data['users_id']));
                 $data['taskcategories_name'] = Html::clean(Dropdown::getDropdownName('glpi_taskcategories', $data['taskcategories_id']));
             }
             $resp['tasks'][] = $data;
         }
         // Documents
         $resp['documents'] = PluginWebservicesMethodTools::getDocForItem($ticket, isset($params['id2name']));
         // History
         $resp['events'] = Log::getHistoryData($ticket, 0, $_SESSION['glpilist_limit']);
         foreach ($resp['events'] as $key => $val) {
             $resp['events'][$key]['change'] = Html::clean($resp['events'][$key]['change']);
         }
     }
     if (Session::haveRight('create_request_validation', 1) || Session::haveRight('create_incident_validation', 1) || Session::haveRight('validate_request', 1) || Session::haveRight('validate_incident', 1)) {
         $query = "SELECT *\n                   FROM `glpi_ticketvalidations`\n                   WHERE `tickets_id` = '" . $params['ticket'] . "' ";
         foreach ($DB->request($query) as $data) {
             if (isset($params['id2name'])) {
                 $data['users_name'] = Html::clean(getUserName($data['users_id']));
                 $data['users_name_validate'] = Html::clean(getUserName($data['users_id_validate']));
                 $data['status_name'] = TicketValidation::getStatus($data['status']);
             }
             $resp['validations'][] = $data;
         }
     }
     // Users & Groups
     $tabtmp = array(CommonITILActor::REQUESTER => 'requester', CommonITILActor::OBSERVER => 'observer', CommonITILActor::ASSIGN => 'assign');
     foreach ($tabtmp as $num => $name) {
         $resp['users'][$name] = array();
         foreach ($ticket->getUsers($num) as $user) {
             if (isset($params['id2name'])) {
                 if ($user['users_id']) {
                     $user['users_name'] = Html::clean(getUserName($user['users_id']));
                 } else {
                     $user['users_name'] = $user['alternative_email'];
                 }
             }
             unset($user['tickets_id']);
             unset($user['type']);
             $resp['users'][$name][] = $user;
         }
         $resp['groups'][$name] = array();
         foreach ($ticket->getGroups($num) as $group) {
             if (isset($params['id2name'])) {
                 $group['groups_name'] = Html::clean(Dropdown::getDropdownName('glpi_groups', $group['groups_id']));
             }
             unset($group['tickets_id']);
             unset($group['type']);
             $resp['groups'][$name][] = $group;
         }
     }
     // Suppliers
     $resp['suppliers']['assign'] = array();
     foreach ($ticket->getSuppliers(CommonITILActor::ASSIGN) as $supplier) {
         if (isset($params['id2name'])) {
             $supplier['suppliers_name'] = Html::clean(Dropdown::getDropdownName('glpi_suppliers', $supplier['suppliers_id']));
         }
         unset($supplier['tickets_id']);
         unset($supplier['type']);
         $resp['suppliers'][$name][] = $supplier;
     }
     // Satisfaction
     $satisfaction = new TicketSatisfaction();
     if ($satisfaction->getFromDB($params['ticket'])) {
         $resp['satisfaction'] = $satisfaction->fields;
     }
     return $resp;
 }
示例#6
0
 /**
  * Generic Function to display Items
  *
  * @param $itemtype              item type
  * @param $ID                    ID of the SEARCH_OPTION item
  * @param $data            array containing data results
  * @param $num                   item num in the request
  * @param $meta                  is a meta item ? (default 0)
  * @param $addobjectparams array added parameters for union search
  *
  * @return string to print
  **/
 static function giveItem($itemtype, $ID, array $data, $num, $meta = 0, array $addobjectparams = array())
 {
     global $CFG_GLPI;
     $showuserlink = 0;
     if (Session::haveRight('user', READ)) {
         $showuserlink = 1;
     }
     $searchopt =& self::getOptions($itemtype);
     if (isset($CFG_GLPI["union_search_type"][$itemtype]) && $CFG_GLPI["union_search_type"][$itemtype] == $searchopt[$ID]["table"]) {
         if (isset($searchopt[$ID]['addobjectparams']) && $searchopt[$ID]['addobjectparams']) {
             return self::giveItem($data["TYPE"], $ID, $data, $num, $meta, $searchopt[$ID]['addobjectparams']);
         }
         return self::giveItem($data["TYPE"], $ID, $data, $num, $meta);
     }
     if (count($addobjectparams)) {
         $searchopt[$ID] = array_merge($searchopt[$ID], $addobjectparams);
     }
     // Plugin can override core definition for its type
     if ($plug = isPluginItemType($itemtype)) {
         $function = 'plugin_' . $plug['plugin'] . '_giveItem';
         if (function_exists($function)) {
             $out = $function($itemtype, $ID, $data, $num);
             if (!empty($out)) {
                 return $out;
             }
         }
     }
     $NAME = "ITEM_";
     if ($meta) {
         $NAME = "META_";
     }
     $table = $searchopt[$ID]["table"];
     $field = $searchopt[$ID]["field"];
     $linkfield = $searchopt[$ID]["linkfield"];
     /// TODO try to clean all specific cases using SpecificToDisplay
     switch ($table . '.' . $field) {
         case "glpi_users.name":
             // USER search case
             if ($itemtype != 'User' && isset($searchopt[$ID]["forcegroupby"]) && $searchopt[$ID]["forcegroupby"]) {
                 $out = "";
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $count_display = 0;
                 $added = array();
                 for ($k = 0; $k < count($split); $k++) {
                     if ($split[$k] > 0) {
                         if ($count_display) {
                             $out .= "<br>";
                         }
                         $count_display++;
                         if ($itemtype == 'Ticket') {
                             $userdata = getUserName($split[$k], 2);
                             $tooltip = "";
                             if (Session::haveRight('user', READ)) {
                                 $tooltip = Html::showToolTip($userdata["comment"], array('link' => $userdata["link"], 'display' => false));
                             }
                             $out .= sprintf(__('%1$s %2$s'), $userdata['name'], $tooltip);
                         } else {
                             $out .= getUserName($split[$k], $showuserlink);
                         }
                     }
                 }
                 // Manage alternative_email for tickets_users
                 if ($itemtype == 'Ticket' && isset($data[$NAME . $num . '_2'])) {
                     $split = explode("\$\$\$\$", $data[$NAME . $num . '_2']);
                     for ($k = 0; $k < count($split); $k++) {
                         $split2 = explode(" ", $split[$k]);
                         if (count($split2) == 2 && $split2[0] == 0 && !empty($split2[1])) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= "<a href='mailto:" . $split2[1] . "'>" . $split2[1] . "</a>";
                         }
                     }
                 }
                 return $out;
             }
             if ($itemtype != 'User') {
                 $toadd = '';
                 if ($itemtype == 'Ticket' && $data[$NAME . $num . "_3"] > 0) {
                     $userdata = getUserName($data[$NAME . $num . "_3"], 2);
                     $toadd = Html::showToolTip($userdata["comment"], array('link' => $userdata["link"], 'display' => false));
                 }
                 if (Session::haveRight('user', READ)) {
                     $usernameformat = formatUserName($data[$NAME . $num . "_3"], $data[$NAME . $num], $data[$NAME . $num . "_2"], $data[$NAME . $num . "_4"], 1);
                 } else {
                     $usernameformat = formatUserName($data[$NAME . $num . "_3"], $data[$NAME . $num], $data[$NAME . $num . "_2"], $data[$NAME . $num . "_4"], 0);
                 }
                 return sprintf(__('%1$s %2$s'), $usernameformat, $toadd);
             }
             break;
         case "glpi_profiles.interface":
             return Profile::getInterfaceName($data[$NAME . $num]);
         case "glpi_profiles.name":
             if ($itemtype == 'User' && $ID == 20) {
                 $out = "";
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $split2 = explode("\$\$\$\$", $data[$NAME . $num . "_2"]);
                 $split3 = explode("\$\$\$\$", $data[$NAME . $num . "_3"]);
                 $split4 = explode("\$\$\$\$", $data[$NAME . $num . "_4"]);
                 $count_display = 0;
                 $added = array();
                 for ($k = 0; $k < count($split); $k++) {
                     if (strlen(trim($split[$k])) > 0) {
                         $text = sprintf(__('%1$s - %2$s'), $split[$k], Dropdown::getDropdownName('glpi_entities', $split2[$k]));
                         $comp = '';
                         if ($split3[$k]) {
                             $comp = __(READ);
                             if ($split4[$k]) {
                                 $comp = sprintf(__('%1$s%2$s'), $comp, ", ");
                             }
                         }
                         if ($split4[$k]) {
                             $comp = sprintf(__('%1$s%2$s'), $comp, __('D'));
                         }
                         if (!empty($comp)) {
                             $text = sprintf(__('%1$s %2$s'), $text, "(" . $comp . ")");
                         }
                         if (!in_array($text, $added)) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= $text;
                             $added[] = $text;
                         }
                     }
                 }
                 return $out;
             }
             break;
         case "glpi_entities.completename":
             if ($itemtype == 'User') {
                 $out = "";
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $split2 = explode("\$\$\$\$", $data[$NAME . $num . "_2"]);
                 $split3 = explode("\$\$\$\$", $data[$NAME . $num . "_3"]);
                 $split4 = explode("\$\$\$\$", $data[$NAME . $num . "_4"]);
                 $added = array();
                 $count_display = 0;
                 for ($k = 0; $k < count($split); $k++) {
                     if (strlen(trim($split[$k])) > 0) {
                         $text = sprintf(__('%1$s - %2$s'), $split[$k], Dropdown::getDropdownName('glpi_profiles', $split2[$k]));
                         $comp = '';
                         if ($split3[$k]) {
                             $comp = __(READ);
                             if ($split4[$k]) {
                                 $comp = sprintf(__('%1$s%2$s'), $comp, ", ");
                             }
                         }
                         if ($split4[$k]) {
                             $comp = sprintf(__('%1$s%2$s'), $comp, __('D'));
                         }
                         if (!empty($comp)) {
                             $text = sprintf(__('%1$s %2$s'), $text, "(" . $comp . ")");
                         }
                         if (!in_array($text, $added)) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= $text;
                             $added[] = $text;
                         }
                     }
                 }
                 return $out;
             }
             break;
         case "glpi_documenttypes.icon":
             if (!empty($data[$NAME . $num])) {
                 return "<img class='middle' alt='' src='" . $CFG_GLPI["typedoc_icon_dir"] . "/" . $data[$NAME . $num] . "'>";
             }
             return "&nbsp;";
         case "glpi_documents.filename":
             $doc = new Document();
             if ($doc->getFromDB($data['id'])) {
                 return $doc->getDownloadLink();
             }
             return NOT_AVAILABLE;
         case "glpi_deviceharddrives.specificity":
         case "glpi_devicememories.specificity":
         case "glpi_deviceprocessors.specificity":
             return $data[$NAME . $num];
         case "glpi_networkports.mac":
             $out = "";
             if ($itemtype == 'Computer') {
                 $displayed = array();
                 if (!empty($data[$NAME . $num . "_2"])) {
                     $split = explode("\$\$\$\$", $data[$NAME . $num . "_2"]);
                     $count_display = 0;
                     for ($k = 0; $k < count($split); $k++) {
                         $lowstr = Toolbox::strtolower($split[$k]);
                         if (strlen(trim($split[$k])) > 0 && !in_array($lowstr, $displayed)) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= $split[$k];
                             $displayed[] = $lowstr;
                         }
                     }
                     if (!empty($data[$NAME . $num])) {
                         $out .= "<br>";
                     }
                 }
                 if (!empty($data[$NAME . $num])) {
                     $split = explode("\$\$\$\$", $data[$NAME . $num]);
                     $count_display = 0;
                     for ($k = 0; $k < count($split); $k++) {
                         $lowstr = Toolbox::strtolower($split[$k]);
                         if (strlen(trim($split[$k])) > 0 && !in_array($lowstr, $displayed)) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= $split[$k];
                             $displayed[] = $lowstr;
                         }
                     }
                 }
                 return $out;
             }
             break;
         case "glpi_contracts.duration":
         case "glpi_contracts.notice":
         case "glpi_contracts.periodicity":
         case "glpi_contracts.billing":
             if (!empty($data[$NAME . $num])) {
                 $split = explode('$$$$', $data[$NAME . $num]);
                 $output = "";
                 foreach ($split as $duration) {
                     $output .= (empty($output) ? '' : '<br>') . sprintf(_n('%d month', '%d months', $duration), $duration);
                 }
                 return $output;
             }
             return "&nbsp;";
         case "glpi_contracts.renewal":
             return Contract::getContractRenewalName($data[$NAME . $num]);
             //          case "glpi_infocoms.sink_time" :
             //             if (!empty($data[$NAME.$num])) {
             //                $split = explode("$$$$", $data[$NAME.$num]);
             //                $out   = '';
             //                foreach ($split as $val) {
             //                   $out .= (empty($out)?'':'<br>');
             //                   if ($val > 0) {
             //                      //TRANS: %d is a number of years
             //                      $out .= sprintf(_n('%d year', '%d years', $val), $val);
             //                   }
             //                }
             //                return $out;
             //             }
             //             return "&nbsp;";
             //
             //          case "glpi_infocoms.warranty_duration" :
             //             if (!empty($data[$NAME.$num])) {
             //                $split = explode("$$$$", $data[$NAME.$num]);
             //                $out   = '';
             //                foreach ($split as $val) {
             //                   $out .= (empty($out)?'':'<br>');
             //                   if ($val > 0) {
             //                      $out .= sprintf(_n('%d month', '%d months', $val), $val);
             //                   }
             //                   if ($val < 0) {
             //                      $out .= __('Lifelong');
             //                   }
             //                }
             //                return $out;
             //             }
             //             return "&nbsp;";
         //          case "glpi_infocoms.sink_time" :
         //             if (!empty($data[$NAME.$num])) {
         //                $split = explode("$$$$", $data[$NAME.$num]);
         //                $out   = '';
         //                foreach ($split as $val) {
         //                   $out .= (empty($out)?'':'<br>');
         //                   if ($val > 0) {
         //                      //TRANS: %d is a number of years
         //                      $out .= sprintf(_n('%d year', '%d years', $val), $val);
         //                   }
         //                }
         //                return $out;
         //             }
         //             return "&nbsp;";
         //
         //          case "glpi_infocoms.warranty_duration" :
         //             if (!empty($data[$NAME.$num])) {
         //                $split = explode("$$$$", $data[$NAME.$num]);
         //                $out   = '';
         //                foreach ($split as $val) {
         //                   $out .= (empty($out)?'':'<br>');
         //                   if ($val > 0) {
         //                      $out .= sprintf(_n('%d month', '%d months', $val), $val);
         //                   }
         //                   if ($val < 0) {
         //                      $out .= __('Lifelong');
         //                   }
         //                }
         //                return $out;
         //             }
         //             return "&nbsp;";
         case "glpi_infocoms.sink_type":
             $split = explode("\$\$\$\$", $data[$NAME . $num]);
             $out = '';
             foreach ($split as $val) {
                 $out .= (empty($out) ? '' : '<br>') . Infocom::getAmortTypeName($val);
             }
             return $out;
         case "glpi_infocoms.alert":
             if ($data[$NAME . $num] == pow(2, Alert::END)) {
                 return __s('Warranty expiration date');
             }
             return "";
         case "glpi_contracts.alert":
             switch ($data[$NAME . $num]) {
                 case pow(2, Alert::END):
                     return __('End');
                 case pow(2, Alert::NOTICE):
                     return __('Notice');
                 case pow(2, Alert::END) + pow(2, Alert::NOTICE):
                     return __('End + Notice');
             }
             return "";
         case "glpi_tickets_tickets.tickets_id_1":
             $out = "";
             $split = explode("\$\$\$\$", $data[$NAME . $num]);
             $split2 = explode("\$\$\$\$", $data[$NAME . $num . "_2"]);
             $displayed = array();
             for ($k = 0; $k < count($split); $k++) {
                 $linkid = $split[$k] == $data['id'] ? $split2[$k] : $split[$k];
                 if ($linkid > 0 && !isset($displayed[$linkid])) {
                     $text = "<a ";
                     $text .= "href=\"" . $CFG_GLPI["root_doc"] . "/front/ticket.form.php?id={$linkid}\">";
                     $text .= Dropdown::getDropdownName('glpi_tickets', $linkid) . "</a>";
                     if (count($displayed)) {
                         $out .= "<br>";
                     }
                     $displayed[$linkid] = $linkid;
                     $out .= $text;
                 }
             }
             return $out;
         case "glpi_problems.count":
             if ($data[$NAME . $num] > 0 && Session::haveRight("problem", Problem::READALL)) {
                 if ($itemtype == 'ITILCategory') {
                     $options['field'][0] = 7;
                     $options['searchtype'][0] = 'equals';
                     $options['contains'][0] = $data['id'];
                     $options['link'][0] = 'AND';
                 }
                 $options['reset'] = 'reset';
                 $out = "<a id='problem{$itemtype}" . $data['id'] . "' ";
                 $out .= "href=\"" . $CFG_GLPI["root_doc"] . "/front/problem.php?" . Toolbox::append_params($options, '&amp;') . "\">";
                 $out .= $data[$NAME . $num] . "</a>";
             } else {
                 $out = $data[$NAME . $num];
             }
             return $out;
         case "glpi_tickets.count":
             if ($data[$NAME . $num] > 0 && Session::haveRight("ticket", Ticket::READALL)) {
                 if ($itemtype == 'User') {
                     $options['field'][0] = 4;
                     $options['searchtype'][0] = 'equals';
                     $options['contains'][0] = $data['id'];
                     $options['link'][0] = 'AND';
                     $options['field'][1] = 22;
                     $options['searchtype'][1] = 'equals';
                     $options['contains'][1] = $data['id'];
                     $options['link'][1] = 'OR';
                     $options['field'][2] = 5;
                     $options['searchtype'][2] = 'equals';
                     $options['contains'][2] = $data['id'];
                     $options['link'][2] = 'OR';
                 } else {
                     if ($itemtype == 'ITILCategory') {
                         $options['field'][0] = 7;
                         $options['searchtype'][0] = 'equals';
                         $options['contains'][0] = $data['id'];
                         $options['link'][0] = 'AND';
                     } else {
                         $options['field'][0] = 12;
                         $options['searchtype'][0] = 'equals';
                         $options['contains'][0] = 'all';
                         $options['link'][0] = 'AND';
                         $options['itemtype2'][0] = $itemtype;
                         $options['field2'][0] = self::getOptionNumber($itemtype, 'name');
                         $options['searchtype2'][0] = 'equals';
                         $options['contains2'][0] = $data['id'];
                         $options['link2'][0] = 'AND';
                     }
                 }
                 $options['reset'] = 'reset';
                 $out = "<a id='ticket{$itemtype}" . $data['id'] . "' ";
                 $out .= "href=\"" . $CFG_GLPI["root_doc"] . "/front/ticket.php?" . Toolbox::append_params($options, '&amp;') . "\">";
                 $out .= $data[$NAME . $num] . "</a>";
             } else {
                 $out = $data[$NAME . $num];
             }
             return $out;
         case "glpi_tickets.due_date":
             // Due date + progress
             if ($ID == 151) {
                 $out = Html::convDate($data[$NAME . $num]);
                 // No due date in waiting status
                 if ($data[$NAME . $num . '_2'] == CommonITILObject::WAITING) {
                     return '';
                 }
                 if (empty($data[$NAME . $num])) {
                     return '';
                 }
                 if ($data[$NAME . $num . '_2'] == Ticket::SOLVED || $data[$NAME . $num . '_2'] == Ticket::CLOSED) {
                     return $data[$NAME . $num];
                 }
                 $ticket = new Ticket();
                 $ticket->getFromDB($data['ITEM_0']);
                 $percentage = 0;
                 $totaltime = 0;
                 $currenttime = 0;
                 if ($ticket->fields['slas_id'] != 0) {
                     // Have SLA
                     $sla = new SLA();
                     $sla->getFromDB($ticket->fields['slas_id']);
                     $currenttime = $sla->getActiveTimeBetween($ticket->fields['date'], date('Y-m-d H:i:s'));
                     $totaltime = $sla->getActiveTimeBetween($ticket->fields['date'], $data[$NAME . $num]);
                 } else {
                     $calendars_id = Entity::getUsedConfig('calendars_id', $ticket->fields['entities_id']);
                     if ($calendars_id != 0) {
                         // Ticket entity have calendar
                         $calendar = new Calendar();
                         $calendar->getFromDB($calendars_id);
                         $currenttime = $calendar->getActiveTimeBetween($ticket->fields['date'], date('Y-m-d H:i:s'));
                         $totaltime = $calendar->getActiveTimeBetween($ticket->fields['date'], $data[$NAME . $num]);
                     } else {
                         // No calendar
                         $currenttime = strtotime(date('Y-m-d H:i:s')) - strtotime($ticket->fields['date']);
                         $totaltime = strtotime($data[$NAME . $num]) - strtotime($ticket->fields['date']);
                     }
                 }
                 if ($totaltime != 0) {
                     $percentage = round(100 * $currenttime / $totaltime);
                 } else {
                     // Total time is null : no active time
                     $percentage = 100;
                 }
                 if ($percentage > 100) {
                     $percentage = 100;
                 }
                 $percentage_text = $percentage;
                 if ($_SESSION['glpiduedatewarning_unit'] == '%') {
                     $less_warn_limit = $_SESSION['glpiduedatewarning_less'];
                     $less_warn = 100 - $percentage;
                 } else {
                     if ($_SESSION['glpiduedatewarning_unit'] == 'hours') {
                         $less_warn_limit = $_SESSION['glpiduedatewarning_less'] * HOUR_TIMESTAMP;
                         $less_warn = $totaltime - $currenttime;
                     } else {
                         if ($_SESSION['glpiduedatewarning_unit'] == 'days') {
                             $less_warn_limit = $_SESSION['glpiduedatewarning_less'] * DAY_TIMESTAMP;
                             $less_warn = $totaltime - $currenttime;
                         }
                     }
                 }
                 if ($_SESSION['glpiduedatecritical_unit'] == '%') {
                     $less_crit_limit = $_SESSION['glpiduedatecritical_less'];
                     $less_crit = 100 - $percentage;
                 } else {
                     if ($_SESSION['glpiduedatecritical_unit'] == 'hours') {
                         $less_crit_limit = $_SESSION['glpiduedatecritical_less'] * HOUR_TIMESTAMP;
                         $less_crit = $totaltime - $currenttime;
                     } else {
                         if ($_SESSION['glpiduedatecritical_unit'] == 'days') {
                             $less_crit_limit = $_SESSION['glpiduedatecritical_less'] * DAY_TIMESTAMP;
                             $less_crit = $totaltime - $currenttime;
                         }
                     }
                 }
                 $color = $_SESSION['glpiduedateok_color'];
                 if ($less_crit < $less_crit_limit) {
                     $color = $_SESSION['glpiduedatecritical_color'];
                 } else {
                     if ($less_warn < $less_warn_limit) {
                         $color = $_SESSION['glpiduedatewarning_color'];
                     }
                 }
                 //Calculate bar progress
                 $out .= "<div class='center' style='background-color: #ffffff; width: 100%;\n                         border: 1px solid #9BA563;' >";
                 $out .= "<div style='position:absolute;'>&nbsp;" . $percentage_text . "%</div>";
                 $out .= "<div class='center' style='background-color: " . $color . ";\n                         width: " . $percentage . "%; height: 12px' ></div>";
                 $out .= "</div>";
                 return $out;
             }
             break;
         case "glpi_softwarelicenses.number":
             if ($data[$NAME . $num . "_2"] == -1) {
                 return __('Unlimited');
             }
             if (empty($data[$NAME . $num])) {
                 return 0;
             }
             return $data[$NAME . $num];
         case "glpi_auth_tables.name":
             return Auth::getMethodName($data[$NAME . $num], $data[$NAME . $num . "_2"], 1, $data[$NAME . $num . "_3"] . $data[$NAME . $num . "_4"]);
         case "glpi_reservationitems.comment":
             if (empty($data[$NAME . $num])) {
                 return "<a title=\"" . __s('Modify the comment') . "\"\n                        href='" . $CFG_GLPI["root_doc"] . "/front/reservationitem.form.php?id=" . $data["refID"] . "' >" . __('None') . "</a>";
             }
             return "<a title=\"" . __s('Modify the comment') . "\"\n                     href='" . $CFG_GLPI["root_doc"] . "/front/reservationitem.form.php?id=" . $data['refID'] . "' >" . Html::resume_text($data[$NAME . $num]) . "</a>";
         case 'glpi_notifications.mode':
             return Notification::getMode($data[$NAME . $num]);
         case 'glpi_notifications.event':
             $item = NotificationTarget::getInstanceByType($data['itemtype']);
             if ($item) {
                 $events = $item->getAllEvents();
                 if (isset($events[$data[$NAME . $num]])) {
                     return $events[$data[$NAME . $num]];
                 }
             }
             return '';
         case 'glpi_reminders.state':
             return Planning::getState($data[$NAME . $num]);
         case 'glpi_crontasks.description':
             $tmp = new CronTask();
             return $tmp->getDescription($data['id']);
         case 'glpi_crontasks.state':
             return CronTask::getStateName($data[$NAME . $num]);
         case 'glpi_crontasks.mode':
             return CronTask::getModeName($data[$NAME . $num]);
         case 'glpi_crontasks.itemtype':
             if ($plug = isPluginItemType($data[$NAME . $num])) {
                 return $plug['plugin'];
             }
             return '';
         case 'glpi_changes.status':
             $status = Change::getStatus($data[$NAME . $num]);
             return "<img src=\"" . Change::getStatusIconURL($data[$NAME . $num]) . "\"\n                     alt=\"{$status}\" title=\"{$status}\">&nbsp;{$status}";
         case 'glpi_problems.status':
             $status = Problem::getStatus($data[$NAME . $num]);
             return "<img src=\"" . Problem::getStatusIconURL($data[$NAME . $num]) . "\"\n                     alt=\"{$status}\" title=\"{$status}\">&nbsp;{$status}";
         case 'glpi_tickets.status':
             $status = Ticket::getStatus($data[$NAME . $num]);
             return "<img src=\"" . Ticket::getStatusIconURL($data[$NAME . $num]) . "\"\n                     alt=\"{$status}\" title=\"{$status}\">&nbsp;{$status}";
         case 'glpi_tickets.items_id':
             if (!empty($data[$NAME . $num . "_2"]) && ($item = getItemForItemtype($data[$NAME . $num . "_2"]))) {
                 if ($item->getFromDB($data[$NAME . $num])) {
                     return $item->getLink(array('comments' => true));
                 }
             }
             return '&nbsp;';
         case 'glpi_tickets.name':
             if (isset($searchopt[$ID]['forcegroupby']) && $searchopt[$ID]['forcegroupby']) {
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $out = '';
                 $link = Toolbox::getItemTypeFormURL('Ticket');
                 foreach ($split as $val) {
                     if (!empty($val)) {
                         $split2 = self::explodeWithID("\$\$", $val);
                         $out .= "<a id='ticket" . $split2[1] . "' href=\"" . $link;
                         $out .= strstr($link, '?') ? '&amp;' : '?';
                         $out .= 'id=' . $split2[1];
                         $out .= "\">";
                         $name = $split2[0];
                         if ($_SESSION["glpiis_ids_visible"] || empty($split2[0])) {
                             $name = sprintf(__('%1$s (%2$s)'), $name, $split2[1]);
                         }
                         $out .= $name . "</a><br>";
                     }
                 }
                 return $out;
             }
             $link = Toolbox::getItemTypeFormURL('Ticket');
             $out = "<a id='ticket" . $data[$NAME . $num . "_2"] . "' href=\"" . $link;
             $out .= strstr($link, '?') ? '&amp;' : '?';
             $out .= 'id=' . $data[$NAME . $num . "_2"];
             // Force solution tab if solved
             if ($data[$NAME . $num . "_4"] == CommonITILObject::SOLVED) {
                 $out .= "&amp;forcetab=Ticket\$2";
             }
             $out .= "\">";
             $name = $data[$NAME . $num];
             if ($_SESSION["glpiis_ids_visible"] || empty($data[$NAME . $num])) {
                 $name = sprintf(__('%1$s (%2$s)'), $name, $data[$NAME . $num . "_2"]);
             }
             $out .= $name . "</a>";
             $out = sprintf(__('%1$s %2$s'), $out, Html::showToolTip(nl2br($data[$NAME . $num . "_3"]), array('applyto' => 'ticket' . $data[$NAME . $num . "_2"], 'display' => false)));
             return $out;
         case 'glpi_ticketvalidations.status':
             $split = explode("\$\$\$\$", $data[$NAME . $num]);
             $out = '';
             foreach ($split as $val) {
                 if (!empty($val)) {
                     $split2 = self::explodeWithID("\$\$", $val);
                     $status = TicketValidation::getStatus($split2[0]);
                     $bgcolor = TicketValidation::getStatusColor($split2[0]);
                     $out .= (empty($out) ? '' : '<br>') . "<div style=\"background-color:" . $bgcolor . ";\">" . $status . '</div>';
                 }
             }
             return $out;
         case 'glpi_ticketsatisfactions.type':
             return TicketSatisfaction::getTypeInquestName($data[$NAME . $num]);
         case 'glpi_ticketsatisfactions.satisfaction':
             return TicketSatisfaction::displaySatisfaction($data[$NAME . $num]);
         case 'glpi_notimportedemails.reason':
             return NotImportedEmail::getReason($data[$NAME . $num]);
         case 'glpi_notimportedemails.messageid':
             $clean = array('<' => '', '>' => '');
             return strtr($data[$NAME . $num], $clean);
     }
     //// Default case
     // Link with plugin tables : need to know left join structure
     if (preg_match("/^glpi_plugin_([a-z0-9]+)/", $table . '.' . $field, $matches)) {
         if (count($matches) == 2) {
             $plug = $matches[1];
             $function = 'plugin_' . $plug . '_giveItem';
             if (function_exists($function)) {
                 $out = $function($itemtype, $ID, $data, $num);
                 if (!empty($out)) {
                     return $out;
                 }
             }
         }
     }
     $unit = '';
     if (isset($searchopt[$ID]['unit'])) {
         $unit = $searchopt[$ID]['unit'];
     }
     /// TODO try to use getvalueToDisplay instead of redefine display system
     // Preformat items
     if (isset($searchopt[$ID]["datatype"])) {
         switch ($searchopt[$ID]["datatype"]) {
             case "itemlink":
                 $linkitemtype = getItemTypeForTable($searchopt[$ID]["table"]);
                 if (isset($data[$NAME . $num . "_2"]) && strlen($data[$NAME . $num . "_2"])) {
                     $link = Toolbox::getItemTypeFormURL($linkitemtype);
                     $out = "<a id='" . $itemtype . "_" . $data[$NAME . $num . "_2"] . "' href=\"" . $link;
                     $out .= strstr($link, '?') ? '&amp;' : '?';
                     $out .= 'id=' . $data[$NAME . $num . "_2"];
                     if (isset($searchopt[$ID]['forcetab'])) {
                         $out .= "&amp;forcetab=" . $searchopt[$ID]['forcetab'];
                     }
                     $out .= "\">";
                     $name = Dropdown::getValueWithUnit($data[$NAME . $num], $unit);
                     if ($_SESSION["glpiis_ids_visible"] || empty($data[$NAME . $num])) {
                         $name = sprintf(__('%1$s (%2$s)'), $name, $data[$NAME . $num . "_2"]);
                     }
                     $out .= $name . "</a>";
                     return $out;
                 }
                 $out = "";
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $count_display = 0;
                 $separate = '<br>';
                 if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) {
                     $separate = '<hr>';
                 }
                 for ($k = 0; $k < count($split); $k++) {
                     if (strlen(trim($split[$k])) > 0) {
                         $split2 = self::explodeWithID("\$\$", $split[$k]);
                         if (isset($split2[1]) && $split2[1] > 0) {
                             if ($count_display) {
                                 $out .= $separate;
                             }
                             $count_display++;
                             $page = Toolbox::getItemTypeFormURL($linkitemtype);
                             $page .= strpos($page, '?') ? '&id' : '?id';
                             $name = Dropdown::getValueWithUnit($split2[0], $unit);
                             if ($_SESSION["glpiis_ids_visible"] || empty($split2[0])) {
                                 $name = sprintf(__('%1$s (%2$s)'), $name, $split2[1]);
                             }
                             $out .= "<a id='" . $linkitemtype . "_" . $data['id'] . "_" . $split2[1] . "' href='{$page}=" . $split2[1] . "'>" . $name . "</a>";
                         }
                     }
                 }
                 return $out;
             case "text":
                 $separate = '<br>';
                 if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) {
                     $separate = '<hr>';
                 }
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $out = '';
                 $count_display = 0;
                 foreach ($split as $val) {
                     if (strlen(trim($val)) > 0) {
                         $split2 = self::explodeWithID("\$\$", $val);
                         if ($count_display) {
                             $out .= $separate;
                         }
                         $count_display++;
                         if (isset($searchopt[$ID]['htmltext']) && $searchopt[$ID]['htmltext']) {
                             $text = Html::clean(Toolbox::unclean_cross_side_scripting_deep(nl2br($split2[0])));
                         } else {
                             $text = nl2br($split2[0]);
                         }
                         if (self::$output_type == self::HTML_OUTPUT && Toolbox::strlen($text) > $CFG_GLPI['cut']) {
                             $rand = mt_rand();
                             $out .= sprintf(__('%1$s %2$s'), "<span id='text{$rand}'>" . Html::resume_text($text, $CFG_GLPI['cut']) . '</span>', Html::showToolTip($text, array('applyto' => "text{$rand}", 'display' => false)));
                         } else {
                             $out .= $text;
                         }
                     }
                 }
                 return $out;
             case "date":
             case "date_delay":
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $out = '';
                 foreach ($split as $val) {
                     $out .= (empty($out) ? '' : '<br>') . Html::convDate($val);
                 }
                 return $out;
             case "datetime":
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $out = '';
                 foreach ($split as $val) {
                     $out .= (empty($out) ? '' : '<br>') . Html::convDateTime($val);
                 }
                 return $out;
             case "timestamp":
                 $withseconds = false;
                 if (isset($searchopt[$ID]['withseconds'])) {
                     $withseconds = $searchopt[$ID]['withseconds'];
                 }
                 $withdays = true;
                 if (isset($searchopt[$ID]['withdays'])) {
                     $withdays = $searchopt[$ID]['withdays'];
                 }
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $out = '';
                 foreach ($split as $val) {
                     $out .= (empty($out) ? '' : '<br>') . Html::timestampToString($val, $withseconds, $withdays);
                 }
                 return $out;
             case "email":
                 $split = explode('$$$$', $data[$NAME . $num]);
                 $out = '';
                 $count_display = 0;
                 foreach ($split as $val) {
                     $split2 = self::explodeWithID("\$\$", $val);
                     if ($count_display) {
                         $out .= "<br>";
                     }
                     $count_display++;
                     if (!empty($val)) {
                         $out .= empty($out) ? '' : '<br>';
                         $out .= "<a href='mailto:{$split2['0']}'>{$split2['0']}</a>";
                     }
                 }
                 return empty($out) ? "&nbsp;" : $out;
             case "weblink":
                 $orig_link = trim($data[$NAME . $num]);
                 if (!empty($orig_link)) {
                     // strip begin of link
                     $link = preg_replace('/https?:\\/\\/(www[^\\.]*\\.)?/', '', $orig_link);
                     $link = preg_replace('/\\/$/', '', $link);
                     if (Toolbox::strlen($link) > $CFG_GLPI["url_maxlength"]) {
                         $link = Toolbox::substr($link, 0, $CFG_GLPI["url_maxlength"]) . "...";
                     }
                     return "<a href=\"" . formatOutputWebLink($orig_link) . "\" target='_blank'>{$link}</a>";
                 }
                 return "&nbsp;";
             case "number":
                 if (isset($searchopt[$ID]['forcegroupby']) && $searchopt[$ID]['forcegroupby']) {
                     $out = "";
                     $split = explode("\$\$\$\$", $data[$NAME . $num]);
                     $count_display = 0;
                     for ($k = 0; $k < count($split); $k++) {
                         if (strlen(trim($split[$k])) > 0) {
                             $split2 = self::explodeWithID("\$\$", $split[$k]);
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             if (isset($searchopt[$ID]['toadd']) && isset($searchopt[$ID]['toadd'][$split2[0]])) {
                                 $out .= $searchopt[$ID]['toadd'][$split2[0]];
                             } else {
                                 $number = str_replace(' ', '&nbsp;', Html::formatNumber($split2[0], false, 0));
                                 $out .= Dropdown::getValueWithUnit($number, $unit);
                             }
                         }
                     }
                     return $out;
                 }
                 if (isset($searchopt[$ID]['toadd']) && isset($searchopt[$ID]['toadd'][$data[$NAME . $num]])) {
                     return $searchopt[$ID]['toadd'][$data[$NAME . $num]];
                 } else {
                     $number = str_replace(' ', '&nbsp;', Html::formatNumber($data[$NAME . $num], false, 0));
                     return Dropdown::getValueWithUnit($number, $unit);
                 }
             case "decimal":
                 if (isset($searchopt[$ID]['forcegroupby']) && $searchopt[$ID]['forcegroupby']) {
                     $out = "";
                     $split = explode("\$\$\$\$", $data[$NAME . $num]);
                     $count_display = 0;
                     for ($k = 0; $k < count($split); $k++) {
                         if (strlen(trim($split[$k])) > 0) {
                             $split2 = self::explodeWithID("\$\$", $split[$k]);
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             if (isset($searchopt[$ID]['toadd']) && isset($searchopt[$ID]['toadd'][$split2[0]])) {
                                 $out .= $searchopt[$ID]['toadd'][$split2[0]];
                             } else {
                                 $number = str_replace(' ', '&nbsp;', Html::formatNumber($split2[0]));
                                 $out .= Dropdown::getValueWithUnit($number, $unit);
                             }
                         }
                     }
                     return $out;
                 }
                 $number = str_replace(' ', '&nbsp;', Html::formatNumber($data[$NAME . $num]));
                 return Dropdown::getValueWithUnit($number, $unit);
             case "bool":
                 if (isset($searchopt[$ID]['forcegroupby']) && $searchopt[$ID]['forcegroupby']) {
                     $out = "";
                     $split = explode("\$\$\$\$", $data[$NAME . $num]);
                     $count_display = 0;
                     for ($k = 0; $k < count($split); $k++) {
                         if (strlen(trim($split[$k])) > 0) {
                             $split2 = self::explodeWithID("\$\$", $split[$k]);
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= Dropdown::getValueWithUnit(Dropdown::getYesNo($split2[0]), $unit);
                         }
                     }
                     return $out;
                 }
                 return Dropdown::getValueWithUnit(Dropdown::getYesNo($data[$NAME . $num]), $unit);
             case "right":
                 return Profile::getRightValue($data[$NAME . $num]);
             case "itemtypename":
                 if ($obj = getItemForItemtype($data[$NAME . $num])) {
                     return $obj->getTypeName();
                 }
                 return "";
             case "language":
                 if (isset($CFG_GLPI['languages'][$data[$NAME . $num]])) {
                     return $CFG_GLPI['languages'][$data[$NAME . $num]][0];
                 }
                 return __('Default value');
         }
     }
     // Manage items with need group by / group_concat
     if (isset($searchopt[$ID]['forcegroupby']) && $searchopt[$ID]['forcegroupby']) {
         $out = "";
         $split = explode("\$\$\$\$", $data[$NAME . $num]);
         $count_display = 0;
         $separate = '<br>';
         if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) {
             $separate = '<hr>';
         }
         for ($k = 0; $k < count($split); $k++) {
             if (strlen(trim($split[$k])) > 0) {
                 if ($count_display) {
                     $out .= $separate;
                 }
                 $withoutid = self::explodeWithID("\$\$", $split[$k]);
                 $count_display++;
                 // Get specific display if available
                 $itemtype = getItemTypeForTable($table);
                 if ($item = getItemForItemtype($itemtype)) {
                     $tmpdata = array($field => $withoutid[0]);
                     $specific = $item->getSpecificValueToDisplay($field, $tmpdata, array('html' => true));
                 }
                 if (!empty($specific)) {
                     $out .= $specific;
                 } else {
                     $out .= Dropdown::getValueWithUnit($withoutid[0], $unit);
                 }
             }
         }
         return $out;
     }
     // Get specific display if available
     $itemtype = getItemTypeForTable($table);
     if ($item = getItemForItemtype($itemtype)) {
         $tmpdata = array($field => $data[$NAME . $num]);
         if (isset($searchopt[$ID]['additionalfields']) && count($searchopt[$ID]['additionalfields'])) {
             foreach ($searchopt[$ID]['additionalfields'] as $key) {
                 $tmpdata[$key] = $data[$NAME . $num . '_' . $key];
             }
         }
         $specific = $item->getSpecificValueToDisplay($field, $tmpdata, array('html' => true));
         if (!empty($specific)) {
             return $specific;
         }
     }
     // Manage auto CONCAT id
     $split = self::explodeWithID('$$', $data[$NAME . $num]);
     $split[0] = trim($split[0]);
     if (isset($searchopt[$ID]['toadd']) && isset($searchopt[$ID]['toadd'][$split[0]])) {
         return $searchopt[$ID]['toadd'][$split[0]];
     }
     // Empty is 0 or empty
     if (empty($split[0]) && isset($searchopt[$ID]['emptylabel'])) {
         return $searchopt[$ID]['emptylabel'];
     }
     return Dropdown::getValueWithUnit($split[0], $unit);
 }
 /**
  * @see NotificationTargetCommonITILObject::getDatasForObject()
  **/
 function getDatasForObject(CommonDBTM $item, array $options, $simple = false)
 {
     global $CFG_GLPI;
     // Common ITIL datas
     $datas = parent::getDatasForObject($item, $options, $simple);
     // Specific datas
     $datas['##change.urlvalidation##'] = $this->formatURL($options['additionnaloption']['usertype'], "change_" . $item->getField("id") . "_ChangeValidation\$1");
     $datas['##change.globalvalidation##'] = ChangeValidation::getStatus($item->getField('global_validation'));
     //       $datas["##problem.impacts##"]  = $item->getField('impactcontent');
     //       $datas["##problem.causes##"]   = $item->getField('causecontent');
     //       $datas["##problem.symptoms##"] = $item->getField('symptomcontent');
     // Complex mode
     if (!$simple) {
         $restrict = "`changes_id`='" . $item->getField('id') . "'";
         $tickets = getAllDatasFromTable('glpi_changes_tickets', $restrict);
         $datas['tickets'] = array();
         if (count($tickets)) {
             $ticket = new Ticket();
             foreach ($tickets as $data) {
                 if ($ticket->getFromDB($data['tickets_id'])) {
                     $tmp = array();
                     $tmp['##ticket.id##'] = $data['tickets_id'];
                     $tmp['##ticket.date##'] = $ticket->getField('date');
                     $tmp['##ticket.title##'] = $ticket->getField('name');
                     $tmp['##ticket.url##'] = $this->formatURL($options['additionnaloption']['usertype'], "Ticket_" . $data['tickets_id']);
                     $tmp['##ticket.content##'] = $ticket->getField('content');
                     $datas['tickets'][] = $tmp;
                 }
             }
         }
         $datas['##change.numberoftickets##'] = count($datas['tickets']);
         $restrict = "`changes_id`='" . $item->getField('id') . "'";
         $problems = getAllDatasFromTable('glpi_changes_problems', $restrict);
         $datas['problems'] = array();
         if (count($problems)) {
             $problem = new Problem();
             foreach ($problems as $data) {
                 if ($problem->getFromDB($data['problems_id'])) {
                     $tmp = array();
                     $tmp['##problem.id##'] = $data['problems_id'];
                     $tmp['##problem.date##'] = $problem->getField('date');
                     $tmp['##problem.title##'] = $problem->getField('name');
                     $tmp['##problem.url##'] = $this->formatURL($options['additionnaloption']['usertype'], "Problem_" . $data['problems_id']);
                     $tmp['##problem.content##'] = $problem->getField('content');
                     $datas['problems'][] = $tmp;
                 }
             }
         }
         $datas['##change.numberofproblems##'] = count($datas['problems']);
         $restrict = "`changes_id` = '" . $item->getField('id') . "'";
         $items = getAllDatasFromTable('glpi_changes_items', $restrict);
         $datas['items'] = array();
         if (count($items)) {
             foreach ($items as $data) {
                 if ($item2 = getItemForItemtype($data['itemtype'])) {
                     if ($item2->getFromDB($data['items_id'])) {
                         $tmp = array();
                         $tmp['##item.itemtype##'] = $item2->getTypeName();
                         $tmp['##item.name##'] = $item2->getField('name');
                         $tmp['##item.serial##'] = $item2->getField('serial');
                         $tmp['##item.otherserial##'] = $item2->getField('otherserial');
                         $tmp['##item.contact##'] = $item2->getField('contact');
                         $tmp['##item.contactnum##'] = $item2->getField('contactnum');
                         $tmp['##item.location##'] = '';
                         $tmp['##item.user##'] = '';
                         $tmp['##item.group##'] = '';
                         $tmp['##item.model##'] = '';
                         //Object location
                         if ($item2->getField('locations_id') != NOT_AVAILABLE) {
                             $tmp['##item.location##'] = Dropdown::getDropdownName('glpi_locations', $item2->getField('locations_id'));
                         }
                         //Object user
                         if ($item2->getField('users_id')) {
                             $user_tmp = new User();
                             if ($user_tmp->getFromDB($item2->getField('users_id'))) {
                                 $tmp['##item.user##'] = $user_tmp->getName();
                             }
                         }
                         //Object group
                         if ($item2->getField('groups_id')) {
                             $tmp['##item.group##'] = Dropdown::getDropdownName('glpi_groups', $item2->getField('groups_id'));
                         }
                         $modeltable = getSingular($item2->getTable()) . "models";
                         $modelfield = getForeignKeyFieldForTable($modeltable);
                         if ($item2->isField($modelfield)) {
                             $tmp['##item.model##'] = $item2->getField($modelfield);
                         }
                         $datas['items'][] = $tmp;
                     }
                 }
             }
         }
         $datas['##change.numberofitems##'] = count($datas['items']);
         //Validation infos
         $restrict = "`changes_id`='" . $item->getField('id') . "'";
         if (isset($options['validation_id']) && $options['validation_id']) {
             $restrict .= " AND `glpi_changevalidations`.`id` = '" . $options['validation_id'] . "'";
         }
         $restrict .= " ORDER BY `submission_date` DESC, `id` ASC";
         $validations = getAllDatasFromTable('glpi_changevalidations', $restrict);
         $datas['validations'] = array();
         foreach ($validations as $validation) {
             $tmp = array();
             $tmp['##validation.submission.title##'] = sprintf(__('An approval request has been submitted by %s'), Html::clean(getUserName($validation['users_id'])));
             $tmp['##validation.answer.title##'] = sprintf(__('An answer to an an approval request was produced by %s'), Html::clean(getUserName($validation['users_id_validate'])));
             $tmp['##validation.author##'] = Html::clean(getUserName($validation['users_id']));
             $tmp['##validation.status##'] = TicketValidation::getStatus($validation['status']);
             $tmp['##validation.storestatus##'] = $validation['status'];
             $tmp['##validation.submissiondate##'] = Html::convDateTime($validation['submission_date']);
             $tmp['##validation.commentsubmission##'] = $validation['comment_submission'];
             $tmp['##validation.validationdate##'] = Html::convDateTime($validation['validation_date']);
             $tmp['##validation.validator##'] = Html::clean(getUserName($validation['users_id_validate']));
             $tmp['##validation.commentvalidation##'] = $validation['comment_validation'];
             $datas['validations'][] = $tmp;
         }
     }
     return $datas;
 }
 /**
  * Get all data needed for template processing
  **/
 function getDatasForTemplate($event, $options = array())
 {
     global $LANG, $CFG_GLPI;
     //----------- Ticket infos -------------- //
     if ($event != 'alertnotclosed') {
         $fields = array('ticket.title' => 'name', 'ticket.content' => 'content', 'ticket.description' => 'content', 'ticket.costfixed' => 'cost_fixed', 'ticket.costmaterial' => 'cost_material');
         foreach ($fields as $tag => $table_field) {
             $this->datas['##' . $tag . '##'] = $this->obj->getField($table_field);
         }
         $this->datas['##ticket.id##'] = sprintf("%07d", $this->obj->getField("id"));
         $this->datas['##ticket.url##'] = urldecode($CFG_GLPI["url_base"] . "/index.php?redirect=ticket_" . $this->obj->getField("id"));
         $this->datas['##ticket.urlapprove##'] = urldecode($CFG_GLPI["url_base"] . "/index.php?redirect=ticket_" . $this->obj->getField("id") . "_4");
         $this->datas['##ticket.urlvalidation##'] = urldecode($CFG_GLPI["url_base"] . "/index.php?redirect=ticket_" . $this->obj->getField("id") . "_7");
         $this->datas['##ticket.entity##'] = Dropdown::getDropdownName('glpi_entities', $this->getEntity());
         $events = $this->getAllEvents();
         if ($event == 'validation' && isset($options['validation_status'])) {
             $this->datas['##ticket.action##'] = $LANG['validation'][0] . ' - ' . TicketValidation::getStatus($options['validation_status']);
         } else {
             $this->datas['##ticket.action##'] = $events[$event];
         }
         $this->datas['##ticket.storestatus##'] = $this->obj->getField('status');
         $this->datas['##ticket.status##'] = Ticket::getStatus($this->obj->getField('status'));
         $this->datas['##ticket.globalvalidation##'] = TicketValidation::getStatus($this->obj->getField('global_validation'));
         $this->datas['##ticket.type##'] = Ticket::getTicketTypeName($this->obj->getField('type'));
         $this->datas['##ticket.requesttype##'] = Dropdown::getDropdownName('glpi_requesttypes', $this->obj->getField('requesttypes_id'));
         $this->datas['##ticket.urgency##'] = Ticket::getUrgencyName($this->obj->getField('urgency'));
         $this->datas['##ticket.impact##'] = Ticket::getImpactName($this->obj->getField('impact'));
         $this->datas['##ticket.priority##'] = Ticket::getPriorityName($this->obj->getField('priority'));
         $this->datas['##ticket.time##'] = Ticket::getActionTime($this->obj->getField('actiontime'));
         $this->datas['##ticket.costtime##'] = $this->obj->getField('cost_time');
         $this->datas['##ticket.creationdate##'] = convDateTime($this->obj->getField('date'));
         $this->datas['##ticket.closedate##'] = convDateTime($this->obj->getField('closedate'));
         $this->datas['##ticket.solvedate##'] = convDateTime($this->obj->getField('solvedate'));
         $this->datas['##ticket.duedate##'] = convDateTime($this->obj->getField('due_date'));
         $entitydata = new EntityData();
         $autoclose_value = $CFG_GLPI['autoclose_delay'];
         if ($entitydata->getFromDB($this->getEntity())) {
             $autoclose_value = $entitydata->getField('autoclose_delay');
             // Set global config value
             if ($autoclose_value == -1) {
                 $autoclose_value = $CFG_GLPI['autoclose_delay'];
             }
         }
         if ($autoclose_value > 0) {
             $this->datas['##ticket.autoclose##'] = $autoclose_value;
             $this->datas['##lang.ticket.autoclosewarning##'] = $LANG['job'][54] . " " . $autoclose_value . " " . $LANG['stats'][31];
         } else {
             $this->datas['##ticket.autoclose##'] = $LANG['setup'][307];
             $this->datas['##lang.ticket.autoclosewarning##'] = "";
         }
         if ($this->obj->getField('ticketcategories_id')) {
             $this->datas['##ticket.category##'] = Dropdown::getDropdownName('glpi_ticketcategories', $this->obj->getField('ticketcategories_id'));
         } else {
             $this->datas['##ticket.category##'] = '';
         }
         if ($this->obj->getField('slas_id')) {
             $this->datas['##ticket.sla##'] = Dropdown::getDropdownName('glpi_slas', $this->obj->getField('slas_id'));
         } else {
             $this->datas['##ticket.sla##'] = '';
         }
         if ($this->obj->countUsers(Ticket::REQUESTER)) {
             $users = array();
             foreach ($this->obj->getUsers(Ticket::REQUESTER) as $uid => $tmp) {
                 $user_tmp = new User();
                 $user_tmp->getFromDB($uid);
                 $users[$uid] = $user_tmp->getName();
                 $tmp = array();
                 $tmp['##author.id##'] = $uid;
                 $tmp['##author.name##'] = $user_tmp->getName();
                 if ($user_tmp->getField('locations_id')) {
                     $tmp['##author.location##'] = Dropdown::getDropdownName('glpi_locations', $user_tmp->getField('locations_id'));
                 } else {
                     $tmp['##author.location##'] = '';
                 }
                 $tmp['##author.phone##'] = $user_tmp->getField('phone');
                 $tmp['##author.phone2##'] = $user_tmp->getField('phone2');
                 $this->datas['authors'][] = $tmp;
             }
             $this->datas['##ticket.authors##'] = implode(', ', $users);
         } else {
             $this->datas['##ticket.authors##'] = '';
         }
         if ($this->obj->getField('users_id_recipient')) {
             $user_tmp = new User();
             $user_tmp->getFromDB($this->obj->getField('users_id_recipient'));
             $this->datas['##ticket.openbyuser##'] = $user_tmp->getName();
         } else {
             $this->datas['##ticket.openbyuser##'] = '';
         }
         if ($this->obj->countUsers(Ticket::ASSIGN)) {
             $users = array();
             foreach ($this->obj->getUsers(Ticket::ASSIGN) as $uid => $tmp) {
                 $user_tmp = new User();
                 $user_tmp->getFromDB($uid);
                 $users[$uid] = $user_tmp->getName();
             }
             $this->datas['##ticket.assigntousers##'] = implode(', ', $users);
         } else {
             $this->datas['##ticket.assigntousers##'] = '';
         }
         if ($this->obj->countUsers(Ticket::OBSERVER)) {
             $users = array();
             foreach ($this->obj->getUsers(Ticket::OBSERVER) as $uid => $tmp) {
                 $user_tmp = new User();
                 $user_tmp->getFromDB($uid);
                 $users[$uid] = $user_tmp->getName();
             }
             $this->datas['##ticket.observerusers##'] = implode(', ', $users);
         } else {
             $this->datas['##ticket.observerusers##'] = '';
         }
         if ($this->obj->getField('suppliers_id_assign')) {
             $this->datas['##ticket.assigntosupplier##'] = Dropdown::getDropdownName('glpi_suppliers', $this->obj->getField('suppliers_id_assign'));
         } else {
             $this->datas['##ticket.assigntosupplier##'] = '';
         }
         if ($this->obj->countGroups(Ticket::REQUESTER)) {
             $groups = array();
             foreach ($this->obj->getUsers(Ticket::REQUESTER) as $gid => $tmp) {
                 $groups[$gid] = Dropdown::getDropdownName('glpi_groups', $gid);
             }
             $this->datas['##ticket.groups##'] = implode(', ', $groups);
         } else {
             $this->datas['##ticket.groups##'] = '';
         }
         if ($this->obj->countGroups(Ticket::OBSERVER)) {
             $groups = array();
             foreach ($this->obj->getGroups(Ticket::OBSERVER) as $gid => $tmp) {
                 $groups[$gid] = Dropdown::getDropdownName('glpi_groups', $gid);
             }
             $this->datas['##ticket.observergroups##'] = implode(', ', $groups);
         } else {
             $this->datas['##ticket.observergroups##'] = '';
         }
         if ($this->obj->countGroups(Ticket::ASSIGN)) {
             $groups = array();
             foreach ($this->obj->getGroups(Ticket::ASSIGN) as $gid => $tmp) {
                 $groups[$gid] = Dropdown::getDropdownName('glpi_groups', $gid);
             }
             $this->datas['##ticket.assigntogroups##'] = implode(', ', $groups);
         } else {
             $this->datas['##ticket.assigntogroups##'] = '';
         }
         //Tags associated with the object linked to the ticket
         if ($this->target_object != null) {
             //Object type
             $this->datas['##ticket.itemtype##'] = $this->target_object->getTypeName();
             //Object name
             $this->datas['##ticket.item.name##'] = $this->target_object->getField('name');
             //Object serial
             if ($this->target_object->isField('serial')) {
                 $this->datas['##ticket.item.serial##'] = $this->target_object->getField('serial');
             } else {
                 $this->datas['##ticket.item.serial##'] = '';
             }
             //Object contact
             if ($this->target_object->isField('contact')) {
                 $this->datas['##ticket.item.contact##'] = $this->target_object->getField('contact');
             } else {
                 $this->datas['##ticket.item.contact##'] = '';
             }
             //Object contact num
             if ($this->target_object->isField('contact_num')) {
                 $this->datas['##ticket.item.contactnumber##'] = $this->target_object->getField('contact_num');
             } else {
                 $this->datas['##ticket.item.contactnumber##'] = '';
             }
             //Object otherserial
             if ($this->target_object->isField('otherserial')) {
                 $this->datas['##ticket.item.otherserial##'] = $this->target_object->getField('otherserial');
             } else {
                 $this->datas['##ticket.item.otherserial##'] = '';
             }
             //Object location
             if ($this->target_object->isField('locations_id')) {
                 $this->datas['##ticket.item.location##'] = Dropdown::getDropdownName('glpi_locations', $this->target_object->getField('locations_id'));
             } else {
                 $this->datas['##ticket.item.location##'] = '';
             }
             //Object user
             $this->datas['##ticket.item.user##'] = '';
             if ($this->obj->getField('users_id')) {
                 $user_tmp = new User();
                 if ($user_tmp->getFromDB($this->target_object->getField('users_id'))) {
                     $this->datas['##ticket.item.user##'] = $user_tmp->getName();
                 }
             }
             //Object group
             if ($this->obj->getField('groups_id')) {
                 $this->datas['##ticket.item.group##'] = Dropdown::getDropdownName('glpi_groups', $this->target_object->getField('groups_id'));
             } else {
                 $this->datas['##ticket.item.group##'] = '';
             }
             $modeltable = getSingular($this->getTable()) . "models";
             $modelfield = getForeignKeyFieldForTable($modeltable);
             if ($this->target_object->isField($modelfield)) {
                 $this->datas['##ticket.item.model##'] = $this->target_object->getField($modelfield);
             } else {
                 $this->datas['##ticket.item.model##'] = '';
             }
         } else {
             $this->datas['##ticket.itemtype##'] = '';
             $this->datas['##ticket.item.name##'] = '';
             $this->datas['##ticket.item.serial##'] = '';
             $this->datas['##ticket.item.otherserial##'] = '';
             $this->datas['##ticket.item.location##'] = '';
         }
         if ($this->obj->getField('ticketsolutiontypes_id')) {
             $this->datas['##ticket.solution.type##'] = Dropdown::getDropdownName('glpi_ticketsolutiontypes', $this->obj->getField('ticketsolutiontypes_id'));
         } else {
             $this->datas['##ticket.solution.type##'] = '';
         }
         $this->datas['##ticket.solution.description##'] = unclean_cross_side_scripting_deep($this->obj->getField('solution'));
         // Linked tickets
         $linked_tickets = Ticket_Ticket::getLinkedTicketsTo($this->obj->getField('id'));
         if (count($linked_tickets)) {
             $linkedticket = new Ticket();
             foreach ($linked_tickets as $data) {
                 if ($linkedticket->getFromDB($data['tickets_id'])) {
                     $tmp = array();
                     $tmp['##linkedticket.id##'] = $data['tickets_id'];
                     $tmp['##linkedticket.link##'] = Ticket_Ticket::getLinkName($data['link']);
                     $tmp['##linkedticket.url##'] = urldecode($CFG_GLPI["url_base"] . "/index.php" . "?redirect=ticket_" . $data['tickets_id']);
                     $tmp['##linkedticket.title##'] = $linkedticket->getField('name');
                     $tmp['##linkedticket.content##'] = $linkedticket->getField('content');
                     $this->datas['linkedtickets'][] = $tmp;
                 }
             }
         }
         if (!empty($this->datas['linkedtickets'])) {
             $this->datas['##ticket.numberoflinkedtickets##'] = count($this->datas['linkedtickets']);
         } else {
             $this->datas['##ticket.numberoflinkedtickets##'] = 0;
         }
         $restrict = "`tickets_id`='" . $this->obj->getField('id') . "'";
         if (!isset($options['additionnaloption']) || !$options['additionnaloption']) {
             $restrict .= " AND `is_private` = '0'";
         }
         $restrict .= " ORDER BY `date` DESC, `id` ASC";
         //Task infos
         $tasks = getAllDatasFromTable('glpi_tickettasks', $restrict);
         foreach ($tasks as $task) {
             $tmp = array();
             $tmp['##task.isprivate##'] = Dropdown::getYesNo($task['is_private']);
             $tmp['##task.author##'] = html_clean(getUserName($task['users_id']));
             $tmp['##task.category##'] = Dropdown::getDropdownName('glpi_taskcategories', $task['taskcategories_id']);
             $tmp['##task.date##'] = convDateTime($task['date']);
             $tmp['##task.description##'] = $task['content'];
             $tmp['##task.time##'] = Ticket::getActionTime($task['actiontime']);
             $plan = new TicketPlanning();
             if ($plan->getFromDBbyTask($task['id'])) {
                 $tmp['##task.planning.user##'] = html_clean(getUserName($plan->fields['users_id']));
                 $tmp['##task.planning.begin##'] = convDateTime($plan->fields['begin']);
                 $tmp['##task.planning.end##'] = convDateTime($plan->fields['end']);
                 $tmp['##task.planning.status##'] = Planning::getState($plan->fields['state']);
             } else {
                 $tmp['##task.planning.user##'] = "";
                 $tmp['##task.planning.begin##'] = "";
                 $tmp['##task.planning.end##'] = "";
                 $tmp['##task.planning.status##'] = "";
             }
             $this->datas['tasks'][] = $tmp;
         }
         if (!empty($this->datas['tasks'])) {
             $this->datas['##ticket.numberoftasks##'] = count($this->datas['tasks']);
         } else {
             $this->datas['##ticket.numberoftasks##'] = 0;
         }
         //Followup infos
         $followups = getAllDatasFromTable('glpi_ticketfollowups', $restrict);
         foreach ($followups as $followup) {
             $tmp = array();
             $tmp['##followup.isprivate##'] = Dropdown::getYesNo($followup['is_private']);
             $tmp['##followup.author##'] = html_clean(getUserName($followup['users_id']));
             $tmp['##followup.requesttype##'] = Dropdown::getDropdownName('glpi_requesttypes', $followup['requesttypes_id']);
             $tmp['##followup.date##'] = convDateTime($followup['date']);
             $tmp['##followup.description##'] = $followup['content'];
             $this->datas['followups'][] = $tmp;
         }
         if (isset($this->datas['followups'])) {
             $this->datas['##ticket.numberoffollowups##'] = count($this->datas['followups']);
         } else {
             $this->datas['##ticket.numberoffollowups##'] = 0;
         }
         //Validation infos
         $restrict = "`tickets_id`='" . $this->obj->getField('id') . "'";
         if (isset($options['validation_id']) && $options['validation_id']) {
             $restrict .= " AND `glpi_ticketvalidations`.`id` = '" . $options['validation_id'] . "'";
         }
         $restrict .= " ORDER BY `submission_date` DESC, `id` ASC";
         $validations = getAllDatasFromTable('glpi_ticketvalidations', $restrict);
         foreach ($validations as $validation) {
             $tmp = array();
             $tmp['##validation.submission.title##'] = $LANG['validation'][27] . " (" . $LANG['job'][4] . " " . html_clean(getUserName($validation['users_id'])) . ")";
             $tmp['##validation.answer.title##'] = $LANG['validation'][32] . " (" . $LANG['validation'][21] . " " . html_clean(getUserName($validation['users_id_validate'])) . ")";
             $tmp['##validation.author##'] = html_clean(getUserName($validation['users_id']));
             $tmp['##validation.status##'] = TicketValidation::getStatus($validation['status']);
             $tmp['##validation.storestatus##'] = $validation['status'];
             $tmp['##validation.submissiondate##'] = convDateTime($validation['submission_date']);
             $tmp['##validation.commentsubmission##'] = $validation['comment_submission'];
             $tmp['##validation.validationdate##'] = convDateTime($validation['validation_date']);
             $tmp['##validation.validator##'] = html_clean(getUserName($validation['users_id_validate']));
             $tmp['##validation.commentvalidation##'] = $validation['comment_validation'];
             $this->datas['validations'][] = $tmp;
         }
         // Ticket Satisfaction
         $inquest = new TicketSatisfaction();
         if ($inquest->getFromDB($this->obj->getField('id'))) {
             // internal inquest
             if ($inquest->fields['type'] == 1) {
                 $this->datas['##ticket.urlsatisfaction##'] = urldecode($CFG_GLPI["url_base"] . "/index.php?redirect=ticket_" . $this->obj->getField("id") . "_10");
                 // external inquest
             } else {
                 if ($inquest->fields['type'] == 2) {
                     $this->datas['##ticket.urlsatisfaction##'] = EntityData::generateLinkSatisfaction($this->obj);
                 }
             }
             $this->datas['##satisfaction.type##'] = $inquest->getTypeInquestName($inquest->getfield('type'));
             $this->datas['##satisfaction.datebegin##'] = convDateTime($inquest->fields['date_begin']);
             $this->datas['##satisfaction.dateanswered##'] = convDateTime($inquest->fields['date_answered']);
             $this->datas['##satisfaction.satisfaction##'] = $inquest->fields['satisfaction'];
             $this->datas['##satisfaction.description##'] = $inquest->fields['comment'];
         } else {
             $this->datas['##satisfaction.type##'] = '';
             $this->datas['##satisfaction.datebegin##'] = '';
             $this->datas['##satisfaction.dateanswered##'] = '';
             $this->datas['##satisfaction.satisfaction##'] = '';
             $this->datas['##satisfaction.description##'] = '';
         }
         // Use list_limit_max or load the full history ?
         foreach (Log::getHistoryData($this->obj, 0, $CFG_GLPI['list_limit_max']) as $data) {
             $tmp = array();
             $tmp['##ticket.log.date##'] = $data['date_mod'];
             $tmp['##ticket.log.user##'] = $data['user_name'];
             $tmp['##ticket.log.field##'] = $data['field'];
             $tmp['##ticket.log.content##'] = $data['change'];
             $this->datas['log'][] = $tmp;
         }
         if (isset($this->datas['log'])) {
             $this->datas['##ticket.numberoflogs##'] = count($this->datas['log']);
         } else {
             $this->datas['##ticket.numberoflogs##'] = 0;
         }
     } else {
         if (isset($options['entities_id']) && isset($options['tickets'])) {
             $this->datas['##ticket.entity##'] = Dropdown::getDropdownName('glpi_entities', $options['entities_id']);
             $this->datas['##ticket.action##'] = $LANG['crontask'][15];
             $t = new Ticket();
             foreach ($options['tickets'] as $ticket) {
                 $tmp = array();
                 $t->getFromDB($ticket['id']);
                 $tmp['##ticket.id##'] = sprintf("%07d", $ticket['id']);
                 $tmp['##ticket.url##'] = urldecode($CFG_GLPI["url_base"] . "/index.php?redirect=ticket_" . $ticket['id']);
                 $tmp['##ticket.title##'] = $ticket['name'];
                 $tmp['##ticket.status##'] = Ticket::getStatus($ticket['status']);
                 $tmp['##ticket.globalvalidation##'] = TicketValidation::getStatus($ticket['global_validation']);
                 $tmp['##ticket.requesttype##'] = Dropdown::getDropdownName('glpi_requesttypes', $ticket['requesttypes_id']);
                 $tmp['##ticket.urgency##'] = Ticket::getUrgencyName($ticket['urgency']);
                 $tmp['##ticket.impact##'] = Ticket::getImpactName($ticket['impact']);
                 $tmp['##ticket.priority##'] = Ticket::getPriorityName($ticket['priority']);
                 $tmp['##ticket.time##'] = Ticket::getActionTime($ticket['actiontime']);
                 $tmp['##ticket.costtime##'] = $ticket['cost_time'];
                 $tmp['##ticket.creationdate##'] = convDateTime($ticket['date']);
                 $tmp['##ticket.content##'] = $ticket['content'];
                 if ($t->getField('ticketsolutiontypes_id')) {
                     $tmp['##ticket.solution.type##'] = Dropdown::getDropdownName('glpi_ticketsolutiontypes', $t->getField('ticketsolutiontypes_id'));
                 } else {
                     $this->datas['##ticket.solution.type##'] = '';
                 }
                 $tmp['##ticket.solution.description##'] = unclean_cross_side_scripting_deep($t->getField('solution'));
                 if ($t->countUsers(Ticket::REQUESTER)) {
                     $users = array();
                     foreach ($t->getUsers(Ticket::REQUESTER) as $uid => $val) {
                         $user_tmp = new User();
                         $user_tmp->getFromDB($uid);
                         $users[$uid] = $user_tmp->getName();
                         $tmp2 = array();
                         $tmp2['##author.id##'] = $uid;
                         $tmp2['##author.name##'] = $user_tmp->getName();
                         if ($user_tmp->getField('locations_id')) {
                             $tmp2['##author.location##'] = Dropdown::getDropdownName('glpi_locations', $user_tmp->getField('locations_id'));
                         } else {
                             $tmp2['##author.location##'] = '';
                         }
                         $tmp2['##author.phone##'] = $user_tmp->getField('phone');
                         $tmp2['##author.phone2##'] = $user_tmp->getField('phone2');
                         $tmp['authors'][] = $tmp2;
                     }
                     $tmp['##ticket.authors##'] = implode(', ', $users);
                 } else {
                     $tmp['##ticket.authors##'] = '';
                 }
                 if ($t->countUsers(Ticket::ASSIGN)) {
                     $users = array();
                     foreach ($t->getUsers(Ticket::ASSIGN) as $uid => $val) {
                         $user_tmp = new User();
                         $user_tmp->getFromDB($uid);
                         $users[$uid] = $user_tmp->getName();
                     }
                     $tmp['##ticket.assigntousers##'] = implode(', ', $users);
                 } else {
                     $tmp['##ticket.assigntousers##'] = '';
                 }
                 if ($t->countGroups(Ticket::ASSIGN)) {
                     $groups = array();
                     foreach ($t->getGroups(Ticket::ASSIGN) as $gid => $val) {
                         $groups[$gid] = Dropdown::getDropdownName('glpi_groups', $gid);
                     }
                     $tmp['##ticket.assigntogroups##'] = implode(', ', $groups);
                 } else {
                     $tmp['##ticket.assigntogroups##'] = '';
                 }
                 if ($t->countGroups(Ticket::REQUESTER)) {
                     $groups = array();
                     foreach ($t->getGroups(Ticket::REQUESTER) as $gid => $val) {
                         $groups[$gid] = Dropdown::getDropdownName('glpi_groups', $gid);
                     }
                     $tmp['##ticket.groups##'] = implode(', ', $groups);
                 } else {
                     $tmp['##ticket.groups##'] = '';
                 }
                 if ($t->countUsers(Ticket::OBSERVER)) {
                     $users = array();
                     foreach ($t->getUsers(Ticket::OBSERVER) as $uid => $tmp) {
                         $user_tmp = new User();
                         $user_tmp->getFromDB($uid);
                         $users[$uid] = $user_tmp->getName();
                     }
                     $tmp['##ticket.observerusers##'] = implode(', ', $users);
                 } else {
                     $tmp['##ticket.observerusers##'] = '';
                 }
                 if ($t->countGroups(Ticket::OBSERVER)) {
                     $groups = array();
                     foreach ($t->getGroups(Ticket::OBSERVER) as $gid => $tmp) {
                         $groups[$gid] = Dropdown::getDropdownName('glpi_groups', $gid);
                     }
                     $tmp['##ticket.observergroups##'] = implode(', ', $groups);
                 } else {
                     $tmp['##ticket.observergroups##'] = '';
                 }
                 if ($ticket['suppliers_id_assign']) {
                     $tmp['##ticket.assigntosupplier##'] = Dropdown::getDropdownName('glpi_suppliers', $ticket['suppliers_id_assign']);
                 } else {
                     $tmp['##ticket.assigntosupplier##'] = '';
                 }
                 $this->datas['tickets'][] = $tmp;
             }
         }
     }
     $this->getTags();
     foreach ($this->tag_descriptions[NotificationTarget::TAG_LANGUAGE] as $tag => $values) {
         if (!isset($this->datas[$tag])) {
             $this->datas[$tag] = $values['label'];
         }
     }
 }
示例#9
0
 /**
  * @since version 0.90
  *
  **/
 function getTimelineItems()
 {
     global $DB, $CFG_GLPI;
     $timeline = array();
     $user = new User();
     $group = new Group();
     $followup_obj = new TicketFollowup();
     $task_obj = new TicketTask();
     $document_item_obj = new Document_Item();
     $ticket_valitation_obj = new TicketValidation();
     //checks rights
     $showpublic = Session::haveRightsOr("followup", array(TicketFollowup::SEEPUBLIC, TicketFollowup::SEEPRIVATE)) || Session::haveRightsOr("task", array(TicketTask::SEEPUBLIC, TicketTask::SEEPRIVATE));
     $restrict_fup = $restrict_task = "";
     if (!Session::haveRight("followup", TicketFollowup::SEEPRIVATE)) {
         $restrict_fup = " AND (`is_private` = '0'\n                                OR `users_id` ='" . Session::getLoginUserID() . "') ";
     }
     if (!Session::haveRight("task", TicketTask::SEEPRIVATE)) {
         $restrict_task = " AND (`is_private` = '0'\n                                 OR `users_id` ='" . Session::getLoginUserID() . "') ";
     }
     if (!$showpublic) {
         $restrict = " AND 1 = 0";
     }
     //add ticket followups to timeline
     if ($followup_obj->canview()) {
         $followups = $followup_obj->find("tickets_id = " . $this->getID() . " {$restrict_fup}", 'date DESC');
         foreach ($followups as $followups_id => $followup) {
             $followup_obj->getFromDB($followups_id);
             $followup['can_edit'] = $followup_obj->canUpdateItem();
             $timeline[$followup['date'] . "_followup_" . $followups_id] = array('type' => 'TicketFollowup', 'item' => $followup);
         }
     }
     //add ticket tasks to timeline
     if ($task_obj->canview()) {
         $tasks = $task_obj->find("tickets_id = " . $this->getID() . " {$restrict_task}", 'date DESC');
         foreach ($tasks as $tasks_id => $task) {
             $task_obj->getFromDB($tasks_id);
             $task['can_edit'] = $task_obj->canUpdateItem();
             $timeline[$task['date'] . "_task_" . $tasks_id] = array('type' => 'TicketTask', 'item' => $task);
         }
     }
     //add ticket documents to timeline
     $document_obj = new Document();
     $document_items = $document_item_obj->find("itemtype = 'Ticket' AND items_id = " . $this->getID());
     foreach ($document_items as $document_item) {
         $document_obj->getFromDB($document_item['documents_id']);
         $timeline[$document_obj->fields['date_mod'] . "_document_" . $document_item['documents_id']] = array('type' => 'Document_Item', 'item' => $document_obj->fields);
     }
     //add existing solution
     if (!empty($this->fields['solution']) || !empty($this->fields['solutiontypes_id'])) {
         $users_id = 0;
         $solution_date = $this->fields['solvedate'];
         //search date and user of last solution in glpi_logs
         if ($res_solution = $DB->query("SELECT `date_mod` AS solution_date, `user_name`, `id`\n                                         FROM `glpi_logs`\n                                         WHERE `itemtype` = 'Ticket'\n                                               AND `items_id` = " . $this->getID() . "\n                                               AND `id_search_option` = 24\n                                         ORDER BY `id` DESC\n                                         LIMIT 1")) {
             $data_solution = $DB->fetch_assoc($res_solution);
             if (!empty($data_solution['solution_date'])) {
                 $solution_date = $data_solution['solution_date'];
             }
             // find user
             if (!empty($data_solution['user_name'])) {
                 $users_id = addslashes(trim(preg_replace("/.*\\(([0-9]+)\\)/", "\$1", $data_solution['user_name'])));
             }
         }
         // fix trouble with html_entity_decode who skip accented characters (on windows browser)
         $solution_content = preg_replace_callback("/(&#[0-9]+;)/", function ($m) {
             return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES");
         }, $this->fields['solution']);
         $timeline[$solution_date . "_solution"] = array('type' => 'Solution', 'item' => array('id' => 0, 'content' => Toolbox::unclean_cross_side_scripting_deep($solution_content), 'date' => $solution_date, 'users_id' => $users_id, 'solutiontypes_id' => $this->fields['solutiontypes_id'], 'can_edit' => Ticket::canUpdate() && $this->canSolve()));
     }
     // add ticket validation to timeline
     if ($this->fields['type'] == Ticket::DEMAND_TYPE && (Session::haveRight('ticketvalidation', TicketValidation::VALIDATEREQUEST) || Session::haveRight('ticketvalidation', TicketValidation::CREATEREQUEST)) || $this->fields['type'] == Ticket::INCIDENT_TYPE && (Session::haveRight('ticketvalidation', TicketValidation::VALIDATEINCIDENT) || Session::haveRight('ticketvalidation', TicketValidation::CREATEINCIDENT))) {
         $ticket_validations = $ticket_valitation_obj->find('tickets_id = ' . $this->getID());
         foreach ($ticket_validations as $validations_id => $validation) {
             $canedit = $ticket_valitation_obj->can($validations_id, UPDATE);
             $user->getFromDB($validation['users_id_validate']);
             $timeline[$validation['submission_date'] . "_validation_" . $validations_id] = array('type' => 'TicketValidation', 'item' => array('id' => $validations_id, 'date' => $validation['submission_date'], 'content' => __('Validation request') . " => " . $user->getlink() . "<br>" . $validation['comment_submission'], 'users_id' => $validation['users_id'], 'can_edit' => $canedit));
             if (!empty($validation['validation_date'])) {
                 $timeline[$validation['validation_date'] . "_validation_" . $validations_id] = array('type' => 'TicketValidation', 'item' => array('id' => $validations_id, 'date' => $validation['validation_date'], 'content' => __('Validation request answer') . " : " . _sx('status', ucfirst(TicketValidation::getStatus($validation['status']))) . "<br>" . $validation['comment_validation'], 'users_id' => $validation['users_id_validate'], 'status' => "status_" . $validation['status'], 'can_edit' => $canedit));
             }
         }
     }
     //reverse sort timeline items by key (date)
     krsort($timeline);
     return $timeline;
 }
示例#10
0
 public function showEquals($searchopt, $value, $edit = true)
 {
     $inputname = $searchopt['linkfield'];
     switch ($searchopt['table'] . "." . $searchopt['linkfield']) {
         case "glpi_tickets.status":
             if ($edit) {
                 Ticket::dropdownStatus($inputname, $value, 1);
             } else {
                 echo Ticket::getStatus($value);
             }
             break;
         case "glpi_tickets.priority":
             if ($edit) {
                 Ticket::dropdownPriority($inputname, $value, true, true);
             } else {
                 echo Ticket::getPriorityName(trim($value));
             }
             break;
         case "glpi_tickets.impact":
             if ($edit) {
                 Ticket::dropdownImpact($inputname, $value, true);
             } else {
                 echo Ticket::getImpactName($value);
             }
             break;
         case "glpi_tickets.urgency":
             if ($edit) {
                 Ticket::dropdownUrgency($inputname, $value, true);
             } else {
                 echo Ticket::getUrgencyName($value);
             }
             break;
         case "glpi_tickets.global_validation":
             if ($edit) {
                 TicketValidation::dropdownStatus($inputname, array('value' => $value, 'all' => 1));
             } else {
                 TicketValidation::getStatus($value);
             }
             break;
         case "glpi_users.name":
             if ($edit) {
                 User::dropdown(array('name' => $inputname, 'value' => $value, 'comments' => false, 'all' => -1, 'right' => 'all'));
             } else {
                 echo getUserName($value);
             }
             break;
         case "glpi_ticketvalidations.status":
             if ($edit) {
                 TicketValidation::dropdownStatus($inputname, array('value' => $value, 'all' => 1));
             } else {
                 echo TicketValidation::getStatus($value);
             }
             break;
     }
 }
示例#11
0
 /**
  * Construct  history for an item
  *
  * @param $item CommonDBTM object
  * @param $oldvalues array of old values updated
  * @param $values array of all values of the item
  *
  * @return boolean for success (at least 1 log entry added)
  **/
 static function constructHistory(CommonDBTM $item, &$oldvalues, &$values)
 {
     global $LANG;
     if (!count($oldvalues)) {
         return false;
     }
     // needed to have  $SEARCHOPTION
     if ($item->getType() == 'TicketSatisfaction') {
         $real_type = 'Ticket';
         $real_id = $item->fields['tickets_id'];
     } else {
         if ($item->getType() == 'Infocom') {
             $real_type = $item->fields['itemtype'];
             $real_id = $item->fields['items_id'];
         } else {
             $real_type = $item->getType();
             $real_id = $item->fields['id'];
         }
     }
     $searchopt = Search::getOptions($real_type);
     if (!is_array($searchopt)) {
         return false;
     }
     $result = 0;
     foreach ($oldvalues as $key => $oldval) {
         $changes = array();
         if ($real_type == 'Infocom') {
             // Parsing $SEARCHOPTION to find infocom
             foreach ($searchopt as $key2 => $val2) {
                 if ($val2["field"] == $key && strpos($val2['table'], 'infocoms') || $key == 'budgets_id' && $val2['table'] == 'glpi_budgets' || $key == 'suppliers_id' && $val2['table'] == 'glpi_suppliers') {
                     $id_search_option = $key2;
                     // Give ID of the $SEARCHOPTION
                     if ($val2["table"] == "glpi_infocoms") {
                         // 1st case : text field -> keep datas
                         $changes = array($id_search_option, addslashes($oldval), $values[$key]);
                     } else {
                         if ($val2["table"] == "glpi_suppliers") {
                             // 2nd case ; link field -> get data from glpi_suppliers
                             $changes = array($id_search_option, addslashes(Dropdown::getDropdownName("glpi_suppliers", $oldval)), addslashes(Dropdown::getDropdownName("glpi_suppliers", $values[$key])));
                         } else {
                             // 3rd case ; link field -> get data from dropdown (budget)
                             $changes = array($id_search_option, addslashes(Dropdown::getDropdownName($val2["table"], $oldval)), addslashes(Dropdown::getDropdownName($val2["table"], $values[$key])));
                         }
                     }
                     break;
                     // foreach exit
                 }
             }
         } else {
             // Not an Infocom
             // Parsing $SEARCHOPTION to find changed field
             foreach ($searchopt as $key2 => $val2) {
                 // Linkfield or standard field not massive action enable
                 if ($val2["linkfield"] == $key || $key == $val2["field"] && $val2["table"] == $item->getTable()) {
                     $id_search_option = $key2;
                     // Give ID of the $SEARCHOPTION
                     // 1st case : Ticket specific dropdown case (without table)
                     if ($real_type == 'Ticket' && in_array($key, array('status', 'urgency', 'impact', 'priority', 'global_validation'))) {
                         switch ($key) {
                             case 'global_validation':
                                 $changes = array($id_search_option, addslashes(TicketValidation::getStatus($oldval)), addslashes(TicketValidation::getStatus($values[$key])));
                                 break;
                             case 'status':
                                 $changes = array($id_search_option, addslashes(Ticket::getStatus($oldval)), addslashes(Ticket::getStatus($values[$key])));
                                 break;
                             case 'urgency':
                                 $changes = array($id_search_option, addslashes(Ticket::getUrgencyName($oldval)), addslashes(Ticket::getUrgencyName($values[$key])));
                                 break;
                             case 'impact':
                                 $changes = array($id_search_option, addslashes(Ticket::getImpactName($oldval)), addslashes(Ticket::getImpactName($values[$key])));
                                 break;
                             case 'priority':
                                 $changes = array($id_search_option, addslashes(Ticket::getPriorityName($oldval)), addslashes(Ticket::getPriorityName($values[$key])));
                                 break;
                         }
                     } else {
                         if ($val2["table"] == $item->getTable()) {
                             // 2nd case : text field -> keep datas
                             $changes = array($id_search_option, addslashes($oldval), $values[$key]);
                         } else {
                             //                      if ($val2['table'] == 'glpi_users_validation') {
                             //                         $val2['table'] = 'glpi_users';
                             //                      }
                             // other cases ; link field -> get data from dropdown
                             if ($val2["table"] != 'glpi_complete_entities') {
                                 $changes = array($id_search_option, addslashes(Dropdown::getDropdownName($val2["table"], $oldval)), addslashes(Dropdown::getDropdownName($val2["table"], $values[$key])));
                             }
                         }
                     }
                     break;
                 }
             }
         }
         if (count($changes)) {
             $result = self::history($real_id, $real_type, $changes);
         }
     }
     return $result;
 }
 static function giveItem($itemtype, $ID, array $data, $num, $meta = 0, array $addobjectparams = array())
 {
     global $CFG_GLPI, $LANG, $PLUGIN_HOOKS;
     $searchopt =& Search::getOptions($itemtype);
     if (isset($CFG_GLPI["union_search_type"][$itemtype]) && $CFG_GLPI["union_search_type"][$itemtype] == $searchopt[$ID]["table"]) {
         return PluginMobileSearch::giveItem($data["TYPE"], $ID, $data, $num, $meta);
     }
     // Plugin can override core definition for its type
     if ($plug = isPluginItemType($itemtype)) {
         $function = 'plugin_' . $plug['plugin'] . '_giveItem';
         if (function_exists($function)) {
             $out = $function($itemtype, $ID, $data, $num);
             if (!empty($out)) {
                 return $out;
             }
         }
     }
     $NAME = "ITEM_";
     if ($meta) {
         $NAME = "META_";
     }
     $table = $searchopt[$ID]["table"];
     $field = $searchopt[$ID]["field"];
     $linkfield = $searchopt[$ID]["linkfield"];
     switch ($table . '.' . $field) {
         case "glpi_users_validation.name":
         case "glpi_users.name":
             // USER search case
             if ($itemtype != 'User' && isset($searchopt[$ID]["forcegroupby"]) && $searchopt[$ID]["forcegroupby"]) {
                 $out = "";
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $count_display = 0;
                 $added = array();
                 for ($k = 0; $k < count($split); $k++) {
                     if ($split[$k] > 0) {
                         if ($count_display) {
                             $out .= "<br>";
                         }
                         $count_display++;
                         if ($itemtype == 'Ticket') {
                             $userdata = getUserNameMobile($split[$k], 2);
                             $out .= $userdata['name'] . "&nbsp;";
                         } else {
                             $out .= getUserNameMobile($split[$k], 1);
                         }
                     }
                 }
                 return $out;
             } else {
                 if (!empty($linkfield)) {
                     $toadd = '';
                     if ($itemtype == 'Ticket' && $data[$NAME . $num . "_3"] > 0) {
                         $userdata = getUserNameMobile($data[$NAME . $num . "_3"], 2);
                         $toadd = "&nbsp;";
                     }
                     //Stevenes
                     $name1 = explode("\$\$", $data[$NAME . $num]);
                     //	return $name1['0'].' ('.$name1['1'].')';
                     $link_user = $_SESSION['mobileSearchLastLink'] = "<a href=" . $CFG_GLPI["root_doc"] . "/plugins/mobile/front/item.php?itemtype=user&menu=admin&ssmenu=user&id=" . $name1['1'] . ">" . $name1['0'] . " (" . $name1['1'] . ")</a>";
                     return $link_user;
                     // return formatUserNameMobile($data[$NAME.$num."_3"],$data[$NAME.$num],$data[$NAME.$num."_2"], $data[$NAME.$num."_4"],1).$toadd;
                 }
             }
             break;
         case "glpi_profiles.interface":
             return Profile::getInterfaceName($data[$NAME . $num]);
             break;
         case "glpi_profiles.name":
             if ($itemtype == 'User') {
                 $out = "";
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $split2 = explode("\$\$\$\$", $data[$NAME . $num . "_2"]);
                 $split3 = explode("\$\$\$\$", $data[$NAME . $num . "_3"]);
                 $count_display = 0;
                 $added = array();
                 for ($k = 0; $k < count($split); $k++) {
                     if (strlen(trim($split[$k])) > 0) {
                         $text = $split[$k] . " - " . $split2[$k];
                         if ($split3[$k]) {
                             $text .= " (R)";
                         }
                         if (!in_array($text, $added)) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= $text;
                             $added[] = $text;
                         }
                     }
                 }
                 return $out;
             }
             break;
         case "glpi_entities.completename":
             if ($itemtype == 'User') {
                 $out = "";
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $split2 = explode("\$\$\$\$", $data[$NAME . $num . "_2"]);
                 $split3 = explode("\$\$\$\$", $data[$NAME . $num . "_3"]);
                 $added = array();
                 $count_display = 0;
                 for ($k = 0; $k < count($split); $k++) {
                     if (strlen(trim($split[$k])) > 0) {
                         $text = $split[$k] . " - " . $split2[$k];
                         if ($split3[$k]) {
                             $text .= " (R)";
                         }
                         if (!in_array($text, $added)) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= $text;
                             $added[] = $text;
                         }
                     }
                 }
                 return $out;
             } else {
                 if ($data[$NAME . $num . "_2"] == 0) {
                     // Set name for Root entity
                     $data[$NAME . $num] = $LANG['entity'][2];
                 }
             }
             break;
         case "glpi_documenttypes.icon":
             if (!empty($data[$NAME . $num])) {
                 return "<img class='middle' alt='' src='" . $CFG_GLPI["typedoc_icon_dir"] . "/" . $data[$NAME . $num] . "'>";
             }
             return "&nbsp;";
         case "glpi_documents.filename":
             $doc = new Document();
             if ($doc->getFromDB($data['id'])) {
                 return $doc->getDownloadLink();
             }
             return NOT_AVAILABLE;
         case "glpi_deviceharddrives.specificity":
         case "glpi_devicememories.specificity":
         case "glpi_deviceprocessors.specificity":
             return $data[$NAME . $num];
         case "glpi_networkports.mac":
             $out = "";
             if ($itemtype == 'Computer') {
                 $displayed = array();
                 if (!empty($data[$NAME . $num . "_2"])) {
                     $split = explode("\$\$\$\$", $data[$NAME . $num . "_2"]);
                     $count_display = 0;
                     for ($k = 0; $k < count($split); $k++) {
                         $lowstr = utf8_strtolower($split[$k]);
                         if (strlen(trim($split[$k])) > 0 && !in_array($lowstr, $displayed)) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= $split[$k];
                             $displayed[] = $lowstr;
                         }
                     }
                     if (!empty($data[$NAME . $num])) {
                         $out .= "<br>";
                     }
                 }
                 if (!empty($data[$NAME . $num])) {
                     $split = explode("\$\$\$\$", $data[$NAME . $num]);
                     $count_display = 0;
                     for ($k = 0; $k < count($split); $k++) {
                         $lowstr = utf8_strtolower($split[$k]);
                         if (strlen(trim($split[$k])) > 0 && !in_array($lowstr, $displayed)) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= $split[$k];
                             $displayed[] = $lowstr;
                         }
                     }
                 }
                 return $out;
             }
             break;
         case "glpi_contracts.duration":
         case "glpi_contracts.notice":
         case "glpi_contracts.periodicity":
         case "glpi_contracts.billing":
             if (!empty($data[$NAME . $num])) {
                 $split = explode('$$$$', $data[$NAME . $num]);
                 $output = "";
                 foreach ($split as $duration) {
                     $output .= (empty($output) ? '' : '<br>') . $duration . " " . $LANG['financial'][57];
                 }
                 return $output;
             }
             return "&nbsp;";
         case "glpi_contracts.renewal":
             return Contract::getContractRenewalName($data[$NAME . $num]);
         case "glpi_infocoms.sink_time":
             if (!empty($data[$NAME . $num])) {
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $out = '';
                 foreach ($split as $val) {
                     $out .= empty($out) ? '' : '<br>';
                     if ($val > 0) {
                         $out .= $val . " " . $LANG['financial'][9];
                     }
                 }
                 return $out;
             }
             return "&nbsp;";
         case "glpi_infocoms.warranty_duration":
             if (!empty($data[$NAME . $num])) {
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $out = '';
                 foreach ($split as $val) {
                     $out .= empty($out) ? '' : '<br>';
                     if ($val > 0) {
                         $out .= $val . " " . $LANG['financial'][57];
                     }
                     if ($val < 0) {
                         $out .= $LANG['financial'][2];
                     }
                 }
                 return $out;
             }
             return "&nbsp;";
         case "glpi_infocoms.sink_type":
             $split = explode("\$\$\$\$", $data[$NAME . $num]);
             $out = '';
             foreach ($split as $val) {
                 $out .= (empty($out) ? '' : '<br>') . Infocom::getAmortTypeName($val);
             }
             return $out;
         case "glpi_infocoms.alert":
             if ($data[$NAME . $num] == pow(2, Alert::END)) {
                 return $LANG['financial'][80];
             }
             return "";
         case "glpi_contracts.alert":
             switch ($data[$NAME . $num]) {
                 case pow(2, Alert::END):
                     return $LANG['buttons'][32];
                 case pow(2, Alert::NOTICE):
                     return $LANG['financial'][10];
                 case pow(2, Alert::END) + pow(2, Alert::NOTICE):
                     return $LANG['buttons'][32] . " + " . $LANG['financial'][10];
             }
             return "";
         case "glpi_tickets.count":
             if ($data[$NAME . $num] > 0 && Session::haveRight("ticket", Ticket::READALL)) {
                 $options['field'][0] = 12;
                 $options['searchtype'][0] = 'equals';
                 $options['contains'][0] = 'all';
                 $options['link'][0] = 'AND';
                 $options['itemtype2'][0] = $itemtype;
                 $options['field2'][0] = self::getOptionNumber($itemtype, 'name');
                 $options['searchtype2'][0] = 'equals';
                 $options['contains2'][0] = $data['id'];
                 $options['link2'][0] = 'AND';
                 $options['reset'] = 'reset';
                 $out = "<a href=\"" . $CFG_GLPI["root_doc"] . "/front/ticket.php?" . Toolbox::append_params($options) . "\" data-back='false'>";
                 $out .= $data[$NAME . $num];
                 $out .= "</a>";
             } else {
                 $out = $data[$NAME . $num];
             }
             return $out;
         case "glpi_softwarelicenses.number":
             if ($data[$NAME . $num . "_2"] == -1) {
                 return $LANG['software'][4];
             }
             if (empty($data[$NAME . $num])) {
                 return 0;
             }
             return $data[$NAME . $num];
         case "glpi_auth_tables.name":
             return Auth::getMethodName($data[$NAME . $num], $data[$NAME . $num . "_2"], 1, $data[$NAME . $num . "_3"] . $data[$NAME . $num . "_4"]);
         case "glpi_reservationitems.comment":
             if (empty($data[$NAME . $num])) {
                 return "<a title='" . $LANG['reservation'][22] . "'\n                        href='" . $CFG_GLPI["root_doc"] . "/front/reservationitem.form.php?id=" . $data["refID"] . "' data-back='false'>" . $LANG['common'][49] . "</a>";
             }
             return "<a title='" . $LANG['reservation'][22] . "'\n                     href='" . $CFG_GLPI["root_doc"] . "/front/reservationitem.form.php?id=" . $data['refID'] . "' data-back='false'>" . resume_text($data[$NAME . $num]) . "</a>";
         case 'glpi_notifications.mode':
             return Notification::getMode($data[$NAME . $num]);
         case 'glpi_notifications.event':
             $item = NotificationTarget::getInstanceByType($data['itemtype']);
             if ($item) {
                 $events = $item->getAllEvents();
                 return $events[$data[$NAME . $num]];
             }
             return '';
         case 'glpi_crontasks.description':
             $tmp = new CronTask();
             return $tmp->getDescription($data['id']);
         case 'glpi_crontasks.state':
             return CronTask::getStateName($data[$NAME . $num]);
         case 'glpi_crontasks.mode':
             return CronTask::getModeName($data[$NAME . $num]);
         case 'glpi_crontasks.itemtype':
             if ($plug = isPluginItemType($data[$NAME . $num])) {
                 return $plug['plugin'];
             }
             return '';
         case 'glpi_tickets.status':
             $status = Ticket::getStatus($data[$NAME . $num]);
             // status Stevenes Donato
             if ($data[$NAME . $num] == "1") {
                 $data[$NAME . $num] = "new";
             }
             if ($data[$NAME . $num] == "2") {
                 $data[$NAME . $num] = "assign";
             }
             if ($data[$NAME . $num] == "3") {
                 $data[$NAME . $num] = "plan";
             }
             if ($data[$NAME . $num] == "4") {
                 $data[$NAME . $num] = "waiting";
             }
             if ($data[$NAME . $num] == "5") {
                 $data[$NAME . $num] = "solved";
             }
             if ($data[$NAME . $num] == "6") {
                 $data[$NAME . $num] = "closed";
             }
             //
             return "<img src=\"" . $CFG_GLPI["root_doc"] . "/pics/" . $data[$NAME . $num] . ".png\"\n                        alt='{$status}' title='{$status}'>&nbsp;{$status}";
         case 'glpi_tickets.priority':
             return Ticket::getPriorityName($data[$NAME . $num]);
         case 'glpi_tickets.urgency':
             return Ticket::getUrgencyName($data[$NAME . $num]);
         case 'glpi_tickets.impact':
             return Ticket::getImpactName($data[$NAME . $num]);
         case 'glpi_tickets.items_id':
             if (!empty($data[$NAME . $num . "_2"]) && class_exists($data[$NAME . $num . "_2"])) {
                 $item = new $data[$NAME . $num . "_2"]();
                 if ($item->getFromDB($data[$NAME . $num])) {
                     return $item->getLink(true);
                 }
             }
             return '&nbsp;';
         case 'glpi_tickets.id':
             $link = getItemTypeFormURLMobile('Ticket');
             $out = "<a id='ticket" . $data[$NAME . $num . "_2"] . "' href=\"" . $link;
             $out .= strstr($link, '?') ? '&amp;' : '?';
             $out .= 'id=' . $data[$NAME . $num];
             //$out .= 'id='.$data[$NAME.$num."_2"];
             $out .= "\" data-back='false'>" . $data[$NAME . $num];
             if ($_SESSION["glpiis_ids_visible"] || empty($data[$NAME . $num])) {
                 //$out .= " (".$data[$NAME.$num."_2"].")";
                 $out .= $data[$NAME . $num . "_2"];
             }
             $out .= "</a>";
             return $out;
         case 'glpi_ticketvalidations.status':
         case "glpi_tickets.global_validation":
             $split = explode("\$\$\$\$", $data[$NAME . $num]);
             $out = '';
             foreach ($split as $val) {
                 $status = TicketValidation::getStatus($val);
                 $bgcolor = TicketValidation::getStatusColor($val);
                 $out .= (empty($out) ? '' : '<br>') . "<div style=\"background-color:" . $bgcolor . ";\">" . $status . '</div>';
             }
             return $out;
         case 'glpi_notimportedemails.reason':
             return NotImportedEmail::getReason($data[$NAME . $num]);
         case 'glpi_notimportedemails.messageid':
             $clean = array('<' => '', '>' => '');
             return strtr($data[$NAME . $num], $clean);
     }
     //// Default case
     // Link with plugin tables : need to know left join structure
     if (preg_match("/^glpi_plugin_([a-z0-9]+)/", $table . '.' . $field, $matches)) {
         if (count($matches) == 2) {
             $plug = $matches[1];
             $function = 'plugin_' . $plug . '_giveItem';
             if (function_exists($function)) {
                 $out = $function($itemtype, $ID, $data, $num);
                 if (!empty($out)) {
                     return $out;
                 }
             }
         }
     }
     $unit = '';
     if (isset($searchopt[$ID]['unit'])) {
         $unit = $searchopt[$ID]['unit'];
     }
     // Preformat items
     if (isset($searchopt[$ID]["datatype"])) {
         switch ($searchopt[$ID]["datatype"]) {
             case "itemlink":
                 if (!empty($data[$NAME . $num . "_2"])) {
                     if (isset($searchopt[$ID]["itemlink_type"])) {
                         $link = getItemTypeFormURLMobile($searchopt[$ID]["itemlink_type"]);
                     } else {
                         $link = getItemTypeFormURLMobile($itemtype);
                     }
                     $out = "<a id='" . $itemtype . "_" . $data[$NAME . $num . "_2"] . "' href=\"" . $link;
                     $out .= strstr($link, '?') ? '&amp;' : '?';
                     $out .= 'id=' . $data[$NAME . $num . "_2"] . "\" data-back='false'>";
                     $out .= $data[$NAME . $num] . $unit;
                     if ($_SESSION["glpiis_ids_visible"] || empty($data[$NAME . $num])) {
                         $out .= " (" . $data[$NAME . $num . "_2"] . ")";
                     }
                     $out .= "</a>";
                     return $out;
                 } else {
                     if (isset($searchopt[$ID]["itemlink_type"])) {
                         $out = "";
                         $split = explode("\$\$\$\$", $data[$NAME . $num]);
                         $count_display = 0;
                         $separate = '<br>';
                         if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) {
                             $separate = '<hr>';
                         }
                         for ($k = 0; $k < count($split); $k++) {
                             if (strlen(trim($split[$k])) > 0) {
                                 $split2 = explode("\$\$", $split[$k]);
                                 if (isset($split2[1]) && $split2[1] > 0) {
                                     if ($count_display) {
                                         $out .= $separate;
                                     }
                                     $count_display++;
                                     $page = getItemTypeFormURLMobile($searchopt[$ID]["itemlink_type"]);
                                     $page .= strpos($page, '?') ? '&id' : '?id';
                                     $out .= "<a id='" . $searchopt[$ID]["itemlink_type"] . "_" . $split2[1] . "'\n                                       href='{$page}=" . $split2[1] . "' data-back='false'>";
                                     $out .= $split2[0] . $unit;
                                     if ($_SESSION["glpiis_ids_visible"] || empty($split2[0])) {
                                         $out .= " (" . $split2[1] . ")";
                                     }
                                     $out .= "</a>";
                                 }
                             }
                         }
                         return $out;
                     }
                 }
                 break;
             case "text":
                 $separate = '<br>';
                 if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) {
                     $separate = '<hr>';
                 }
                 return str_replace('$$$$', $separate, nl2br($data[$NAME . $num]));
             case "date":
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $out = '';
                 foreach ($split as $val) {
                     $out .= (empty($out) ? '' : '<br>') . convDate($val);
                 }
                 return $out;
             case "datetime":
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $out = '';
                 foreach ($split as $val) {
                     $out .= (empty($out) ? '' : '<br>') . Html::convDateTime($val);
                 }
                 return $out;
             case "timestamp":
                 return timestampToString($data[$NAME . $num]);
             case "realtime":
                 return Ticket::getRealtime($data[$NAME . $num]);
             case "date_delay":
                 $split = explode('$$$$', $data[$NAME . $num]);
                 $out = '';
                 foreach ($split as $val) {
                     if (strpos($val, ',')) {
                         list($dat, $dur) = explode(',', $val);
                         if (!empty($dat)) {
                             $out .= (empty($out) ? '' : '<br>') . getWarrantyExpir($dat, $dur);
                         }
                     }
                 }
                 return empty($out) ? "&nbsp;" : $out;
             case "email":
                 // Stevenes
                 //               $email=trim($data[$NAME.$num]);
                 $email = explode('$$', $data[$NAME . $num]);
                 if (!empty($email['0'])) {
                     return $email['0'];
                     //return "<a href='mailto:$email'>$email</a>";
                 }
                 return "&nbsp;";
             case "weblink":
                 $orig_link = trim($data[$NAME . $num]);
                 if (!empty($orig_link)) {
                     // strip begin of link
                     $link = preg_replace('/https?:\\/\\/(www[^\\.]*\\.)?/', '', $orig_link);
                     $link = preg_replace('/\\/$/', '', $link);
                     if (utf8_strlen($link) > 30) {
                         $link = Toolbox::substr($link, 0, 30) . "...";
                     }
                     //return "<a href=\"".formatOutputWebLink($orig_link)."\" target='_blank'>$link</a>";
                     return $orig_link;
                 }
                 return "&nbsp;";
             case "number":
                 if (isset($searchopt[$ID]['forcegroupby']) && $searchopt[$ID]['forcegroupby']) {
                     $out = "";
                     $split = explode("\$\$\$\$", $data[$NAME . $num]);
                     $count_display = 0;
                     for ($k = 0; $k < count($split); $k++) {
                         if (strlen(trim($split[$k])) > 0) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= str_replace(' ', '&nbsp;', Html::formatNumber($split[$k], false, 0)) . $unit;
                         }
                     }
                     return $out;
                 }
                 return str_replace(' ', '&nbsp;', Html::formatNumber($data[$NAME . $num], false, 0)) . $unit;
             case "decimal":
                 if (isset($searchopt[$ID]['forcegroupby']) && $searchopt[$ID]['forcegroupby']) {
                     $out = "";
                     $split = explode("\$\$\$\$", $data[$NAME . $num]);
                     $count_display = 0;
                     for ($k = 0; $k < count($split); $k++) {
                         if (strlen(trim($split[$k])) > 0) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= str_replace(' ', '&nbsp;', Html::formatNumber($split[$k])) . $unit;
                         }
                     }
                     return $out;
                 }
                 return str_replace(' ', '&nbsp;', Html::formatNumber($data[$NAME . $num])) . $unit;
             case "bool":
                 return Dropdown::getYesNo($data[$NAME . $num]) . $unit;
             case "right":
                 return Profile::getRightValue($data[$NAME . $num]);
             case "itemtypename":
                 if (class_exists($data[$NAME . $num])) {
                     $obj = new $data[$NAME . $num]();
                     return $obj->getTypeName();
                 } else {
                     return "";
                 }
             case "language":
                 if (isset($CFG_GLPI['languages'][$data[$NAME . $num]])) {
                     return $CFG_GLPI['languages'][$data[$NAME . $num]][0];
                 } else {
                     return $LANG['setup'][46];
                 }
                 break;
         }
     }
     // Manage items with need group by / group_concat
     if (isset($searchopt[$ID]['forcegroupby']) && $searchopt[$ID]['forcegroupby']) {
         $out = "";
         $split = explode("\$\$\$\$", $data[$NAME . $num]);
         $count_display = 0;
         $separate = '<br>';
         if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) {
             $separate = '<hr>';
         }
         for ($k = 0; $k < count($split); $k++) {
             if (strlen(trim($split[$k])) > 0) {
                 if ($count_display) {
                     $out .= $separate;
                 }
                 $count_display++;
                 $out .= $split[$k] . $unit;
             }
         }
         return $out;
     }
     return $data[$NAME . $num] . $unit;
 }
 /**
  * Get all data needed for template processing
  *
  * @param $event
  * @param $options array
  **/
 function getDatasForTemplate($event, $options = array())
 {
     global $CFG_GLPI;
     $events = $this->getAllEvents();
     $objettype = strtolower($this->obj->getType());
     // Get datas from ITIL objects
     if ($event != 'alertnotclosed') {
         $this->datas = $this->getDatasForObject($this->obj, $options);
     } else {
         if (isset($options['entities_id']) && isset($options['items'])) {
             $entity = new Entity();
             if ($entity->getFromDB($options['entities_id'])) {
                 $this->datas["##{$objettype}.entity##"] = $entity->getField('completename');
                 $this->datas["##{$objettype}.shortentity##"] = $entity->getField('name');
             }
             if ($item = getItemForItemtype($objettype)) {
                 $objettypes = Toolbox::strtolower(getPlural($objettype));
                 $items = array();
                 foreach ($options['items'] as $object) {
                     $item->getFromDB($object['id']);
                     $tmp = $this->getDatasForObject($item, $options, true);
                     $this->datas[$objettypes][] = $tmp;
                 }
             }
         }
     }
     if ($event == 'validation' && isset($options['validation_status'])) {
         $this->datas["##{$objettype}.action##"] = sprintf(__('%1$s - %2$s'), __('Approval'), TicketValidation::getStatus($options['validation_status']));
     } else {
         $this->datas["##{$objettype}.action##"] = $events[$event];
     }
     $this->getTags();
     foreach ($this->tag_descriptions[parent::TAG_LANGUAGE] as $tag => $values) {
         if (!isset($this->datas[$tag])) {
             $this->datas[$tag] = $values['label'];
         }
     }
 }
示例#14
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 ?
  *
  * @return string to print
  **/
 static function giveItem($itemtype, $ID, $data, $num, $meta = 0)
 {
     global $CFG_GLPI, $LANG;
     $searchopt =& self::getOptions($itemtype);
     if (isset($CFG_GLPI["union_search_type"][$itemtype]) && $CFG_GLPI["union_search_type"][$itemtype] == $searchopt[$ID]["table"]) {
         return self::giveItem($data["TYPE"], $ID, $data, $num, $meta);
     }
     // Plugin can override core definition for its type
     if ($plug = isPluginItemType($itemtype)) {
         $function = 'plugin_' . $plug['plugin'] . '_giveItem';
         if (function_exists($function)) {
             $out = $function($itemtype, $ID, $data, $num);
             if (!empty($out)) {
                 return $out;
             }
         }
     }
     $NAME = "ITEM_";
     if ($meta) {
         $NAME = "META_";
     }
     $table = $searchopt[$ID]["table"];
     $field = $searchopt[$ID]["field"];
     $linkfield = $searchopt[$ID]["linkfield"];
     switch ($table . '.' . $field) {
         case "glpi_users.name":
             // USER search case
             if ($itemtype != 'User' && isset($searchopt[$ID]["forcegroupby"]) && $searchopt[$ID]["forcegroupby"]) {
                 $out = "";
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $count_display = 0;
                 $added = array();
                 for ($k = 0; $k < count($split); $k++) {
                     if ($split[$k] > 0) {
                         if ($count_display) {
                             $out .= "<br>";
                         }
                         $count_display++;
                         if ($itemtype == 'Ticket') {
                             $userdata = getUserName($split[$k], 2);
                             $out .= $userdata['name'] . "&nbsp;" . showToolTip($userdata["comment"], array('link' => $userdata["link"], 'display' => false));
                         } else {
                             $out .= getUserName($split[$k], 1);
                         }
                     }
                 }
                 // Manage alternative_email for tickets_users
                 if ($itemtype == 'Ticket' && isset($data[$NAME . $num . '_2'])) {
                     $split = explode("\$\$\$\$", $data[$NAME . $num . '_2']);
                     for ($k = 0; $k < count($split); $k++) {
                         $split2 = explode(" ", $split[$k]);
                         if (count($split2) == 2 && $split2[0] == 0 && !empty($split2[1])) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= "<a href='mailto:" . $split2[1] . "'>" . $split2[1] . "</a>";
                         }
                     }
                 }
                 return $out;
             }
             if ($itemtype != 'User') {
                 $toadd = '';
                 if ($itemtype == 'Ticket' && $data[$NAME . $num . "_3"] > 0) {
                     $userdata = getUserName($data[$NAME . $num . "_3"], 2);
                     $toadd = "&nbsp;" . showToolTip($userdata["comment"], array('link' => $userdata["link"], 'display' => false));
                 }
                 return formatUserName($data[$NAME . $num . "_3"], $data[$NAME . $num], $data[$NAME . $num . "_2"], $data[$NAME . $num . "_4"], 1) . $toadd;
             }
             break;
         case "glpi_profiles.interface":
             return Profile::getInterfaceName($data[$NAME . $num]);
         case "glpi_profiles.name":
             if ($itemtype == 'User' && $ID == 20) {
                 $out = "";
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $split2 = explode("\$\$\$\$", $data[$NAME . $num . "_2"]);
                 $split3 = explode("\$\$\$\$", $data[$NAME . $num . "_3"]);
                 $count_display = 0;
                 $added = array();
                 for ($k = 0; $k < count($split); $k++) {
                     if (strlen(trim($split[$k])) > 0) {
                         $text = $split[$k] . " - " . Dropdown::getDropdownName('glpi_entities', $split2[$k]);
                         if ($split3[$k]) {
                             $text .= " (R)";
                         }
                         if (!in_array($text, $added)) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= $text;
                             $added[] = $text;
                         }
                     }
                 }
                 return $out;
             }
             break;
         case "glpi_complete_entities.completename":
             if ($itemtype == 'User') {
                 $out = "";
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $split2 = explode("\$\$\$\$", $data[$NAME . $num . "_2"]);
                 $split3 = explode("\$\$\$\$", $data[$NAME . $num . "_3"]);
                 $added = array();
                 $count_display = 0;
                 for ($k = 0; $k < count($split); $k++) {
                     if (strlen(trim($split[$k])) > 0) {
                         $text = $split[$k] . " - " . Dropdown::getDropdownName('glpi_profiles', $split2[$k]);
                         if ($split3[$k]) {
                             $text .= " (R)";
                         }
                         if (!in_array($text, $added)) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= $text;
                             $added[] = $text;
                         }
                     }
                 }
                 return $out;
             }
             break;
         case "glpi_entities.completename":
             if ($data[$NAME . $num . "_2"] == 0) {
                 // Set name for Root entity
                 $data[$NAME . $num] = $LANG['entity'][2];
             }
             break;
         case "glpi_documenttypes.icon":
             if (!empty($data[$NAME . $num])) {
                 return "<img class='middle' alt='' src='" . $CFG_GLPI["typedoc_icon_dir"] . "/" . $data[$NAME . $num] . "'>";
             }
             return "&nbsp;";
         case "glpi_documents.filename":
             $doc = new Document();
             if ($doc->getFromDB($data['id'])) {
                 return $doc->getDownloadLink();
             }
             return NOT_AVAILABLE;
         case "glpi_deviceharddrives.specificity":
         case "glpi_devicememories.specificity":
         case "glpi_deviceprocessors.specificity":
             return $data[$NAME . $num];
         case "glpi_networkports.mac":
             $out = "";
             if ($itemtype == 'Computer') {
                 $displayed = array();
                 if (!empty($data[$NAME . $num . "_2"])) {
                     $split = explode("\$\$\$\$", $data[$NAME . $num . "_2"]);
                     $count_display = 0;
                     for ($k = 0; $k < count($split); $k++) {
                         $lowstr = utf8_strtolower($split[$k]);
                         if (strlen(trim($split[$k])) > 0 && !in_array($lowstr, $displayed)) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= $split[$k];
                             $displayed[] = $lowstr;
                         }
                     }
                     if (!empty($data[$NAME . $num])) {
                         $out .= "<br>";
                     }
                 }
                 if (!empty($data[$NAME . $num])) {
                     $split = explode("\$\$\$\$", $data[$NAME . $num]);
                     $count_display = 0;
                     for ($k = 0; $k < count($split); $k++) {
                         $lowstr = utf8_strtolower($split[$k]);
                         if (strlen(trim($split[$k])) > 0 && !in_array($lowstr, $displayed)) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= $split[$k];
                             $displayed[] = $lowstr;
                         }
                     }
                 }
                 return $out;
             }
             break;
         case "glpi_contracts.duration":
         case "glpi_contracts.notice":
         case "glpi_contracts.periodicity":
         case "glpi_contracts.billing":
             if (!empty($data[$NAME . $num])) {
                 $split = explode('$$$$', $data[$NAME . $num]);
                 $output = "";
                 foreach ($split as $duration) {
                     $output .= (empty($output) ? '' : '<br>') . $duration . " " . $LANG['financial'][57];
                 }
                 return $output;
             }
             return "&nbsp;";
         case "glpi_contracts.renewal":
             return Contract::getContractRenewalName($data[$NAME . $num]);
         case "glpi_infocoms.sink_time":
             if (!empty($data[$NAME . $num])) {
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $out = '';
                 foreach ($split as $val) {
                     $out .= empty($out) ? '' : '<br>';
                     if ($val > 0) {
                         $out .= $val . " " . $LANG['financial'][9];
                     }
                 }
                 return $out;
             }
             return "&nbsp;";
         case "glpi_infocoms.warranty_duration":
             if (!empty($data[$NAME . $num])) {
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $out = '';
                 foreach ($split as $val) {
                     $out .= empty($out) ? '' : '<br>';
                     if ($val > 0) {
                         $out .= $val . " " . $LANG['financial'][57];
                     }
                     if ($val < 0) {
                         $out .= $LANG['financial'][2];
                     }
                 }
                 return $out;
             }
             return "&nbsp;";
         case "glpi_infocoms.sink_type":
             $split = explode("\$\$\$\$", $data[$NAME . $num]);
             $out = '';
             foreach ($split as $val) {
                 $out .= (empty($out) ? '' : '<br>') . Infocom::getAmortTypeName($val);
             }
             return $out;
         case "glpi_infocoms.alert":
             if ($data[$NAME . $num] == pow(2, Alert::END)) {
                 return $LANG['financial'][80];
             }
             return "";
         case "glpi_contracts.alert":
             switch ($data[$NAME . $num]) {
                 case pow(2, Alert::END):
                     return $LANG['buttons'][32];
                 case pow(2, Alert::NOTICE):
                     return $LANG['financial'][10];
                 case pow(2, Alert::END) + pow(2, Alert::NOTICE):
                     return $LANG['buttons'][32] . " + " . $LANG['financial'][10];
             }
             return "";
         case "glpi_tickets_tickets.tickets_id_1":
             $out = "";
             $split = explode("\$\$\$\$", $data[$NAME . $num]);
             $split2 = explode("\$\$\$\$", $data[$NAME . $num . "_2"]);
             $displayed = array();
             for ($k = 0; $k < count($split); $k++) {
                 $linkid = $split[$k] == $data['id'] ? $split2[$k] : $split[$k];
                 if ($linkid > 0 && !isset($displayed[$linkid])) {
                     $text = $linkid . " - " . Dropdown::getDropdownName('glpi_tickets', $linkid);
                     if (count($displayed)) {
                         $out .= "<br>";
                     }
                     $displayed[$linkid] = $linkid;
                     $out .= $text;
                 }
             }
             return $out;
         case "glpi_tickets.count":
             if ($data[$NAME . $num] > 0 && haveRight("show_all_ticket", "1")) {
                 if ($itemtype == 'User') {
                     $options['field'][0] = 4;
                     $options['searchtype'][0] = 'equals';
                     $options['contains'][0] = $data['id'];
                     $options['link'][0] = 'AND';
                     $options['field'][1] = 22;
                     $options['searchtype'][1] = 'equals';
                     $options['contains'][1] = $data['id'];
                     $options['link'][1] = 'OR';
                     $options['field'][2] = 5;
                     $options['searchtype'][2] = 'equals';
                     $options['contains'][2] = $data['id'];
                     $options['link'][2] = 'OR';
                 } else {
                     $options['field'][0] = 12;
                     $options['searchtype'][0] = 'equals';
                     $options['contains'][0] = 'all';
                     $options['link'][0] = 'AND';
                     $options['itemtype2'][0] = $itemtype;
                     $options['field2'][0] = self::getOptionNumber($itemtype, 'name');
                     $options['searchtype2'][0] = 'equals';
                     $options['contains2'][0] = $data['id'];
                     $options['link2'][0] = 'AND';
                 }
                 $options['reset'] = 'reset';
                 $out = "<a id='ticket{$itemtype}" . $data['id'] . "' ";
                 $out .= "href=\"" . $CFG_GLPI["root_doc"] . "/front/ticket.php?" . append_params($options, '&amp;') . "\">";
                 $out .= $data[$NAME . $num] . "</a>";
             } else {
                 $out = $data[$NAME . $num];
             }
             return $out;
         case "glpi_softwarelicenses.number":
             if ($data[$NAME . $num . "_2"] == -1) {
                 return $LANG['software'][4];
             }
             if (empty($data[$NAME . $num])) {
                 return 0;
             }
             return $data[$NAME . $num];
         case "glpi_auth_tables.name":
             return Auth::getMethodName($data[$NAME . $num], $data[$NAME . $num . "_2"], 1, $data[$NAME . $num . "_3"] . $data[$NAME . $num . "_4"]);
         case "glpi_reservationitems.comment":
             if (empty($data[$NAME . $num])) {
                 return "<a title=\"" . $LANG['reservation'][22] . "\"\n                        href='" . $CFG_GLPI["root_doc"] . "/front/reservationitem.form.php?id=" . $data["refID"] . "' >" . $LANG['common'][49] . "</a>";
             }
             return "<a title=\"" . $LANG['reservation'][22] . "\"\n                     href='" . $CFG_GLPI["root_doc"] . "/front/reservationitem.form.php?id=" . $data['refID'] . "' >" . resume_text($data[$NAME . $num]) . "</a>";
         case 'glpi_notifications.mode':
             return Notification::getMode($data[$NAME . $num]);
         case 'glpi_notifications.event':
             $item = NotificationTarget::getInstanceByType($data['itemtype']);
             if ($item) {
                 $events = $item->getAllEvents();
                 return $events[$data[$NAME . $num]];
             }
             return '';
         case 'glpi_crontasks.description':
             $tmp = new CronTask();
             return $tmp->getDescription($data['id']);
         case 'glpi_crontasks.state':
             return CronTask::getStateName($data[$NAME . $num]);
         case 'glpi_crontasks.mode':
             return CronTask::getModeName($data[$NAME . $num]);
         case 'glpi_crontasks.itemtype':
             if ($plug = isPluginItemType($data[$NAME . $num])) {
                 return $plug['plugin'];
             }
             return '';
         case 'glpi_tickets.status':
             $status = Ticket::getStatus($data[$NAME . $num]);
             return "<img src=\"" . $CFG_GLPI["root_doc"] . "/pics/" . $data[$NAME . $num] . ".png\"\n                     alt=\"{$status}\" title=\"{$status}\">&nbsp;{$status}";
         case 'glpi_tickets.type':
             return Ticket::getTicketTypeName($data[$NAME . $num]);
         case 'glpi_tickets.priority':
             return Ticket::getPriorityName($data[$NAME . $num]);
         case 'glpi_tickets.urgency':
             return Ticket::getUrgencyName($data[$NAME . $num]);
         case 'glpi_tickets.impact':
             return Ticket::getImpactName($data[$NAME . $num]);
         case 'glpi_tickets.items_id':
             if (!empty($data[$NAME . $num . "_2"]) && class_exists($data[$NAME . $num . "_2"])) {
                 $item = new $data[$NAME . $num . "_2"]();
                 if ($item->getFromDB($data[$NAME . $num])) {
                     return $item->getLink(true);
                 }
             }
             return '&nbsp;';
         case 'glpi_tickets.name':
             $link = getItemTypeFormURL('Ticket');
             $out = "<a id='ticket" . $data[$NAME . $num . "_2"] . "' href=\"" . $link;
             $out .= strstr($link, '?') ? '&amp;' : '?';
             $out .= 'id=' . $data[$NAME . $num . "_2"];
             // Force solution tab if solved
             if ($data[$NAME . $num . "_4"] == 'solved') {
                 $out .= "&amp;forcetab=4";
             }
             $out .= "\">" . $data[$NAME . $num];
             if ($_SESSION["glpiis_ids_visible"] || empty($data[$NAME . $num])) {
                 $out .= " (" . $data[$NAME . $num . "_2"] . ")";
             }
             $out .= "</a>";
             $out .= showToolTip(nl2br($data[$NAME . $num . "_3"]), array('applyto' => 'ticket' . $data[$NAME . $num . "_2"], 'display' => false));
             return $out;
         case "glpi_tickets.due_date":
             // No due date in waiting status
             if ($data[$NAME . $num . '_2'] == 'waiting') {
                 $data[$NAME . $num] = "";
             }
             break;
         case 'glpi_ticketvalidations.status':
         case "glpi_tickets.global_validation":
             $split = explode("\$\$\$\$", $data[$NAME . $num]);
             $out = '';
             foreach ($split as $val) {
                 $status = TicketValidation::getStatus($val);
                 $bgcolor = TicketValidation::getStatusColor($val);
                 $out .= (empty($out) ? '' : '<br>') . "<div style=\"background-color:" . $bgcolor . ";\">" . $status . '</div>';
             }
             return $out;
         case 'glpi_ticketsatisfactions.type':
             return TicketSatisfaction::getTypeInquestName($data[$NAME . $num]);
         case 'glpi_ticketsatisfactions.satisfaction':
             return TicketSatisfaction::displaySatisfaction($data[$NAME . $num]);
         case 'glpi_notimportedemails.reason':
             return NotImportedEmail::getReason($data[$NAME . $num]);
         case 'glpi_notimportedemails.messageid':
             $clean = array('<' => '', '>' => '');
             return strtr($data[$NAME . $num], $clean);
         case 'glpi_fieldunicities.fields':
             $values = explode(',', $data[$NAME . $num]);
             $item = new $data['ITEMTYPE']();
             $message = array();
             foreach ($values as $field) {
                 $table = getTableNameForForeignKeyField($field);
                 if ($table != '') {
                     $searchOption = $item->getSearchOptionByField('field', 'name', $table);
                 } else {
                     $searchOption = $item->getSearchOptionByField('field', $field);
                 }
                 $message[] = $searchOption['name'];
             }
             return implode(',', $message);
     }
     //// Default case
     // Link with plugin tables : need to know left join structure
     if (preg_match("/^glpi_plugin_([a-z0-9]+)/", $table . '.' . $field, $matches)) {
         if (count($matches) == 2) {
             $plug = $matches[1];
             $function = 'plugin_' . $plug . '_giveItem';
             if (function_exists($function)) {
                 $out = $function($itemtype, $ID, $data, $num);
                 if (!empty($out)) {
                     return $out;
                 }
             }
         }
     }
     $unit = '';
     if (isset($searchopt[$ID]['unit'])) {
         $unit = $searchopt[$ID]['unit'];
     }
     // Preformat items
     if (isset($searchopt[$ID]["datatype"])) {
         switch ($searchopt[$ID]["datatype"]) {
             case "itemlink":
                 if (!empty($data[$NAME . $num . "_2"])) {
                     if (isset($searchopt[$ID]["itemlink_type"])) {
                         $link = getItemTypeFormURL($searchopt[$ID]["itemlink_type"]);
                     } else {
                         $link = getItemTypeFormURL($itemtype);
                     }
                     $out = "<a id='" . $itemtype . "_" . $data[$NAME . $num . "_2"] . "' href=\"" . $link;
                     $out .= strstr($link, '?') ? '&amp;' : '?';
                     $out .= 'id=' . $data[$NAME . $num . "_2"] . "\">" . $data[$NAME . $num] . $unit;
                     if ($_SESSION["glpiis_ids_visible"] || empty($data[$NAME . $num])) {
                         $out .= " (" . $data[$NAME . $num . "_2"] . ")";
                     }
                     $out .= "</a>";
                     return $out;
                 }
                 if (isset($searchopt[$ID]["itemlink_type"])) {
                     $out = "";
                     $split = explode("\$\$\$\$", $data[$NAME . $num]);
                     $count_display = 0;
                     $separate = '<br>';
                     if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) {
                         $separate = '<hr>';
                     }
                     for ($k = 0; $k < count($split); $k++) {
                         if (strlen(trim($split[$k])) > 0) {
                             $split2 = explode("\$\$", $split[$k]);
                             if (isset($split2[1]) && $split2[1] > 0) {
                                 if ($count_display) {
                                     $out .= $separate;
                                 }
                                 $count_display++;
                                 $page = getItemTypeFormURL($searchopt[$ID]["itemlink_type"]);
                                 $page .= strpos($page, '?') ? '&id' : '?id';
                                 $out .= "<a id='" . $searchopt[$ID]["itemlink_type"] . "_" . $data['id'] . "_" . $split2[1] . "' href='{$page}=" . $split2[1] . "'>" . $split2[0] . $unit;
                                 if ($_SESSION["glpiis_ids_visible"] || empty($split2[0])) {
                                     $out .= " (" . $split2[1] . ")";
                                 }
                                 $out .= "</a>";
                             }
                         }
                     }
                     return $out;
                 }
                 break;
             case "text":
                 $separate = '<br>';
                 if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) {
                     $separate = '<hr>';
                 }
                 $text = str_replace('$$$$', $separate, nl2br($data[$NAME . $num]));
                 if (isset($searchopt[$ID]['htmltext']) && $searchopt[$ID]['htmltext']) {
                     $text = html_clean(unclean_cross_side_scripting_deep($text));
                 }
                 return $text;
             case "date":
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $out = '';
                 foreach ($split as $val) {
                     $out .= (empty($out) ? '' : '<br>') . convDate($val);
                 }
                 return $out;
             case "datetime":
                 $split = explode("\$\$\$\$", $data[$NAME . $num]);
                 $out = '';
                 foreach ($split as $val) {
                     $out .= (empty($out) ? '' : '<br>') . convDateTime($val);
                 }
                 return $out;
             case "timestamp":
                 $withseconds = false;
                 if (isset($searchopt[$ID]['withseconds'])) {
                     $withseconds = $searchopt[$ID]['withseconds'];
                 }
                 return timestampToString($data[$NAME . $num], $withseconds);
             case "date_delay":
                 $split = explode('$$$$', $data[$NAME . $num]);
                 $out = '';
                 foreach ($split as $val) {
                     if (strpos($val, ',')) {
                         list($dat, $dur) = explode(',', $val);
                         if (!empty($dat)) {
                             $out .= (empty($out) ? '' : '<br>') . getWarrantyExpir($dat, $dur);
                         }
                     }
                 }
                 return empty($out) ? "&nbsp;" : $out;
             case "email":
                 $email = trim($data[$NAME . $num]);
                 if (!empty($email)) {
                     return "<a href='mailto:{$email}'>{$email}</a>";
                 }
                 return "&nbsp;";
             case "weblink":
                 $orig_link = trim($data[$NAME . $num]);
                 if (!empty($orig_link)) {
                     // strip begin of link
                     $link = preg_replace('/https?:\\/\\/(www[^\\.]*\\.)?/', '', $orig_link);
                     $link = preg_replace('/\\/$/', '', $link);
                     if (utf8_strlen($link) > $CFG_GLPI["url_maxlength"]) {
                         $link = utf8_substr($link, 0, $CFG_GLPI["url_maxlength"]) . "...";
                     }
                     return "<a href=\"" . formatOutputWebLink($orig_link) . "\" target='_blank'>{$link}</a>";
                 }
                 return "&nbsp;";
             case "number":
                 if (isset($searchopt[$ID]['forcegroupby']) && $searchopt[$ID]['forcegroupby']) {
                     $out = "";
                     $split = explode("\$\$\$\$", $data[$NAME . $num]);
                     $count_display = 0;
                     for ($k = 0; $k < count($split); $k++) {
                         if (strlen(trim($split[$k])) > 0) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= str_replace(' ', '&nbsp;', formatNumber($split[$k], false, 0)) . $unit;
                         }
                     }
                     return $out;
                 }
                 return str_replace(' ', '&nbsp;', formatNumber($data[$NAME . $num], false, 0)) . $unit;
             case "decimal":
                 if (isset($searchopt[$ID]['forcegroupby']) && $searchopt[$ID]['forcegroupby']) {
                     $out = "";
                     $split = explode("\$\$\$\$", $data[$NAME . $num]);
                     $count_display = 0;
                     for ($k = 0; $k < count($split); $k++) {
                         if (strlen(trim($split[$k])) > 0) {
                             if ($count_display) {
                                 $out .= "<br>";
                             }
                             $count_display++;
                             $out .= str_replace(' ', '&nbsp;', formatNumber($split[$k])) . $unit;
                         }
                     }
                     return $out;
                 }
                 return str_replace(' ', '&nbsp;', formatNumber($data[$NAME . $num])) . $unit;
             case "bool":
                 return Dropdown::getYesNo($data[$NAME . $num]) . $unit;
             case "right":
                 return Profile::getRightValue($data[$NAME . $num]);
             case "itemtypename":
                 if (class_exists($data[$NAME . $num])) {
                     $obj = new $data[$NAME . $num]();
                     return $obj->getTypeName();
                 }
                 return "";
             case "language":
                 if (isset($CFG_GLPI['languages'][$data[$NAME . $num]])) {
                     return $CFG_GLPI['languages'][$data[$NAME . $num]][0];
                 }
                 return $LANG['setup'][46];
         }
     }
     // Manage items with need group by / group_concat
     if (isset($searchopt[$ID]['forcegroupby']) && $searchopt[$ID]['forcegroupby']) {
         $out = "";
         $split = explode("\$\$\$\$", $data[$NAME . $num]);
         $count_display = 0;
         $separate = '<br>';
         if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) {
             $separate = '<hr>';
         }
         for ($k = 0; $k < count($split); $k++) {
             if (strlen(trim($split[$k])) > 0) {
                 if ($count_display) {
                     $out .= $separate;
                 }
                 $count_display++;
                 $out .= $split[$k] . $unit;
             }
         }
         return $out;
     }
     return $data[$NAME . $num] . $unit;
 }
 /**
  * List the tickets for an authenticated user
  *
  * @param $params    array of options (author, group, category, status, startdate, enddate, itemtype)
  * @param $protocol        the communication protocol used
  *
  * @return array of hashtable
  **/
 static function methodListTickets($params, $protocol)
 {
     global $DB, $CFG_GLPI;
     if (isset($params['help'])) {
         return array('count' => 'bool,optional', 'start' => 'integer,optional', 'limit' => 'integer,optional', 'user' => 'integer,optional', 'recipient' => 'integer,optional', 'mine' => 'bool,optional', 'group' => 'integer,optional', 'mygroups' => 'bool,optional', 'category' => 'integer,optional', 'status' => 'integer,optional', 'startdate' => 'datetime,optional', 'enddate' => 'datetime,optional', 'itemtype' => 'string,optional', 'item' => 'integer,optional', 'entity' => 'integer,optional', 'satisfaction' => 'integer,optional', 'approval' => 'text,optional', 'approver' => 'integer,optional', 'id2name' => 'bool,optional', 'order' => 'array,optional', 'help' => 'bool,optional');
     }
     if (!Session::getLoginUserID()) {
         return self::Error($protocol, WEBSERVICES_ERROR_NOTAUTHENTICATED);
     }
     $resp = array();
     $start = 0;
     if (isset($params['start']) && is_numeric($params['start'])) {
         $start = $params['start'];
     }
     $limit = $_SESSION['glpilist_limit'];
     if (isset($params['limit']) && is_numeric($params['limit'])) {
         $limit = $params['limit'];
     }
     $where = $join = '';
     // User (victim)
     if (isset($params['user'])) {
         if (!is_numeric($params['user']) || $params['user'] < 0) {
             return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', 'user');
         }
         if (Session::haveRightsOr('ticket', array(Ticket::READALL, Ticket::READGROUP)) || $params['user'] == Session::getLoginUserID()) {
             // restrict to author parameter
             $where = " AND `glpi_tickets_users_request`.`users_id` = '" . $params['user'] . "'";
         } else {
             return self::Error($protocol, WEBSERVICES_ERROR_NOTALLOWED);
         }
     } else {
         if (Session::haveRightsOr('ticket', array(Ticket::READALL, Ticket::READGROUP))) {
             $where = '';
             // Restrict will come from group (if needed)
         } else {
             // Only connected user's tickets'
             $where = " AND `glpi_tickets_users_request`.`users_id`\n                           = '" . Session::getLoginUserID() . "'";
         }
     }
     // Group
     if (isset($params['group'])) {
         if (!is_numeric($params['group']) || $params['group'] < 0) {
             return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', 'group');
         }
         if (Session::haveRight('ticket', Ticket::READALL) || Session::haveRight('ticket', Ticket::READGROUP) && in_array($params['group'], $_SESSION['glpigroups'])) {
             // restrict to group parameter
             $where = " AND `glpi_groups_tickets_request`.`groups_id` = '" . $params['group'] . "'";
         } else {
             return self::Error($protocol, WEBSERVICES_ERROR_NOTALLOWED);
         }
     } else {
         if (Session::haveRight('ticket', Ticket::READGROUP) && !Session::haveRight('ticket', Ticket::READALL)) {
             // Connected user's group'
             if (count($_SESSION['glpigroups']) > 0) {
                 $where = " AND `glpi_groups_tickets_request`.`groups_id`\n                              IN (" . implode(',', $_SESSION['glpigroups']) . ")";
             } else {
                 $where = " AND `glpi_tickets_users_request`.`users_id`\n                              = '" . Session::getLoginUserID() . "'";
             }
         }
     }
     // Security
     if (empty($where) && !Session::haveRight('ticket', Ticket::READALL)) {
         return self::Error($protocol, WEBSERVICES_ERROR_NOTALLOWED, '', 'profil');
     }
     // Recipient (person creating the ticket)
     if (isset($params['recipient'])) {
         if (!is_numeric($params['recipient']) || $params['recipient'] < 0) {
             return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', 'recipient');
         }
         // restrict to recipient parameter
         $where = " AND `users_id_recipient`='" . $params['recipient'] . "'";
     }
     // Mine (user or recipient for the ticket)
     if (isset($params['mine'])) {
         $where = " AND (`glpi_tickets_users_request`.`users_id` = '" . Session::getLoginUserID() . "'\n                         OR `users_id_recipient` = '" . Session::getLoginUserID() . "')";
     }
     // Mygroups
     if (isset($param['mygroups'])) {
         $where = " AND `glpi_groups_tickets`.`groups_id`\n                        IN (" . implode(',', $_SESSION['glpigroups']) . ")";
     }
     // Entity
     if (isset($params['entity'])) {
         if (!Session::haveAccessToEntity($params['entity'])) {
             return self::Error($protocol, WEBSERVICES_ERROR_NOTALLOWED, '', 'entity');
         }
         $where = getEntitiesRestrictRequest("WHERE", "glpi_tickets", '', $params['entity']) . $where;
     } else {
         $where = getEntitiesRestrictRequest("WHERE", "glpi_tickets") . $where;
     }
     // Category
     if (isset($params['category'])) {
         if (!is_numeric($params['category']) || $params['category'] <= 0) {
             return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', 'category');
         }
         $where .= " AND " . getRealQueryForTreeItem("glpi_itilcategories", $params['category'], "glpi_tickets.itilcategories_id");
     }
     if (isset($params['approval']) || isset($params['approver'])) {
         $join .= "INNER JOIN `glpi_ticketvalidations`\n                         ON (`glpi_tickets`.`id` = `glpi_ticketvalidations`.`tickets_id` ) ";
         if (isset($params['approver']) && is_numeric($params['approver'])) {
             $where .= " AND `glpi_ticketvalidations`.`users_id_validate`=" . $params['approver'];
         }
         $tabstatus = TicketValidation::getAllStatusArray();
         if (isset($params['approval']) && isset($tabstatus[$params['approval']])) {
             $where .= " AND `glpi_ticketvalidations`.`status`='" . $params['approval'] . "'";
         }
     }
     if (isset($params['satisfaction'])) {
         $join .= "INNER JOIN `glpi_ticketsatisfactions`\n                        ON (`glpi_tickets`.`id` = `glpi_ticketsatisfactions`.`tickets_id` ) ";
         switch ($params['satisfaction']) {
             case 1:
                 $where .= " AND `glpi_ticketsatisfactions`.`date_answered` IS NULL";
                 break;
             case 2:
                 $where .= " AND `glpi_ticketsatisfactions`.`date_answered` IS NOT NULL";
                 break;
             default:
                 // survey exists (by Inner Join)
         }
         $params['status'] = Ticket::CLOSED;
     }
     // Status
     if (isset($params['status'])) {
         $status = '';
         foreach (Ticket::getAllStatusArray(true) as $key => $val) {
             $status[] = $key;
         }
         if (!in_array($params['status'], $status)) {
             return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', 'status');
         }
         switch ($params['status']) {
             case 'all':
                 // No restriction
                 break;
             case 'notclosed':
                 $status = Ticket::getAllStatusArray();
                 unset($status[Ticket::CLOSED]);
                 $where .= " AND `glpi_tickets`.`status` IN ('" . implode("','", array_keys($status)) . "') ";
                 break;
             case 'notold':
                 $status = Ticket::getAllStatusArray();
                 unset($status[Ticket::SOLVED], $status[Ticket::CLOSED]);
                 $where .= " AND `glpi_tickets`.`status` IN ('" . implode("','", array_keys($status)) . "') ";
                 break;
             case 'old':
                 $status = array_merge(Ticket::getSolvedStatusArray(), Ticket::getClosedStatusArray());
                 $where .= " AND `glpi_tickets`.`status` IN ('" . implode("','", $status) . "') ";
                 break;
             case 'process':
                 $status = Ticket::getProcessStatusArray();
                 $where .= " AND `glpi_tickets`.`status` IN ('" . implode("','", $status) . "') ";
                 break;
             default:
                 $where .= " AND `glpi_tickets`.`status` = '" . $params['status'] . "' ";
         }
     }
     // Dates
     if (isset($params["startdate"])) {
         if (preg_match(WEBSERVICES_REGEX_DATETIME, $params["startdate"]) || preg_match(WEBSERVICES_REGEX_DATE, $params["startdate"])) {
             $where .= " AND `glpi_tickets`.`date` >= '" . $params['startdate'] . "' ";
         } else {
             return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', 'date');
         }
     }
     if (isset($params["enddate"])) {
         if (preg_match(WEBSERVICES_REGEX_DATETIME, $params["enddate"]) || preg_match(WEBSERVICES_REGEX_DATE, $params["enddate"])) {
             $where .= " AND `glpi_tickets`.`date` <= '" . $params['enddate'] . "' ";
         } else {
             return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', 'date');
         }
     }
     if (isset($params['itemtype'])) {
         if (!empty($params['itemtype']) && !class_exists($params['itemtype'])) {
             return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', 'itemtype');
         }
         $where .= " AND `glpi_tickets`.`itemtype`='" . $params['itemtype'] . "'";
     }
     if (isset($params['item'])) {
         if (!isset($params['itemtype'])) {
             return self::Error($protocol, WEBSERVICES_ERROR_MISSINGPARAMETER, '', 'itemtype');
         }
         if (!is_numeric($params['item']) || $params['item'] <= 0) {
             return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', 'item');
         }
         $where .= " AND `glpi_tickets`.`items_id`='" . $params['item'] . "'";
     }
     $orders = array();
     if (isset($params['order'])) {
         if (is_array($params['order'])) {
             $tab = $params['order'];
         } else {
             $tab = array($params['order'] => 'DESC');
         }
         foreach ($tab as $key => $val) {
             if ($val != 'ASC') {
                 $val = 'DESC';
             }
             $sqlkey = array('id' => '`glpi_tickets`.`id`', 'date' => '`glpi_tickets`.`date`', 'closedate' => '`glpi_tickets`.`closedate`', 'date_mod' => '`glpi_tickets`.`date_mod`', 'status' => '`glpi_tickets`.`status`', 'entities_id' => '`glpi_tickets`.`entities_id`', 'priority' => '`glpi_tickets`.`priority`');
             if (isset($sqlkey[$key])) {
                 $orders[] = $sqlkey[$key] . " {$val}";
             } else {
                 return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', 'order=$key');
             }
         }
     }
     if (count($orders)) {
         $order = implode(',', $orders);
     } else {
         $order = "`glpi_tickets`.`date_mod` DESC";
     }
     $resp = array();
     if (isset($params['count'])) {
         $query = "SELECT COUNT(DISTINCT `glpi_tickets`.`id`) AS count\n                   FROM `glpi_tickets`\n                   {$join}\n                   LEFT JOIN `glpi_tickets_users` AS glpi_tickets_users_request\n                        ON (`glpi_tickets`.`id` = `glpi_tickets_users_request`.`tickets_id`\n                            AND `glpi_tickets_users_request`.`type` = 1)\n                   LEFT JOIN `glpi_groups_tickets` AS glpi_groups_tickets_request\n                        ON (`glpi_tickets`.`id` = `glpi_groups_tickets_request`.`tickets_id`\n                            AND `glpi_groups_tickets_request`.`type` = 1 )\n                   {$where}";
         $resp = $DB->request($query)->next();
         //debug $resp['query'] = $query;
     } else {
         $query = "SELECT `glpi_tickets`.*,\n                          GROUP_CONCAT(DISTINCT `glpi_tickets_users_request`.`users_id` SEPARATOR ',')\n                                 AS users_id_request,\n                          GROUP_CONCAT(DISTINCT `glpi_tickets_users_observer`.`users_id` SEPARATOR ',')\n                                 AS users_id_observer,\n                          GROUP_CONCAT(DISTINCT `glpi_tickets_users_assign`.`users_id` SEPARATOR ',')\n                                 AS users_id_assign,\n                          GROUP_CONCAT(DISTINCT `glpi_groups_tickets_request`.`groups_id` SEPARATOR ',')\n                                 AS groups_id_request,\n                          GROUP_CONCAT(DISTINCT `glpi_groups_tickets_observer`.`groups_id` SEPARATOR ',')\n                                 AS groups_id_observer,\n                          GROUP_CONCAT(DISTINCT `glpi_groups_tickets_assign`.`groups_id` SEPARATOR ',')\n                                 AS groups_id_assign\n                   FROM `glpi_tickets`\n                   {$join}\n                   LEFT JOIN `glpi_tickets_users` AS glpi_tickets_users_request\n                        ON (`glpi_tickets`.`id` = `glpi_tickets_users_request`.`tickets_id`\n                            AND `glpi_tickets_users_request`.`type` = 1)\n                   LEFT JOIN `glpi_tickets_users` AS glpi_tickets_users_assign\n                        ON (`glpi_tickets`.`id` = `glpi_tickets_users_assign`.`tickets_id`\n                            AND `glpi_tickets_users_assign`.`type` = 2)\n                   LEFT JOIN `glpi_tickets_users` AS glpi_tickets_users_observer\n                        ON (`glpi_tickets`.`id` = `glpi_tickets_users_observer`.`tickets_id`\n                            AND `glpi_tickets_users_observer`.`type` = 3)\n                   LEFT JOIN `glpi_groups_tickets` AS glpi_groups_tickets_request\n                        ON (`glpi_tickets`.`id` = `glpi_groups_tickets_request`.`tickets_id`\n                            AND `glpi_groups_tickets_request`.`type` = 1)\n                   LEFT JOIN `glpi_groups_tickets` AS glpi_groups_tickets_assign\n                        ON (`glpi_tickets`.`id` = `glpi_groups_tickets_assign`.`tickets_id`\n                            AND `glpi_groups_tickets_assign`.`type` = 2)\n                   LEFT JOIN `glpi_groups_tickets` AS glpi_groups_tickets_observer\n                        ON (`glpi_tickets`.`id` = `glpi_groups_tickets_observer`.`tickets_id`\n                            AND `glpi_groups_tickets_observer`.`type` = 3)\n                   {$where}\n                   GROUP BY `glpi_tickets`.`id`\n                   ORDER BY {$order}\n                   LIMIT {$start},{$limit}";
         foreach ($DB->request($query) as $data) {
             $tmp = explode(',', $data['users_id_request']);
             $data['users']['requester'] = array();
             foreach ($tmp as $id) {
                 $data['users']['requester'][]['id'] = $id;
             }
             $tmp = explode(',', $data['users_id_observer']);
             $data['users']['observer'] = array();
             foreach ($tmp as $id) {
                 $data['users']['observer'][]['id'] = $id;
             }
             $tmp = explode(',', $data['users_id_assign']);
             $data['users']['assign'] = array();
             foreach ($tmp as $id) {
                 $data['users']['assign'][]['id'] = $id;
             }
             $tmp = explode(',', $data['groups_id_request']);
             $data['groups']['requester'] = array();
             foreach ($tmp as $id) {
                 $data['groups']['requester'][]['id'] = $id;
             }
             $tmp = explode(',', $data['groups_id_observer']);
             $data['groups']['observer'] = array();
             foreach ($tmp as $id) {
                 $data['groups']['observer'][]['id'] = $id;
             }
             $tmp = explode(',', $data['groups_id_assign']);
             $data['groups']['assign'] = array();
             foreach ($tmp as $id) {
                 $data['groups']['assign'][]['id'] = $id;
             }
             unset($data['groups_id_request'], $data['groups_id_observer'], $data['groups_id_assign'], $data['users_id_request'], $data['users_id_observer'], $data['users_id_assign']);
             $data['solution'] = Html::clean(Toolbox::unclean_cross_side_scripting_deep($data['solution']));
             if (isset($params['id2name'])) {
                 if ($data['itemtype'] && ($item = getItemForItemtype($data['itemtype']))) {
                     $data['itemtype_name'] = Html::clean($item->getTypeName());
                     if ($item->getFromDB($data['items_id'])) {
                         $data['items_name'] = Html::clean($item->getNameID());
                     } else {
                         $data['items_name'] = NOT_AVAILABLE;
                     }
                 }
                 foreach ($data['groups'] as $type => $tab) {
                     foreach ($tab as $key => $grp) {
                         $data['groups'][$type][$key]['name'] = Html::clean(Dropdown::getDropdownName('glpi_groups', $grp['id']));
                     }
                 }
                 foreach ($data['users'] as $type => $tab) {
                     foreach ($tab as $key => $usr) {
                         $data['users'][$type][$key]['name'] = Html::clean(getUserName($usr['id']));
                     }
                 }
                 $data['status_name'] = Html::clean(Ticket::getStatus($data['status']));
                 $data['urgency_name'] = Ticket::getUrgencyName($data['urgency']);
                 $data['impact_name'] = Ticket::getImpactName($data['impact']);
                 $data['priority_name'] = Ticket::getPriorityName($data['priority']);
                 $data['users_name_recipient'] = Html::clean(getUserName($data['users_id_recipient']));
                 $data['entities_name'] = Html::clean(Dropdown::getDropdownName('glpi_entities', $data['entities_id']));
                 $data['suppliers_name_assign'] = Html::clean(Dropdown::getDropdownName('glpi_suppliers', $data['suppliers_id_assign']));
                 $data['ticketcategories_name'] = Html::clean(Dropdown::getDropdownName('glpi_itilcategories', $data['itilcategories_id']));
                 $data['requesttypes_name'] = Html::clean(Dropdown::getDropdownName('glpi_requesttypes', $data['requesttypes_id']));
                 $data['solutiontypes_name'] = Html::clean(Dropdown::getDropdownName('glpi_solutiontypes', $data['solutiontypes_id']));
                 $data['slas_name'] = Html::clean(Dropdown::getDropdownName('glpi_slas', $data['slas_id']));
                 $data['slalevels_name'] = Html::clean(Dropdown::getDropdownName('glpi_slalevels', $data['slalevels_id']));
                 $data['global_validation_name'] = Html::clean(TicketValidation::getStatus($data['global_validation']));
             }
             $resp[] = $data;
         }
     }
     return $resp;
 }
示例#16
0
 /**
  * Clone of Ticket::showForm()
  * Change '$this' by '$ticket', 'self' by 'Ticket' and 'parent' by 'Ticket'
  */
 static function getCentral($ID = 0, $options = array())
 {
     global $CFG_GLPI;
     // * Added by plugin survey ticket
     $ticket = new Ticket();
     // * End of adding
     $default_values = Ticket::getDefaultValues();
     // Get default values from posted values on reload form
     if (!isset($options['template_preview'])) {
         if (isset($_POST)) {
             $values = $_POST;
         }
     }
     // Restore saved value or override with page parameter
     $saved = $ticket->restoreInput();
     foreach ($default_values as $name => $value) {
         if (!isset($values[$name])) {
             if (isset($saved[$name])) {
                 $values[$name] = $saved[$name];
             } else {
                 $values[$name] = $value;
             }
         }
     }
     // Default check
     if ($ID > 0) {
         $ticket->check($ID, 'r');
     } else {
         // Create item
         $ticket->check(-1, 'w', $values);
     }
     if (!$ID) {
         $ticket->userentities = array();
         if ($values["_users_id_requester"]) {
             //Get all the user's entities
             $all_entities = Profile_User::getUserEntities($values["_users_id_requester"], true, true);
             //For each user's entity, check if the technician which creates the ticket have access to it
             foreach ($all_entities as $tmp => $ID_entity) {
                 if (Session::haveAccessToEntity($ID_entity)) {
                     $ticket->userentities[] = $ID_entity;
                 }
             }
         }
         $ticket->countentitiesforuser = count($ticket->userentities);
         if ($ticket->countentitiesforuser > 0 && !in_array($ticket->fields["entities_id"], $ticket->userentities)) {
             // If entity is not in the list of user's entities,
             // then use as default value the first value of the user's entites list
             $ticket->fields["entities_id"] = $ticket->userentities[0];
             // Pass to values
             $values['entities_id'] = $ticket->userentities[0];
         }
     }
     if ($values['type'] <= 0) {
         $values['type'] = Entity::getUsedConfig('tickettype', $values['entities_id'], '', Ticket::INCIDENT_TYPE);
     }
     if (!isset($options['template_preview'])) {
         $options['template_preview'] = 0;
     }
     // Load ticket template if available :
     $tt = $ticket->getTicketTemplateToUse($options['template_preview'], $values['type'], $values['itilcategories_id'], $values['entities_id']);
     // Predefined fields from template : reset them
     if (isset($values['_predefined_fields'])) {
         $values['_predefined_fields'] = Toolbox::decodeArrayFromInput($values['_predefined_fields']);
     } else {
         $values['_predefined_fields'] = array();
     }
     // Store predefined fields to be able not to take into account on change template
     // Only manage predefined values on ticket creation
     $predefined_fields = array();
     if (!$ID) {
         if (isset($tt->predefined) && count($tt->predefined)) {
             foreach ($tt->predefined as $predeffield => $predefvalue) {
                 if (isset($default_values[$predeffield])) {
                     // Is always default value : not set
                     // Set if already predefined field
                     // Set if ticket template change
                     if ($values[$predeffield] == $default_values[$predeffield] || isset($values['_predefined_fields'][$predeffield]) && $values[$predeffield] == $values['_predefined_fields'][$predeffield] || isset($values['_tickettemplates_id']) && $values['_tickettemplates_id'] != $tt->getID()) {
                         // Load template data
                         $values[$predeffield] = $predefvalue;
                         $ticket->fields[$predeffield] = $predefvalue;
                         $predefined_fields[$predeffield] = $predefvalue;
                     }
                 }
             }
         } else {
             // No template load : reset predefined values
             if (count($values['_predefined_fields'])) {
                 foreach ($values['_predefined_fields'] as $predeffield => $predefvalue) {
                     if ($values[$predeffield] == $predefvalue) {
                         $values[$predeffield] = $default_values[$predeffield];
                     }
                 }
             }
         }
     }
     // Put ticket template on $values for actors
     $values['_tickettemplate'] = $tt;
     $canupdate = Session::haveRight('update_ticket', '1');
     $canpriority = Session::haveRight('update_priority', '1');
     $canstatus = $canupdate;
     if (in_array($ticket->fields['status'], $ticket->getClosedStatusArray())) {
         $canupdate = false;
     }
     $showuserlink = 0;
     if (Session::haveRight('user', 'r')) {
         $showuserlink = 1;
     }
     if (!$options['template_preview']) {
         $ticket->showTabs($options);
     } else {
         // Add all values to fields of tickets for template preview
         foreach ($values as $key => $val) {
             if (!isset($ticket->fields[$key])) {
                 $ticket->fields[$key] = $val;
             }
         }
     }
     // In percent
     $colsize1 = '13';
     $colsize2 = '29';
     $colsize3 = '13';
     $colsize4 = '45';
     $canupdate_descr = $canupdate || $ticket->fields['status'] == Ticket::INCOMING && $ticket->isUser(CommonITILActor::REQUESTER, Session::getLoginUserID()) && $ticket->numberOfFollowups() == 0 && $ticket->numberOfTasks() == 0;
     if (!$options['template_preview']) {
         echo "<form method='post' name='form_ticket' enctype='multipart/form-data' action='" . $CFG_GLPI["root_doc"] . "/front/ticket.form.php'>";
     }
     echo "<div class='spaced' id='tabsbody'>";
     echo "<table class='tab_cadre_fixe' id='mainformtable'>";
     // Optional line
     $ismultientities = Session::isMultiEntitiesMode();
     echo "<tr class='headerRow'>";
     echo "<th colspan='4'>";
     if ($ID) {
         $text = sprintf(__('%1$s - %2$s'), $ticket->getTypeName(1), sprintf(__('%1$s: %2$s'), __('ID'), $ID));
         if ($ismultientities) {
             $text = sprintf(__('%1$s (%2$s)'), $text, Dropdown::getDropdownName('glpi_entities', $ticket->fields['entities_id']));
         }
         echo $text;
     } else {
         if ($ismultientities) {
             printf(__('The ticket will be added in the entity %s'), Dropdown::getDropdownName("glpi_entities", $ticket->fields['entities_id']));
         } else {
             _e('New ticket');
         }
     }
     echo "</th></tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<th width='{$colsize1}%'>";
     echo $tt->getBeginHiddenFieldText('date');
     if (!$ID) {
         printf(__('%1$s%2$s'), __('Opening date'), $tt->getMandatoryMark('date'));
     } else {
         _e('Opening date');
     }
     echo $tt->getEndHiddenFieldText('date');
     echo "</th>";
     echo "<td width='{$colsize2}%'>";
     echo $tt->getBeginHiddenFieldValue('date');
     $date = $ticket->fields["date"];
     if ($canupdate) {
         Html::showDateTimeFormItem("date", $date, 1, false);
     } else {
         echo Html::convDateTime($date);
     }
     echo $tt->getEndHiddenFieldValue('date', $ticket);
     echo "</td>";
     // SLA
     echo "<th width='{$colsize3}%'>" . $tt->getBeginHiddenFieldText('due_date');
     if (!$ID) {
         printf(__('%1$s%2$s'), __('Due date'), $tt->getMandatoryMark('due_date'));
     } else {
         _e('Due date');
     }
     echo $tt->getEndHiddenFieldText('due_date');
     echo "</th>";
     echo "<td width='{$colsize4}%' class='nopadding'>";
     if ($ID) {
         if ($ticket->fields["slas_id"] > 0) {
             echo "<table width='100%'><tr><td class='nopadding'>";
             echo Html::convDateTime($ticket->fields["due_date"]);
             echo "</td><td class='b'>" . __('SLA') . "</td>";
             echo "<td class='nopadding'>";
             echo Dropdown::getDropdownName("glpi_slas", $ticket->fields["slas_id"]);
             $commentsla = "";
             $slalevel = new SlaLevel();
             if ($slalevel->getFromDB($ticket->fields['slalevels_id'])) {
                 $commentsla .= '<span class="b spaced">' . sprintf(__('%1$s: %2$s'), __('Escalation level'), $slalevel->getName()) . '</span><br>';
             }
             $nextaction = new SlaLevel_Ticket();
             if ($nextaction->getFromDBForTicket($ticket->fields["id"])) {
                 $commentsla .= '<span class="b spaced">' . sprintf(__('Next escalation: %s'), Html::convDateTime($nextaction->fields['date'])) . '</span>';
                 if ($slalevel->getFromDB($nextaction->fields['slalevels_id'])) {
                     $commentsla .= '<span class="b spaced">' . sprintf(__('%1$s: %2$s'), __('Escalation level'), $slalevel->getName()) . '</span>';
                 }
             }
             $slaoptions = array();
             if (Session::haveRight('config', 'r')) {
                 $slaoptions['link'] = Toolbox::getItemTypeFormURL('SLA') . "?id=" . $ticket->fields["slas_id"];
             }
             Html::showToolTip($commentsla, $slaoptions);
             if ($canupdate) {
                 echo "&nbsp;<input type='submit' class='submit' name='sla_delete' value='" . _sx('button', 'Delete permanently') . "'>";
             }
             echo "</td>";
             echo "</tr></table>";
         } else {
             echo "<table><tr><td class='nopadding'>";
             echo $tt->getBeginHiddenFieldValue('due_date');
             Html::showDateTimeFormItem("due_date", $ticket->fields["due_date"], 1, true, $canupdate);
             echo $tt->getEndHiddenFieldValue('due_date', $ticket);
             echo "</td>";
             if ($canupdate) {
                 echo "<td>";
                 echo $tt->getBeginHiddenFieldText('slas_id');
                 echo "<span id='sla_action'>";
                 echo "<a class='vsubmit' " . Html::addConfirmationOnAction(array(__('The assignment of a SLA to a ticket causes the recalculation of the due date.'), __("Escalations defined in the SLA will be triggered under this new date.")), "cleanhide('sla_action');cleandisplay('sla_choice');") . ">" . __('Assign a SLA') . '</a>';
                 echo "</span>";
                 echo "<span id='sla_choice' style='display:none'>";
                 echo "<span  class='b'>" . __('SLA') . "</span>&nbsp;";
                 Sla::dropdown(array('entity' => $ticket->fields["entities_id"], 'value' => $ticket->fields["slas_id"]));
                 echo "</span>";
                 echo $tt->getEndHiddenFieldText('slas_id');
                 echo "</td>";
             }
             echo "</tr></table>";
         }
     } else {
         // New Ticket
         echo "<table><tr><td class='nopadding'>";
         if ($ticket->fields["due_date"] == 'NULL') {
             $ticket->fields["due_date"] = '';
         }
         echo $tt->getBeginHiddenFieldValue('due_date');
         Html::showDateTimeFormItem("due_date", $ticket->fields["due_date"], 1, false, $canupdate);
         echo $tt->getEndHiddenFieldValue('due_date', $ticket);
         echo "</td>";
         if ($canupdate) {
             echo "<td class='nopadding b'>" . $tt->getBeginHiddenFieldText('slas_id');
             printf(__('%1$s%2$s'), __('SLA'), $tt->getMandatoryMark('slas_id'));
             echo $tt->getEndHiddenFieldText('slas_id') . "</td>";
             echo "<td class='nopadding'>" . $tt->getBeginHiddenFieldValue('slas_id');
             Sla::dropdown(array('entity' => $ticket->fields["entities_id"], 'value' => $ticket->fields["slas_id"]));
             echo $tt->getEndHiddenFieldValue('slas_id', $ticket);
             echo "</td>";
         }
         echo "</tr></table>";
     }
     echo "</td></tr>";
     if ($ID) {
         echo "<tr class='tab_bg_1'>";
         echo "<th width='{$colsize1}%'>" . __('By') . "</th>";
         echo "<td width='{$colsize2}%'>";
         if ($canupdate) {
             User::dropdown(array('name' => 'users_id_recipient', 'value' => $ticket->fields["users_id_recipient"], 'entity' => $ticket->fields["entities_id"], 'right' => 'all'));
         } else {
             echo getUserName($ticket->fields["users_id_recipient"], $showuserlink);
         }
         echo "</td>";
         echo "<th width='{$colsize3}%'>" . __('Last update') . "</th>";
         echo "<td width='{$colsize4}%'>";
         if ($ticket->fields['users_id_lastupdater'] > 0) {
             //TRANS: %1$s is the update date, %2$s is the last updater name
             printf(__('%1$s by %2$s'), Html::convDateTime($ticket->fields["date_mod"]), getUserName($ticket->fields["users_id_lastupdater"], $showuserlink));
         }
         echo "</td>";
         echo "</tr>";
     }
     if ($ID && (in_array($ticket->fields["status"], $ticket->getSolvedStatusArray()) || in_array($ticket->fields["status"], $ticket->getClosedStatusArray()))) {
         echo "<tr class='tab_bg_1'>";
         echo "<th width='{$colsize1}%'>" . __('Resolution date') . "</th>";
         echo "<td width='{$colsize2}%'>";
         Html::showDateTimeFormItem("solvedate", $ticket->fields["solvedate"], 1, false, $canupdate);
         echo "</td>";
         if (in_array($ticket->fields["status"], $ticket->getClosedStatusArray())) {
             echo "<th width='{$colsize3}%'>" . __('Close date') . "</th>";
             echo "<td width='{$colsize4}%'>";
             Html::showDateTimeFormItem("closedate", $ticket->fields["closedate"], 1, false, $canupdate);
             echo "</td>";
         } else {
             echo "<td colspan='2'>&nbsp;</td>";
         }
         echo "</tr>";
     }
     if ($ID) {
         echo "</table>";
         echo "<table  class='tab_cadre_fixe' id='mainformtable2'>";
     }
     echo "<tr class='tab_bg_1'>";
     echo "<th width='{$colsize1}%'>" . sprintf(__('%1$s%2$s'), __('Type'), $tt->getMandatoryMark('type')) . "</th>";
     echo "<td width='{$colsize2}%'>";
     // Permit to set type when creating ticket without update right
     if ($canupdate || !$ID) {
         $opt = array('value' => $ticket->fields["type"]);
         /// Auto submit to load template
         if (!$ID) {
             $opt['on_change'] = 'submit()';
         }
         $rand = Ticket::dropdownType('type', $opt);
         if ($ID) {
             $params = array('type' => '__VALUE__', 'entity_restrict' => $ticket->fields['entities_id'], 'value' => $ticket->fields['itilcategories_id'], 'currenttype' => $ticket->fields['type']);
             Ajax::updateItemOnSelectEvent("dropdown_type{$rand}", "show_category_by_type", $CFG_GLPI["root_doc"] . "/ajax/dropdownTicketCategories.php", $params);
         }
     } else {
         echo Ticket::getTicketTypeName($ticket->fields["type"]);
     }
     echo "</td>";
     echo "<th width='{$colsize3}%'>" . sprintf(__('%1$s%2$s'), __('Category'), $tt->getMandatoryMark('itilcategories_id')) . "</th>";
     echo "<td width='{$colsize4}%'>";
     // Permit to set category when creating ticket without update right
     if ($canupdate || !$ID || $canupdate_descr) {
         $opt = array('value' => $ticket->fields["itilcategories_id"], 'entity' => $ticket->fields["entities_id"]);
         if ($_SESSION["glpiactiveprofile"]["interface"] == "helpdesk") {
             $opt['condition'] = "`is_helpdeskvisible`='1' AND ";
         } else {
             $opt['condition'] = '';
         }
         /// Auto submit to load template
         if (!$ID) {
             $opt['on_change'] = 'submit()';
         }
         /// if category mandatory, no empty choice
         /// no empty choice is default value set on ticket creation, else yes
         if (($ID || $values['itilcategories_id']) && $tt->isMandatoryField("itilcategories_id") && $ticket->fields["itilcategories_id"] > 0) {
             $opt['display_emptychoice'] = false;
         }
         switch ($ticket->fields["type"]) {
             case Ticket::INCIDENT_TYPE:
                 $opt['condition'] .= "`is_incident`='1'";
                 break;
             case Ticket::DEMAND_TYPE:
                 $opt['condition'] .= "`is_request`='1'";
                 break;
             default:
                 break;
         }
         echo "<span id='show_category_by_type'>";
         ITILCategory::dropdown($opt);
         echo "</span>";
     } else {
         echo Dropdown::getDropdownName("glpi_itilcategories", $ticket->fields["itilcategories_id"]);
     }
     echo "</td>";
     echo "</tr>";
     if (!$ID) {
         echo "</table>";
         $ticket->showActorsPartForm($ID, $values);
         echo "<table class='tab_cadre_fixe' id='mainformtable3'>";
     }
     echo "<tr class='tab_bg_1'>";
     echo "<th width='{$colsize1}%'>" . $tt->getBeginHiddenFieldText('status');
     printf(__('%1$s%2$s'), __('Status'), $tt->getMandatoryMark('status'));
     echo $tt->getEndHiddenFieldText('status') . "</th>";
     echo "<td width='{$colsize2}%'>";
     echo $tt->getBeginHiddenFieldValue('status');
     if ($canstatus) {
         Ticket::dropdownStatus(array('value' => $ticket->fields["status"], 'showtype' => 'allowed'));
     } else {
         echo Ticket::getStatus($ticket->fields["status"]);
     }
     echo $tt->getEndHiddenFieldValue('status', $ticket);
     echo "</td>";
     echo "<th width='{$colsize3}%'>" . $tt->getBeginHiddenFieldText('requesttypes_id');
     printf(__('%1$s%2$s'), __('Request source'), $tt->getMandatoryMark('requesttypes_id'));
     echo $tt->getEndHiddenFieldText('requesttypes_id') . "</th>";
     echo "<td width='{$colsize4}%'>";
     echo $tt->getBeginHiddenFieldValue('requesttypes_id');
     if ($canupdate) {
         RequestType::dropdown(array('value' => $ticket->fields["requesttypes_id"]));
     } else {
         echo Dropdown::getDropdownName('glpi_requesttypes', $ticket->fields["requesttypes_id"]);
     }
     echo $tt->getEndHiddenFieldValue('requesttypes_id', $ticket);
     echo "</td>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<th>" . $tt->getBeginHiddenFieldText('urgency');
     printf(__('%1$s%2$s'), __('Urgency'), $tt->getMandatoryMark('urgency'));
     echo $tt->getEndHiddenFieldText('urgency') . "</th>";
     echo "<td>";
     if ($canupdate && $canpriority || !$ID || $canupdate_descr) {
         // Only change during creation OR when allowed to change priority OR when user is the creator
         echo $tt->getBeginHiddenFieldValue('urgency');
         $idurgency = Ticket::dropdownUrgency(array('value' => $ticket->fields["urgency"]));
         echo $tt->getEndHiddenFieldValue('urgency', $ticket);
     } else {
         $idurgency = "value_urgency" . mt_rand();
         echo "<input id='{$idurgency}' type='hidden' name='urgency' value='" . $ticket->fields["urgency"] . "'>";
         echo Ticket::getUrgencyName($ticket->fields["urgency"]);
     }
     echo "</td>";
     // Display validation state
     echo "<th>";
     if (!$ID) {
         echo $tt->getBeginHiddenFieldText('_add_validation');
         printf(__('%1$s%2$s'), __('Approval request'), $tt->getMandatoryMark('_add_validation'));
         echo $tt->getEndHiddenFieldText('_add_validation');
     } else {
         echo $tt->getBeginHiddenFieldText('global_validation');
         _e('Approval');
         echo $tt->getEndHiddenFieldText('global_validation');
     }
     echo "</th>";
     echo "<td>";
     if (!$ID) {
         echo $tt->getBeginHiddenFieldValue('_add_validation');
         $validation_right = '';
         if ($values['type'] == Ticket::INCIDENT_TYPE && Session::haveRight('create_incident_validation', 1)) {
             $validation_right = 'validate_incident';
         }
         if ($values['type'] == Ticket::DEMAND_TYPE && Session::haveRight('create_request_validation', 1)) {
             $validation_right = 'validate_request';
         }
         if (!empty($validation_right)) {
             User::dropdown(array('name' => "_add_validation", 'entity' => $ticket->fields['entities_id'], 'right' => $validation_right, 'value' => $values['_add_validation']));
         }
         echo $tt->getEndHiddenFieldValue('_add_validation', $ticket);
         if ($tt->isPredefinedField('global_validation')) {
             echo "<input type='hidden' name='global_validation' value='" . $tt->predefined['global_validation'] . "'>";
         }
     } else {
         echo $tt->getBeginHiddenFieldValue('global_validation');
         if ($canupdate) {
             TicketValidation::dropdownStatus('global_validation', array('global' => true, 'value' => $ticket->fields['global_validation']));
         } else {
             echo TicketValidation::getStatus($ticket->fields['global_validation']);
         }
         echo $tt->getEndHiddenFieldValue('global_validation', $ticket);
     }
     echo "</td></tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<th>" . $tt->getBeginHiddenFieldText('impact');
     printf(__('%1$s%2$s'), __('Impact'), $tt->getMandatoryMark('impact'));
     echo $tt->getEndHiddenFieldText('impact') . "</th>";
     echo "<td>";
     echo $tt->getBeginHiddenFieldValue('impact');
     if ($canupdate) {
         $idimpact = Ticket::dropdownImpact(array('value' => $ticket->fields["impact"]));
     } else {
         $idimpact = "value_impact" . mt_rand();
         echo "<input id='{$idimpact}' type='hidden' name='impact' value='" . $ticket->fields["impact"] . "'>";
         echo Ticket::getImpactName($ticket->fields["impact"]);
     }
     echo $tt->getEndHiddenFieldValue('impact', $ticket);
     echo "</td>";
     echo "<th rowspan='2'>" . $tt->getBeginHiddenFieldText('itemtype');
     printf(__('%1$s%2$s'), __('Associated element'), $tt->getMandatoryMark('itemtype'));
     if ($ID && $canupdate) {
         echo "&nbsp;<img title='" . __s('Update') . "' alt='" . __s('Update') . "'\n                      onClick=\"Ext.get('tickethardwareselection{$ID}').setDisplayed('block')\"\n                      class='pointer' src='" . $CFG_GLPI["root_doc"] . "/pics/showselect.png'>";
     }
     echo $tt->getEndHiddenFieldText('itemtype');
     echo "</th>";
     echo "<td rowspan='2'>";
     echo $tt->getBeginHiddenFieldValue('itemtype');
     // Select hardware on creation or if have update right
     if ($canupdate || !$ID || $canupdate_descr) {
         if ($ID) {
             if ($ticket->fields['itemtype'] && ($item = getItemForItemtype($ticket->fields['itemtype'])) && $ticket->fields["items_id"]) {
                 if ($item->can($ticket->fields["items_id"], 'r')) {
                     printf(__('%1$s - %2$s'), $item->getTypeName(), $item->getLink(array('comments' => true)));
                 } else {
                     printf(__('%1$s - %2$s'), $item->getTypeName(), $item->getNameID());
                 }
             }
         }
         $dev_user_id = 0;
         $dev_itemtype = $ticket->fields["itemtype"];
         $dev_items_id = $ticket->fields["items_id"];
         if (!$ID) {
             $dev_user_id = $values['_users_id_requester'];
             $dev_itemtype = $values["itemtype"];
             $dev_items_id = $values["items_id"];
         } else {
             if (isset($ticket->users[CommonITILActor::REQUESTER]) && count($ticket->users[CommonITILActor::REQUESTER]) == 1) {
                 foreach ($ticket->users[CommonITILActor::REQUESTER] as $user_id_single) {
                     $dev_user_id = $user_id_single['users_id'];
                 }
             }
         }
         if ($ID) {
             echo "<div id='tickethardwareselection{$ID}' style='display:none'>";
         }
         if ($dev_user_id > 0) {
             Ticket::dropdownMyDevices($dev_user_id, $ticket->fields["entities_id"], $dev_itemtype, $dev_items_id);
         }
         Ticket::dropdownAllDevices("itemtype", $dev_itemtype, $dev_items_id, 1, $dev_user_id, $ticket->fields["entities_id"]);
         if ($ID) {
             echo "</div>";
         }
         echo "<span id='item_ticket_selection_information'></span>";
     } else {
         if ($ID && $ticket->fields['itemtype'] && ($item = getItemForItemtype($ticket->fields['itemtype']))) {
             $item->getFromDB($ticket->fields['items_id']);
             printf(__('%1$s - %2$s'), $item->getTypeName(), $item->getNameID());
         } else {
             _e('General');
         }
     }
     echo $tt->getEndHiddenFieldValue('itemtype', $ticket);
     echo "</td>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<th>" . sprintf(__('%1$s%2$s'), __('Priority'), $tt->getMandatoryMark('priority')) . "</th>";
     echo "<td>";
     $idajax = 'change_priority_' . mt_rand();
     if ($canupdate && $canpriority && !$tt->isHiddenField('priority')) {
         $idpriority = Ticket::dropdownPriority(array('value' => $ticket->fields["priority"], 'withmajor' => true));
         echo "&nbsp;<span id='{$idajax}' style='display:none'></span>";
     } else {
         $idpriority = 0;
         echo "<span id='{$idajax}'>" . Ticket::getPriorityName($ticket->fields["priority"]) . "</span>";
     }
     if ($canupdate || $canupdate_descr) {
         $params = array('urgency' => '__VALUE0__', 'impact' => '__VALUE1__', 'priority' => $idpriority);
         Ajax::updateItemOnSelectEvent(array($idurgency, $idimpact), $idajax, $CFG_GLPI["root_doc"] . "/ajax/priority.php", $params);
     }
     echo "</td>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     // Need comment right to add a followup with the actiontime
     if (!$ID && Session::haveRight("global_add_followups", "1")) {
         echo "<th>" . $tt->getBeginHiddenFieldText('actiontime');
         printf(__('%1$s%2$s'), __('Total duration'), $tt->getMandatoryMark('actiontime'));
         echo $tt->getEndHiddenFieldText('actiontime') . "</th>";
         echo "<td>";
         echo $tt->getBeginHiddenFieldValue('actiontime');
         Dropdown::showTimeStamp('actiontime', array('value' => $values['actiontime'], 'addfirstminutes' => true));
         echo $tt->getEndHiddenFieldValue('actiontime', $ticket);
         echo "</td>";
     } else {
         echo "<th></th><td></td>";
     }
     echo "<th>" . $tt->getBeginHiddenFieldText('locations_id');
     printf(__('%1$s%2$s'), __('Location'), $tt->getMandatoryMark('locations_id'));
     echo $tt->getEndHiddenFieldText('locations_id') . "</th>";
     echo "<td>";
     echo $tt->getBeginHiddenFieldValue('locations_id');
     if ($canupdate) {
         Location::dropdown(array('value' => $ticket->fields['locations_id'], 'entity' => $ticket->fields['entities_id']));
     } else {
         echo Dropdown::getDropdownName('glpi_locations', $ticket->fields["locations_id"]);
     }
     echo $tt->getEndHiddenFieldValue('locations_id', $ticket);
     echo "</td></tr>";
     echo "</table>";
     if ($ID) {
         $values['canupdate'] = $canupdate;
         $ticket->showActorsPartForm($ID, $values);
     }
     $view_linked_tickets = $ID || $canupdate;
     echo "<table class='tab_cadre_fixe' id='mainformtable4'>";
     echo "<tr class='tab_bg_1'>";
     echo "<th width='{$colsize1}%'>" . $tt->getBeginHiddenFieldText('name');
     printf(__('%1$s%2$s'), __('Title'), $tt->getMandatoryMark('name'));
     echo $tt->getEndHiddenFieldText('name') . "</th>";
     echo "<td width='" . (100 - $colsize1) . "%' colspan='3'>";
     if (!$ID || $canupdate_descr) {
         echo $tt->getBeginHiddenFieldValue('name');
         $rand = mt_rand();
         echo "<script type='text/javascript' >\n";
         echo "function showName{$rand}() {\n";
         echo "Ext.get('name{$rand}').setDisplayed('none');";
         $params = array('maxlength' => 250, 'size' => 90, 'name' => 'name', 'data' => rawurlencode($ticket->fields["name"]));
         Ajax::updateItemJsCode("viewname{$rand}", $CFG_GLPI["root_doc"] . "/ajax/inputtext.php", $params);
         echo "}";
         echo "</script>\n";
         echo "<div id='name{$rand}' class='tracking left' onClick='showName{$rand}()'>\n";
         if (empty($ticket->fields["name"])) {
             _e('Without title');
         } else {
             echo $ticket->fields["name"];
         }
         echo "</div>\n";
         echo "<div id='viewname{$rand}'>\n";
         echo "</div>\n";
         if (!$ID) {
             echo "<script type='text/javascript' >\n\n            showName{$rand}();\n            </script>";
         }
         echo $tt->getEndHiddenFieldValue('name', $ticket);
     } else {
         if (empty($ticket->fields["name"])) {
             _e('Without title');
         } else {
             echo $ticket->fields["name"];
         }
     }
     echo "</td>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<th width='{$colsize1}%'>" . $tt->getBeginHiddenFieldText('content');
     printf(__('%1$s%2$s'), __('Description'), $tt->getMandatoryMark('content'));
     echo $tt->getEndHiddenFieldText('content') . "</th>";
     echo "<td width='" . (100 - $colsize1) . "%' colspan='3'>";
     // * Added by plugin surveyticket
     $psTicketTemplate = new PluginSurveyticketTicketTemplate();
     $psSurvey = new PluginSurveyticketSurvey();
     $plugin_surveyticket_surveys_id = 0;
     $a_tickettemplates = current($psTicketTemplate->find("`tickettemplates_id`='" . $tt->fields['id'] . "'\n                                                      AND `type`='" . $values['type'] . "'\n                                                      AND `is_central`='1'"));
     if (isset($a_tickettemplates['plugin_surveyticket_surveys_id'])) {
         $psSurvey = new PluginSurveyticketSurvey();
         $psSurvey->getFromDB($a_tickettemplates['plugin_surveyticket_surveys_id']);
         if ($psSurvey->fields['is_active'] == 1) {
             $plugin_surveyticket_surveys_id = $a_tickettemplates['plugin_surveyticket_surveys_id'];
             $psSurvey = new PluginSurveyticketSurvey();
             $psSurvey->startSurvey($plugin_surveyticket_surveys_id);
         }
     } else {
         // End of adding by plugin
         if (!$ID || $canupdate_descr) {
             // Admin =oui on autorise la modification de la description
             echo $tt->getBeginHiddenFieldValue('content');
             $rand = mt_rand();
             echo "<script type='text/javascript' >\n";
             echo "function showDesc{$rand}() {\n";
             echo "Ext.get('desc{$rand}').setDisplayed('none');";
             $params = array('rows' => 6, 'cols' => 90, 'name' => 'content', 'data' => rawurlencode($ticket->fields["content"]));
             Ajax::updateItemJsCode("viewdesc{$rand}", $CFG_GLPI["root_doc"] . "/ajax/textarea.php", $params);
             echo "}";
             echo "</script>\n";
             echo "<div id='desc{$rand}' class='tracking' onClick='showDesc{$rand}()'>\n";
             if (!empty($ticket->fields["content"])) {
                 echo nl2br($ticket->fields["content"]);
             } else {
                 _e('Empty description');
             }
             echo "</div>\n";
             echo "<div id='viewdesc{$rand}'></div>\n";
             if (!$ID) {
                 echo "<script type='text/javascript' >\n\n            showDesc{$rand}();\n            </script>";
             }
             echo $tt->getEndHiddenFieldValue('content', $ticket);
         } else {
             echo nl2br($ticket->fields["content"]);
         }
         // * Added by plugin surveyticket
     }
     // End of adding by plugin
     echo "</td>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     // Permit to add doc when creating a ticket
     if (!$ID) {
         echo "<th width='{$colsize1}%'>" . sprintf(__('File (%s)'), Document::getMaxUploadSize());
         echo "<img src='" . $CFG_GLPI["root_doc"] . "/pics/aide.png' class='pointer' alt=\"" . __s('Help') . "\" onclick=\"window.open('" . $CFG_GLPI["root_doc"] . "/front/documenttype.list.php','Help','scrollbars=1,resizable=1,width=1000," . "height=800')\">";
         echo "&nbsp;";
         Ticket::showDocumentAddButton();
         echo "</th>";
         echo "<td width='{$colsize2}%'>";
         echo "<div id='uploadfiles'><input type='file' name='filename[]' size='20'></div></td>";
     } else {
         echo "<th colspan='2'>";
         $docnb = Document_Item::countForItem($ticket);
         echo "<a href=\"" . $ticket->getLinkURL() . "&amp;forcetab=Document_Item\$1\">";
         //TRANS: %d is the document number
         echo sprintf(_n('%d associated document', '%d associated documents', $docnb), $docnb);
         echo "</a></th>";
     }
     if ($view_linked_tickets) {
         echo "<th width='{$colsize3}%'>" . _n('Linked ticket', 'Linked tickets', 2);
         $rand_linked_ticket = mt_rand();
         if ($canupdate) {
             echo "&nbsp;";
             echo "<img onClick=\"Ext.get('linkedticket{$rand_linked_ticket}').setDisplayed('block')\"\n                   title=\"" . __s('Add') . "\" alt=\"" . __s('Add') . "\"\n                   class='pointer' src='" . $CFG_GLPI["root_doc"] . "/pics/add_dropdown.png'>";
         }
         echo '</th>';
         echo "<td width='{$colsize4}%'>";
         if ($canupdate) {
             echo "<div style='display:none' id='linkedticket{$rand_linked_ticket}'>";
             Ticket_Ticket::dropdownLinks('_link[link]', isset($values["_link"]) ? $values["_link"]['link'] : '');
             printf(__('%1$s: %2$s'), __('Ticket'), __('ID'));
             echo "<input type='hidden' name='_link[tickets_id_1]' value='{$ID}'>\n";
             echo "<input type='text' name='_link[tickets_id_2]'\n                   value='" . (isset($values["_link"]) ? $values["_link"]['tickets_id_2'] : '') . "'\n                   size='10'>\n";
             echo "&nbsp;";
             echo "</div>";
             if (isset($values["_link"]) && !empty($values["_link"]['tickets_id_2'])) {
                 echo "<script language='javascript'>Ext.get('linkedticket{$rand_linked_ticket}').\n                      setDisplayed('block');</script>";
             }
         }
         Ticket_Ticket::displayLinkedTicketsTo($ID);
         echo "</td>";
     } else {
         echo "<td></td>";
     }
     echo "</tr>";
     if ((!$ID || $canupdate || $canupdate_descr || Session::haveRight("assign_ticket", "1") || Session::haveRight("steal_ticket", "1")) && !$options['template_preview']) {
         echo "<tr class='tab_bg_1'>";
         if ($ID) {
             if (Session::haveRight('delete_ticket', 1)) {
                 echo "<td class='tab_bg_2 center' colspan='2'>";
                 if ($ticket->fields["is_deleted"] == 1) {
                     echo "<input type='submit' class='submit' name='restore' value='" . _sx('button', 'Restore') . "'></td>";
                 } else {
                     echo "<input type='submit' class='submit' name='update' value='" . _sx('button', 'Save') . "'></td>";
                 }
                 echo "<td class='tab_bg_2 center' colspan='2'>";
                 if ($ticket->fields["is_deleted"] == 1) {
                     echo "<input type='submit' class='submit' name='purge' value='" . _sx('button', 'Delete permanently') . "' " . Html::addConfirmationOnAction(__('Confirm the final deletion?')) . ">";
                 } else {
                     echo "<input type='submit' class='submit' name='delete' value='" . _sx('button', 'Put in dustbin') . "'></td>";
                 }
             } else {
                 echo "<td class='tab_bg_2 center' colspan='4'>";
                 echo "<input type='submit' class='submit' name='update' value='" . _sx('button', 'Save') . "'>";
             }
             echo "<input type='hidden' name='_read_date_mod' value='" . $ticket->getField('date_mod') . "'>";
         } else {
             echo "<td class='tab_bg_2 center' colspan='4'>";
             echo "<input type='submit' name='add' value=\"" . _sx('button', 'Add') . "\" class='submit'>";
             if ($tt->isField('id') && $tt->fields['id'] > 0) {
                 echo "<input type='hidden' name='_tickettemplates_id' value='" . $tt->fields['id'] . "'>";
                 echo "<input type='hidden' name='_predefined_fields'\n                      value=\"" . Toolbox::prepareArrayForInput($predefined_fields) . "\">";
             }
         }
     }
     echo "</table>";
     echo "<input type='hidden' name='id' value='{$ID}'>";
     echo "</div>";
     if (!$options['template_preview']) {
         Html::closeForm();
         $ticket->addDivForTabs();
     }
     return true;
 }
示例#17
0
 static function pdfMain(PluginPdfSimplePDF $pdf, Ticket $job)
 {
     global $CFG_GLPI, $DB;
     $ID = $job->getField('id');
     if (!$job->can($ID, 'r')) {
         return false;
     }
     $pdf->setColumnsSize(100);
     $pdf->displayTitle('<b>' . (empty($job->fields["name"]) ? __('Without title') : ($name = $job->fields["name"])) . '</b>');
     if (count($_SESSION['glpiactiveentities']) > 1) {
         $entity = " (" . Dropdown::getDropdownName("glpi_entities", $job->fields["entities_id"]) . ")";
     } else {
         $entity = '';
     }
     $pdf->setColumnsSize(50, 50);
     $recipient_name = '';
     if ($job->fields["users_id_recipient"]) {
         $recipient = new User();
         $recipient->getFromDB($job->fields["users_id_recipient"]);
         $recipient_name = $recipient->getName();
     }
     $sla = $due = $commentsla = '';
     if ($job->fields['due_date']) {
         $due = "<b><i>" . sprintf(__('%1$s: %2$s'), __('Due date') . "</b></i>", Html::convDateTime($job->fields['due_date']));
     }
     $pdf->displayLine("<b><i>" . sprintf(__('%1$s: %2$s'), __('Opening date') . "</i></b>", Html::convDateTime($job->fields["date"])), $due);
     $pdf->setColumnsSize(100);
     if ($job->fields["slas_id"] > 0) {
         $sla = "<b><i>" . sprintf(__('%1$s: %2$s'), __('SLA') . "</b></i>", Html::clean(Dropdown::getDropdownName("glpi_slas", $job->fields["slas_id"])));
         $slalevel = new SlaLevel();
         if ($slalevel->getFromDB($job->fields['slalevels_id'])) {
             $commentsla = "<b><i>" . sprintf(__('%1$s: %2$s'), __('Escalation level') . "</b></i>", $slalevel->getName());
         }
         $nextaction = new SlaLevel_Ticket();
         if ($nextaction->getFromDBForTicket($job->fields["id"])) {
             $commentsla .= " <b><i>" . sprintf(__('Next escalation: %s') . "</b></i>", Html::convDateTime($nextaction->fields['date']));
             if ($slalevel->getFromDB($nextaction->fields['slalevels_id'])) {
                 $commentsla .= " <b><i>" . sprintf(__('%1$s: %2$s'), __('Escalation level'), $slalevel->getName());
             }
         }
         $pdf->displayText($sla, $commentsla, 1);
     }
     $pdf->setColumnsSize(50, 50);
     $lastupdate = Html::convDateTime($job->fields["date_mod"]);
     if ($job->fields['users_id_lastupdater'] > 0) {
         $lastupdate = sprintf(__('%1$s by %2$s'), $lastupdate, getUserName($job->fields["users_id_lastupdater"]));
     }
     $pdf->displayLine('<b><i>' . sprintf(__('%1$s: %2$s'), __('By') . "</i></b>", $recipient_name), '<b><i>' . sprintf(__('%1$s: %2$s'), __('Last update') . '</i></b>', $lastupdate));
     $pdf->displayLine("<b><i>" . sprintf(__('%1$s: %2$s'), __('Type') . "</i></b>", Html::clean(Ticket::getTicketTypeName($job->fields["type"]))), "<b><i>" . sprintf(__('%1$s: %2$s'), __('Category') . "</i></b>", Html::clean(Dropdown::getDropdownName("glpi_itilcategories", $job->fields["itilcategories_id"]))));
     $status = '';
     if (in_array($job->fields["status"], $job->getSolvedStatusArray()) || in_array($job->fields["status"], $job->getClosedStatusArray())) {
         $status = sprintf(__('%1$s %2$s'), '-', Html::convDateTime($job->fields["solvedate"]));
     }
     if (in_array($job->fields["status"], $job->getClosedStatusArray())) {
         $status = sprintf(__('%1$s %2$s'), '-', Html::convDateTime($job->fields["closedate"]));
     }
     if ($job->fields["status"] == Ticket::WAITING) {
         $status = sprintf(__('%1$s %2$s'), '-', Html::convDateTime($job->fields['begin_waiting_date']));
     }
     $pdf->displayLine("<b><i>" . sprintf(__('%1$s: %2$s'), __('Status') . "</i></b>", Html::clean($job->getStatus($job->fields["status"])) . $status), "<b><i>" . sprintf(__('%1$s: %2$s'), __('Request source') . "</i></b>", Html::clean(Dropdown::getDropdownName('glpi_requesttypes', $job->fields['requesttypes_id']))));
     $pdf->displayLine("<b><i>" . sprintf(__('%1$s: %2$s'), __('Urgency') . "</i></b>", Html::clean($job->getUrgencyName($job->fields["urgency"]))), "<b><i>" . sprintf(__('%1$s: %2$s'), __('Approval') . "</i></b>", TicketValidation::getStatus($job->fields['global_validation'])));
     $pdf->displayLine("<b><i>" . sprintf(__('%1$s: %2$s'), __('Impact') . "</i></b>", Html::clean($job->getImpactName($job->fields["impact"]))));
     $pdf->displayLine("<b><i>" . sprintf(__('%1$s: %2$s'), __('Priority') . "</i></b>", Html::clean($job->getPriorityName($job->fields["priority"]))), "<b><i>" . sprintf(__('%1$s: %2$s'), __('Location') . "</i></b>", Html::clean(Dropdown::getDropdownName("glpi_locations", $job->fields["locations_id"]))));
     // Item
     $name = "<b><i>" . sprintf(__('%1$s: %2$s'), __('Associated element') . "</i></b>", '');
     $commentitem = '';
     $pdf->setColumnsSize(100);
     if ($job->fields['itemtype'] && ($item = getItemForItemtype($job->fields['itemtype']))) {
         if ($item->getFromDB($job->fields["items_id"])) {
             $name = "<b><i>" . sprintf(__('%1$s: %2$s'), __('Associated element') . "</i></b>", $item->getNameID());
             if (isset($item->fields["serial"])) {
                 $commentitem = ", <b><i>" . sprintf(__('%1$s: %2$s'), __('Serial number') . "</i></b>", Html::clean($item->fields["serial"]));
                 Html::clean($item->fields["serial"]);
             }
             if (isset($item->fields["otherserial"])) {
                 $commentitem .= ", <b><i>" . sprintf(__('%1$s: %2$s'), __('Inventory number') . "</i></b>", Html::clean($item->fields["otherserial"]));
             }
             if (isset($item->fields["locations_id"])) {
                 $commentitem .= ", <b><i>" . sprintf(__('%1$s: %2$s'), __('Location') . "</i></b>", Html::clean(Dropdown::getDropdownName("glpi_locations", $item->fields["locations_id"])));
             }
         }
     }
     $pdf->displayText($name, $commentitem, 1);
     $pdf->setColumnsSize(50, 50);
     // Requester
     $users = array();
     $listusers = '';
     $requester = '<b><i>' . sprintf(__('%1$s: %2$s') . "</i></b>", __('Requester'), $listusers);
     foreach ($job->getUsers(CommonITILActor::REQUESTER) as $d) {
         if ($d['users_id']) {
             $tmp = Html::clean(getUserName($d['users_id']));
             if ($d['alternative_email']) {
                 $tmp .= ' (' . $d['alternative_email'] . ')';
             }
         } else {
             $tmp = $d['alternative_email'];
         }
         $users[] = $tmp;
     }
     if (count($users)) {
         $listusers = implode(', ', $users);
     }
     $pdf->displayText($requester, $listusers, 1);
     $groups = array();
     $listgroups = '';
     $requestergroup = '<b><i>' . sprintf(__('%1$s: %2$s') . "</i></b>", __('Requester group'), $listgroups);
     foreach ($job->getGroups(CommonITILActor::REQUESTER) as $d) {
         $groups[] = Html::clean(Dropdown::getDropdownName("glpi_groups", $d['groups_id']));
     }
     if (count($groups)) {
         $listgroups = implode(', ', $groups);
     }
     $pdf->displayText($requestergroup, $listgroups, 1);
     // Observer
     $users = array();
     $listusers = '';
     $watcher = '<b><i>' . sprintf(__('%1$s: %2$s') . "</i></b>", __('Watcher'), $listusers);
     foreach ($job->getUsers(CommonITILActor::OBSERVER) as $d) {
         if ($d['users_id']) {
             $tmp = Html::clean(getUserName($d['users_id']));
             if ($d['alternative_email']) {
                 $tmp .= ' (' . $d['alternative_email'] . ')';
             }
         } else {
             $tmp = $d['alternative_email'];
         }
         $users[] = $tmp;
     }
     if (count($users)) {
         $listusers = implode(', ', $users);
     }
     $pdf->displayText($watcher, $listusers, 1);
     $groups = array();
     $listgroups = '';
     $watchergroup = '<b><i>' . sprintf(__('%1$s: %2$s') . "</i></b>", __('Watcher group'), $listgroups);
     foreach ($job->getGroups(CommonITILActor::OBSERVER) as $d) {
         $groups[] = Html::clean(Dropdown::getDropdownName("glpi_groups", $d['groups_id']));
     }
     if (count($groups)) {
         $listgroups = implode(', ', $groups);
     }
     $pdf->displayText($watchergroup, $listgroups, 1);
     // Assign to
     $users = array();
     $listusers = '';
     $assign = '<b><i>' . sprintf(__('%1$s: %2$s') . "</i></b>", __('User assigned'), $listusers);
     foreach ($job->getUsers(CommonITILActor::ASSIGN) as $d) {
         if ($d['users_id']) {
             $tmp = Html::clean(getUserName($d['users_id']));
             if ($d['alternative_email']) {
                 $tmp .= ' (' . $d['alternative_email'] . ')';
             }
         } else {
             $tmp = $d['alternative_email'];
         }
         $users[] = $tmp;
     }
     if (count($users)) {
         $listusers = implode(', ', $users);
     }
     $pdf->displayText($assign, $listusers, 1);
     $groups = array();
     $listgroups = '';
     $assigngroup = '<b><i>' . sprintf(__('%1$s: %2$s') . "</i></b>", __('Group assigned'), $listgroups);
     foreach ($job->getGroups(CommonITILActor::ASSIGN) as $d) {
         $groups[] = Html::clean(Dropdown::getDropdownName("glpi_groups", $d['groups_id']));
     }
     if (count($groups)) {
         $listgroups = implode(', ', $groups);
     }
     $pdf->displayText($assigngroup, $listgroups, 1);
     // Supplier
     $suppliers = array();
     $listsuppliers = '';
     $assignsupplier = '<b><i>' . sprintf(__('%1$s: %2$s') . "</i></b>", __('Supplier assigned'), $listsuppliers);
     foreach ($job->getSuppliers(CommonITILActor::ASSIGN) as $d) {
         $suppliers[] = Html::clean(Dropdown::getDropdownName("glpi_suppliers", $d['suppliers_id']));
     }
     if (count($suppliers)) {
         $listsuppliers = implode(', ', $suppliers);
     }
     $pdf->displayText($assignsupplier, $listsuppliers, 1);
     $pdf->setColumnsSize(100);
     $pdf->displayLine("<b><i>" . sprintf(__('%1$s: %2$s'), __('Title') . "</i></b>", $job->fields["name"]));
     $pdf->displayText("<b><i>" . sprintf(__('%1$s: %2$s'), __('Description') . "</i></b>", $job->fields['content']));
     // Linked tickets
     $tickets = Ticket_Ticket::getLinkedTicketsTo($ID);
     if (is_array($tickets) && count($tickets)) {
         $ticket = new Ticket();
         foreach ($tickets as $linkID => $data) {
             $tmp = sprintf(__('%1$s %2$s'), Ticket_Ticket::getLinkName($data['link']), sprintf(__('%1$s %2$s'), __('ID'), $data['tickets_id']));
             if ($ticket->getFromDB($data['tickets_id'])) {
                 $tmp = sprintf(__('%1$s: %2$s'), $tmp, $ticket->getName());
             }
             $jobs[] = $tmp;
             $jobs = implode("\n", $jobs);
         }
         $linked = "<b><i>" . sprintf(__('%1$s: %2$s') . "</i></b>", __('Linked tickets'), '');
         $pdf->displayText($linked, $jobs, 1);
     }
     $pdf->displaySpace();
 }
 function showForm($ID, $options = array())
 {
     global $DB, $CFG_GLPI;
     $default_values = self::getDefaultValues();
     // Get default values from posted values on reload form
     // On get because of tabs
     if (!isset($options['template_preview'])) {
         if (isset($_GET)) {
             $values = Html::cleanPostForTextArea($_GET);
         }
     }
     // Restore saved value or override with page parameter
     $saved = $this->restoreInput();
     foreach ($default_values as $name => $value) {
         if (!isset($values[$name])) {
             if (isset($saved[$name])) {
                 $values[$name] = $saved[$name];
             } else {
                 $values[$name] = $value;
             }
         }
     }
     if (isset($values['content'])) {
         // Clean new lines to be fix encoding
         $order = array('\\r', '\\n', "\\");
         $replace = array("", "", "");
         $values['content'] = str_replace($order, $replace, $values['content']);
     }
     if (isset($values['name'])) {
         $values['name'] = str_replace("\\", "", $values['name']);
     }
     if (!$ID) {
         // Override defaut values from projecttask if needed
         if (isset($options['_projecttasks_id'])) {
             $pt = new ProjectTask();
             if ($pt->getFromDB($options['_projecttasks_id'])) {
                 $values['name'] = $pt->getField('name');
                 $values['content'] = $pt->getField('name');
             }
         }
     }
     // Check category / type validity
     if ($values['itilcategories_id']) {
         $cat = new ITILCategory();
         if ($cat->getFromDB($values['itilcategories_id'])) {
             switch ($values['type']) {
                 case self::INCIDENT_TYPE:
                     if (!$cat->getField('is_incident')) {
                         $values['itilcategories_id'] = 0;
                     }
                     break;
                 case self::DEMAND_TYPE:
                     if (!$cat->getField('is_request')) {
                         $values['itilcategories_id'] = 0;
                     }
                     break;
                 default:
                     break;
             }
         }
     }
     // Default check
     if ($ID > 0) {
         $this->check($ID, READ);
     } else {
         // Create item
         $this->check(-1, CREATE, $values);
     }
     if (!$ID) {
         $this->userentities = array();
         if ($values["_users_id_requester"]) {
             //Get all the user's entities
             $all_entities = Profile_User::getUserEntities($values["_users_id_requester"], true, true);
             //For each user's entity, check if the technician which creates the ticket have access to it
             foreach ($all_entities as $tmp => $ID_entity) {
                 if (Session::haveAccessToEntity($ID_entity)) {
                     $this->userentities[] = $ID_entity;
                 }
             }
         }
         $this->countentitiesforuser = count($this->userentities);
         if ($this->countentitiesforuser > 0 && !in_array($this->fields["entities_id"], $this->userentities)) {
             // If entity is not in the list of user's entities,
             // then use as default value the first value of the user's entites list
             $this->fields["entities_id"] = $this->userentities[0];
             // Pass to values
             $values['entities_id'] = $this->userentities[0];
         }
     }
     if ($values['type'] <= 0) {
         $values['type'] = Entity::getUsedConfig('tickettype', $values['entities_id'], '', Ticket::INCIDENT_TYPE);
     }
     if (!isset($options['template_preview'])) {
         $options['template_preview'] = 0;
     }
     // Load ticket template if available :
     if ($ID) {
         $tt = $this->getTicketTemplateToUse($options['template_preview'], $this->fields['type'], $this->fields['itilcategories_id'], $this->fields['entities_id']);
     } else {
         $tt = $this->getTicketTemplateToUse($options['template_preview'], $values['type'], $values['itilcategories_id'], $values['entities_id']);
     }
     // Predefined fields from template : reset them
     if (isset($values['_predefined_fields'])) {
         $values['_predefined_fields'] = Toolbox::decodeArrayFromInput($values['_predefined_fields']);
     } else {
         $values['_predefined_fields'] = array();
     }
     // Store predefined fields to be able not to take into account on change template
     // Only manage predefined values on ticket creation
     $predefined_fields = array();
     if (!$ID) {
         if (isset($tt->predefined) && count($tt->predefined)) {
             foreach ($tt->predefined as $predeffield => $predefvalue) {
                 if (isset($default_values[$predeffield])) {
                     // Is always default value : not set
                     // Set if already predefined field
                     // Set if ticket template change
                     if (count($values['_predefined_fields']) == 0 && $values[$predeffield] == $default_values[$predeffield] || isset($values['_predefined_fields'][$predeffield]) && $values[$predeffield] == $values['_predefined_fields'][$predeffield] || isset($values['_tickettemplates_id']) && $values['_tickettemplates_id'] != $tt->getID()) {
                         // Load template data
                         $values[$predeffield] = $predefvalue;
                         $this->fields[$predeffield] = $predefvalue;
                         $predefined_fields[$predeffield] = $predefvalue;
                     }
                 }
             }
             // All predefined override : add option to say predifined exists
             if (count($predefined_fields) == 0) {
                 $predefined_fields['_all_predefined_override'] = 1;
             }
         } else {
             // No template load : reset predefined values
             if (count($values['_predefined_fields'])) {
                 foreach ($values['_predefined_fields'] as $predeffield => $predefvalue) {
                     if ($values[$predeffield] == $predefvalue) {
                         $values[$predeffield] = $default_values[$predeffield];
                     }
                 }
             }
         }
     }
     // Put ticket template on $values for actors
     $values['_tickettemplate'] = $tt;
     $canupdate = Session::haveRight(self::$rightname, UPDATE);
     $canpriority = Session::haveRight(self::$rightname, self::CHANGEPRIORITY);
     $canstatus = $canupdate;
     if ($ID && in_array($this->fields['status'], $this->getClosedStatusArray())) {
         $canupdate = false;
         // No update for actors
         $values['_noupdate'] = true;
     }
     $showuserlink = 0;
     if (Session::haveRight('user', READ)) {
         $showuserlink = 1;
     }
     if ($options['template_preview']) {
         // Add all values to fields of tickets for template preview
         foreach ($values as $key => $val) {
             if (!isset($this->fields[$key])) {
                 $this->fields[$key] = $val;
             }
         }
     }
     // In percent
     $colsize1 = '13';
     $colsize2 = '29';
     $colsize3 = '13';
     $colsize4 = '45';
     $canupdate_descr = $canupdate || $this->fields['status'] == self::INCOMING && $this->isUser(CommonITILActor::REQUESTER, Session::getLoginUserID()) && $this->numberOfFollowups() == 0 && $this->numberOfTasks() == 0;
     if (!$options['template_preview']) {
         echo "<form method='post' name='form_ticket' enctype='multipart/form-data' action='" . $CFG_GLPI["root_doc"] . "/front/ticket.form.php'>";
         if (isset($options['_projecttasks_id'])) {
             echo "<input type='hidden' name='_projecttasks_id' value='" . $options['_projecttasks_id'] . "'>";
         }
     }
     echo "<div class='spaced' id='tabsbody'>";
     echo "<table class='tab_cadre_fixe' id='mainformtable'>";
     // Optional line
     $ismultientities = Session::isMultiEntitiesMode();
     echo "<tr class='headerRow'>";
     echo "<th colspan='4'>";
     if ($ID) {
         $text = sprintf(__('%1$s - %2$s'), $this->getTypeName(1), sprintf(__('%1$s: %2$s'), __('ID'), $ID));
         if ($ismultientities) {
             $text = sprintf(__('%1$s (%2$s)'), $text, Dropdown::getDropdownName('glpi_entities', $this->fields['entities_id']));
         }
         echo $text;
     } else {
         if ($ismultientities) {
             printf(__('The ticket will be added in the entity %s'), Dropdown::getDropdownName("glpi_entities", $this->fields['entities_id']));
         } else {
             _e('New ticket');
         }
     }
     echo "</th></tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<th width='{$colsize1}%'>";
     echo $tt->getBeginHiddenFieldText('date');
     if (!$ID) {
         printf(__('%1$s%2$s'), __('Opening date'), $tt->getMandatoryMark('date'));
     } else {
         _e('Opening date');
     }
     echo $tt->getEndHiddenFieldText('date');
     echo "</th>";
     echo "<td width='{$colsize2}%'>";
     echo $tt->getBeginHiddenFieldValue('date');
     $date = $this->fields["date"];
     if ($canupdate) {
         Html::showDateTimeField("date", array('value' => $date, 'timestep' => 1, 'maybeempty' => false));
     } else {
         echo Html::convDateTime($date);
     }
     echo $tt->getEndHiddenFieldValue('date', $this);
     echo "</td>";
     // SLA
     echo "<th width='{$colsize3}%'>" . $tt->getBeginHiddenFieldText('due_date');
     if (!$ID) {
         printf(__('%1$s%2$s'), __('Due date'), $tt->getMandatoryMark('due_date'));
     } else {
         _e('Due date');
     }
     echo $tt->getEndHiddenFieldText('due_date');
     echo "</th>";
     echo "<td width='{$colsize4}%' class='nopadding'>";
     if ($ID) {
         if ($this->fields["slas_id"] > 0) {
             echo "<table width='100%'><tr><td class='nopadding'>";
             echo Html::convDateTime($this->fields["due_date"]);
             echo "</td><td class='b'>" . __('SLA') . "</td>";
             echo "<td class='nopadding'>";
             echo Dropdown::getDropdownName("glpi_slas", $this->fields["slas_id"]);
             $commentsla = "";
             $slalevel = new SlaLevel();
             if ($slalevel->getFromDB($this->fields['slalevels_id'])) {
                 $commentsla .= '<span class="b spaced">' . sprintf(__('%1$s: %2$s'), __('Escalation level'), $slalevel->getName()) . '</span><br>';
             }
             $nextaction = new SlaLevel_Ticket();
             if ($nextaction->getFromDBForTicket($this->fields["id"])) {
                 $commentsla .= '<span class="b spaced">' . sprintf(__('Next escalation: %s'), Html::convDateTime($nextaction->fields['date'])) . '</span><br>';
                 if ($slalevel->getFromDB($nextaction->fields['slalevels_id'])) {
                     $commentsla .= '<span class="b spaced">' . sprintf(__('%1$s: %2$s'), __('Escalation level'), $slalevel->getName()) . '</span>';
                 }
             }
             $slaoptions = array();
             if (Session::haveRight('config', READ)) {
                 $slaoptions['link'] = Toolbox::getItemTypeFormURL('SLA') . "?id=" . $this->fields["slas_id"];
             }
             Html::showToolTip($commentsla, $slaoptions);
             if ($canupdate) {
                 echo "&nbsp;";
                 Html::showSimpleForm($this->getFormURL(), 'sla_delete', _x('button', 'Delete permanently'), array('id' => $this->getID()));
             }
             echo "</td>";
             echo "</tr></table>";
         } else {
             echo "<table width='100%'><tr><td class='nopadding'>";
             echo $tt->getBeginHiddenFieldValue('due_date');
             if ($canupdate) {
                 Html::showDateTimeField("due_date", array('value' => $this->fields["due_date"], 'timestep' => 1, 'maybeempty' => true));
             } else {
                 echo Html::convDateTime($this->fields["due_date"]);
             }
             echo $tt->getEndHiddenFieldValue('due_date', $this);
             echo "</td>";
             if ($canupdate) {
                 echo "<td>";
                 echo $tt->getBeginHiddenFieldText('slas_id');
                 echo "<span id='sla_action'>";
                 echo "<a class='vsubmit' " . Html::addConfirmationOnAction(array(__('The assignment of a SLA to a ticket causes the recalculation of the due date.'), __("Escalations defined in the SLA will be triggered under this new date.")), "cleanhide('sla_action');cleandisplay('sla_choice');") . ">" . __('Assign a SLA') . '</a>';
                 echo "</span>";
                 echo "<div id='sla_choice' style='display:none'>";
                 echo "<span  class='b'>" . __('SLA') . "</span>&nbsp;";
                 Sla::dropdown(array('entity' => $this->fields["entities_id"], 'value' => $this->fields["slas_id"]));
                 echo "</div>";
                 echo $tt->getEndHiddenFieldText('slas_id');
                 echo "</td>";
             }
             echo "</tr></table>";
         }
     } else {
         // New Ticket
         echo "<table width='100%'><tr><td width='40%' class='nopadding'>";
         if ($this->fields["due_date"] == 'NULL') {
             $this->fields["due_date"] = '';
         }
         echo $tt->getBeginHiddenFieldValue('due_date');
         Html::showDateTimeField("due_date", array('value' => $this->fields["due_date"], 'timestep' => 1, 'maybeempty' => false, 'canedit' => $canupdate));
         echo $tt->getEndHiddenFieldValue('due_date', $this);
         echo "</td>";
         if ($canupdate) {
             echo "<td class='nopadding b'>" . $tt->getBeginHiddenFieldText('slas_id');
             printf(__('%1$s%2$s'), __('SLA'), $tt->getMandatoryMark('slas_id'));
             echo $tt->getEndHiddenFieldText('slas_id') . "</td>";
             echo "<td class='nopadding'>" . $tt->getBeginHiddenFieldValue('slas_id');
             Sla::dropdown(array('entity' => $this->fields["entities_id"], 'value' => $this->fields["slas_id"]));
             echo $tt->getEndHiddenFieldValue('slas_id', $this);
             echo "</td>";
         }
         echo "</tr></table>";
     }
     echo "</td></tr>";
     if ($ID) {
         echo "<tr class='tab_bg_1'>";
         echo "<th width='{$colsize1}%'>" . __('By') . "</th>";
         echo "<td width='{$colsize2}%'>";
         if ($canupdate) {
             User::dropdown(array('name' => 'users_id_recipient', 'value' => $this->fields["users_id_recipient"], 'entity' => $this->fields["entities_id"], 'right' => 'all'));
         } else {
             echo getUserName($this->fields["users_id_recipient"], $showuserlink);
         }
         echo "</td>";
         echo "<th width='{$colsize3}%'>" . __('Last update') . "</th>";
         echo "<td width='{$colsize4}%'>";
         if ($this->fields['users_id_lastupdater'] > 0) {
             //TRANS: %1$s is the update date, %2$s is the last updater name
             printf(__('%1$s by %2$s'), Html::convDateTime($this->fields["date_mod"]), getUserName($this->fields["users_id_lastupdater"], $showuserlink));
         }
         echo "</td>";
         echo "</tr>";
     }
     if ($ID && (in_array($this->fields["status"], $this->getSolvedStatusArray()) || in_array($this->fields["status"], $this->getClosedStatusArray()))) {
         echo "<tr class='tab_bg_1'>";
         echo "<th width='{$colsize1}%'>" . __('Resolution date') . "</th>";
         echo "<td width='{$colsize2}%'>";
         Html::showDateTimeField("solvedate", array('value' => $this->fields["solvedate"], 'timestep' => 1, 'maybeempty' => false, 'canedit' => $canupdate));
         echo "</td>";
         if (in_array($this->fields["status"], $this->getClosedStatusArray())) {
             echo "<th width='{$colsize3}%'>" . __('Close date') . "</th>";
             echo "<td width='{$colsize4}%'>";
             Html::showDateTimeField("closedate", array('value' => $this->fields["closedate"], 'timestep' => 1, 'maybeempty' => false, 'canedit' => $canupdate));
             echo "</td>";
         } else {
             echo "<td colspan='2'>&nbsp;</td>";
         }
         echo "</tr>";
     }
     if ($ID) {
         echo "</table>";
         echo "<table  class='tab_cadre_fixe' id='mainformtable2'>";
     }
     echo "<tr class='tab_bg_1'>";
     echo "<th width='{$colsize1}%'>" . sprintf(__('%1$s%2$s'), __('Type'), $tt->getMandatoryMark('type')) . "</th>";
     echo "<td width='{$colsize2}%'>";
     // Permit to set type when creating ticket without update right
     if ($canupdate || !$ID) {
         $opt = array('value' => $this->fields["type"]);
         /// Auto submit to load template
         if (!$ID) {
             $opt['on_change'] = 'this.form.submit()';
         }
         $rand = self::dropdownType('type', $opt);
         if ($ID) {
             $params = array('type' => '__VALUE__', 'entity_restrict' => $this->fields['entities_id'], 'value' => $this->fields['itilcategories_id'], 'currenttype' => $this->fields['type']);
             Ajax::updateItemOnSelectEvent("dropdown_type{$rand}", "show_category_by_type", $CFG_GLPI["root_doc"] . "/ajax/dropdownTicketCategories.php", $params);
         }
     } else {
         echo self::getTicketTypeName($this->fields["type"]);
     }
     echo "</td>";
     echo "<th width='{$colsize3}%'>" . sprintf(__('%1$s%2$s'), __('Category'), $tt->getMandatoryMark('itilcategories_id')) . "</th>";
     echo "<td width='{$colsize4}%'>";
     // Permit to set category when creating ticket without update right
     if ($canupdate || !$ID || $canupdate_descr) {
         $opt = array('value' => $this->fields["itilcategories_id"], 'entity' => $this->fields["entities_id"]);
         if ($_SESSION["glpiactiveprofile"]["interface"] == "helpdesk") {
             $opt['condition'] = "`is_helpdeskvisible`='1' AND ";
         } else {
             $opt['condition'] = '';
         }
         /// Auto submit to load template
         if (!$ID) {
             $opt['on_change'] = 'this.form.submit()';
         }
         /// if category mandatory, no empty choice
         /// no empty choice is default value set on ticket creation, else yes
         if (($ID || $values['itilcategories_id']) && $tt->isMandatoryField("itilcategories_id") && $this->fields["itilcategories_id"] > 0) {
             $opt['display_emptychoice'] = false;
         }
         switch ($this->fields["type"]) {
             case self::INCIDENT_TYPE:
                 $opt['condition'] .= "`is_incident`='1'";
                 break;
             case self::DEMAND_TYPE:
                 $opt['condition'] .= "`is_request`='1'";
                 break;
             default:
                 break;
         }
         echo "<span id='show_category_by_type'>";
         ITILCategory::dropdown($opt);
         echo "</span>";
     } else {
         echo Dropdown::getDropdownName("glpi_itilcategories", $this->fields["itilcategories_id"]);
     }
     echo "</td>";
     echo "</tr>";
     if (!$ID) {
         echo "</table>";
         $this->showActorsPartForm($ID, $values);
         echo "<table class='tab_cadre_fixe' id='mainformtable3'>";
     }
     echo "<tr class='tab_bg_1'>";
     echo "<th width='{$colsize1}%'>" . $tt->getBeginHiddenFieldText('status');
     printf(__('%1$s%2$s'), __('Status'), $tt->getMandatoryMark('status'));
     echo $tt->getEndHiddenFieldText('status') . "</th>";
     echo "<td width='{$colsize2}%'>";
     echo $tt->getBeginHiddenFieldValue('status');
     if ($canstatus) {
         self::dropdownStatus(array('value' => $this->fields["status"], 'showtype' => 'allowed'));
         TicketValidation::alertValidation($this, 'status');
     } else {
         echo self::getStatus($this->fields["status"]);
         if (in_array($this->fields["status"], $this->getClosedStatusArray()) && $this->isAllowedStatus($this->fields['status'], Ticket::INCOMING)) {
             echo "&nbsp;<a class='vsubmit' href='" . $this->getLinkURL() . "&amp;forcetab=TicketFollowup\$1&amp;_openfollowup=1'>" . __('Reopen') . "</a>";
         }
     }
     echo $tt->getEndHiddenFieldValue('status', $this);
     echo "</td>";
     echo "<th width='{$colsize3}%'>" . $tt->getBeginHiddenFieldText('requesttypes_id');
     printf(__('%1$s%2$s'), __('Request source'), $tt->getMandatoryMark('requesttypes_id'));
     echo $tt->getEndHiddenFieldText('requesttypes_id') . "</th>";
     echo "<td width='{$colsize4}%'>";
     echo $tt->getBeginHiddenFieldValue('requesttypes_id');
     if ($canupdate) {
         RequestType::dropdown(array('value' => $this->fields["requesttypes_id"]));
     } else {
         echo Dropdown::getDropdownName('glpi_requesttypes', $this->fields["requesttypes_id"]);
     }
     echo $tt->getEndHiddenFieldValue('requesttypes_id', $this);
     echo "</td>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<th>" . $tt->getBeginHiddenFieldText('urgency');
     printf(__('%1$s%2$s'), __('Urgency'), $tt->getMandatoryMark('urgency'));
     echo $tt->getEndHiddenFieldText('urgency') . "</th>";
     echo "<td>";
     if ($canupdate && $canpriority || !$ID || $canupdate_descr) {
         // Only change during creation OR when allowed to change priority OR when user is the creator
         echo $tt->getBeginHiddenFieldValue('urgency');
         $idurgency = self::dropdownUrgency(array('value' => $this->fields["urgency"]));
         echo $tt->getEndHiddenFieldValue('urgency', $this);
     } else {
         $idurgency = "value_urgency" . mt_rand();
         echo "<input id='{$idurgency}' type='hidden' name='urgency' value='" . $this->fields["urgency"] . "'>";
         echo parent::getUrgencyName($this->fields["urgency"]);
     }
     echo "</td>";
     // Display validation state
     echo "<th>";
     if (!$ID) {
         echo $tt->getBeginHiddenFieldText('_add_validation');
         printf(__('%1$s%2$s'), __('Approval request'), $tt->getMandatoryMark('_add_validation'));
         echo $tt->getEndHiddenFieldText('_add_validation');
     } else {
         echo $tt->getBeginHiddenFieldText('global_validation');
         _e('Approval');
         echo $tt->getEndHiddenFieldText('global_validation');
     }
     echo "</th>";
     echo "<td>";
     if (!$ID) {
         echo $tt->getBeginHiddenFieldValue('_add_validation');
         $validation_right = '';
         if ($values['type'] == self::INCIDENT_TYPE && Session::haveRight('ticketvalidation', TicketValidation::CREATEINCIDENT)) {
             $validation_right = 'validate_incident';
         }
         if ($values['type'] == self::DEMAND_TYPE && Session::haveRight('ticketvalidation', TicketValidation::CREATEREQUEST)) {
             $validation_right = 'validate_request';
         }
         if (!empty($validation_right)) {
             echo "<input type='hidden' name='_add_validation' value='" . $values['_add_validation'] . "'>";
             $params = array('name' => "users_id_validate", 'entity' => $this->fields['entities_id'], 'right' => $validation_right, 'users_id_validate' => $values['users_id_validate']);
             TicketValidation::dropdownValidator($params);
         }
         echo $tt->getEndHiddenFieldValue('_add_validation', $this);
         if ($tt->isPredefinedField('global_validation')) {
             echo "<input type='hidden' name='global_validation' value='" . $tt->predefined['global_validation'] . "'>";
         }
     } else {
         echo $tt->getBeginHiddenFieldValue('global_validation');
         if ($canupdate) {
             TicketValidation::dropdownStatus('global_validation', array('global' => true, 'value' => $this->fields['global_validation']));
         } else {
             echo TicketValidation::getStatus($this->fields['global_validation']);
         }
         echo $tt->getEndHiddenFieldValue('global_validation', $this);
     }
     echo "</td></tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<th>" . $tt->getBeginHiddenFieldText('impact');
     printf(__('%1$s%2$s'), __('Impact'), $tt->getMandatoryMark('impact'));
     echo $tt->getEndHiddenFieldText('impact') . "</th>";
     echo "<td>";
     echo $tt->getBeginHiddenFieldValue('impact');
     if ($canupdate) {
         $idimpact = self::dropdownImpact(array('value' => $this->fields["impact"]));
     } else {
         $idimpact = "value_impact" . mt_rand();
         echo "<input id='{$idimpact}' type='hidden' name='impact' value='" . $this->fields["impact"] . "'>";
         echo parent::getImpactName($this->fields["impact"]);
     }
     echo $tt->getEndHiddenFieldValue('impact', $this);
     echo "</td>";
     echo "<th>" . $tt->getBeginHiddenFieldText('locations_id');
     printf(__('%1$s%2$s'), __('Location'), $tt->getMandatoryMark('locations_id'));
     echo $tt->getEndHiddenFieldText('locations_id') . "</th>";
     echo "<td>";
     echo $tt->getBeginHiddenFieldValue('locations_id');
     if ($canupdate) {
         Location::dropdown(array('value' => $this->fields['locations_id'], 'entity' => $this->fields['entities_id']));
     } else {
         echo Dropdown::getDropdownName('glpi_locations', $this->fields["locations_id"]);
     }
     echo $tt->getEndHiddenFieldValue('locations_id', $this);
     echo "</td>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<th>" . sprintf(__('%1$s%2$s'), __('Priority'), $tt->getMandatoryMark('priority')) . "</th>";
     echo "<td>";
     $idajax = 'change_priority_' . mt_rand();
     if ($canupdate && $canpriority && !$tt->isHiddenField('priority')) {
         $idpriority = parent::dropdownPriority(array('value' => $this->fields["priority"], 'withmajor' => true));
         echo "&nbsp;<span id='{$idajax}' style='display:none'></span>";
     } else {
         $idpriority = 0;
         echo $tt->getBeginHiddenFieldValue('priority');
         echo "<span id='{$idajax}'>" . parent::getPriorityName($this->fields["priority"]) . "</span>";
         echo $tt->getEndHiddenFieldValue('priority', $this);
     }
     if ($canupdate || $canupdate_descr) {
         $params = array('urgency' => '__VALUE0__', 'impact' => '__VALUE1__', 'priority' => 'dropdown_priority' . $idpriority);
         Ajax::updateItemOnSelectEvent(array('dropdown_urgency' . $idurgency, 'dropdown_impact' . $idimpact), $idajax, $CFG_GLPI["root_doc"] . "/ajax/priority.php", $params);
     }
     echo "</td>";
     echo "<th rowspan='2'>" . $tt->getBeginHiddenFieldText('itemtype');
     printf(__('%1$s%2$s'), _n('Associated element', 'Associated elements', Session::getPluralNumber()), $tt->getMandatoryMark('itemtype'));
     if ($ID && $canupdate) {
         echo "&nbsp;<a  href='" . $this->getFormURL() . "?id=" . $ID . "&amp;forcetab=Item_Ticket\$1'><img title='" . __s('Update') . "' alt='" . __s('Update') . "'\n                      class='pointer' src='" . $CFG_GLPI["root_doc"] . "/pics/showselect.png'></a>";
     }
     echo $tt->getEndHiddenFieldText('itemtype');
     echo "</th>";
     echo "<td rowspan='2'>";
     if (!$ID) {
         echo $tt->getBeginHiddenFieldValue('itemtype');
         // Select hardware on creation or if have update right
         if ($canupdate || $canupdate_descr) {
             $dev_user_id = $values['_users_id_requester'];
             $dev_itemtype = $values["itemtype"];
             $dev_items_id = $values["items_id"];
             if ($dev_user_id > 0) {
                 Item_Ticket::dropdownMyDevices($dev_user_id, $this->fields["entities_id"], $dev_itemtype, $dev_items_id);
             }
             Item_Ticket::dropdownAllDevices("itemtype", $dev_itemtype, $dev_items_id, 1, $dev_user_id, $this->fields["entities_id"]);
             echo "<span id='item_ticket_selection_information'></span>";
         }
         echo $tt->getEndHiddenFieldValue('itemtype', $this);
     } else {
         // display associated elements
         $item_tickets = getAllDatasFromTable(getTableForItemType('Item_Ticket'), "`tickets_id`='" . $ID . "'");
         $i = 0;
         foreach ($item_tickets as $itdata) {
             if ($i >= 5) {
                 echo "<i><a href='" . $this->getFormURL() . "?id=" . $ID . "&amp;forcetab=Item_Ticket\$1'>" . __('Display all items') . " (" . count($item_tickets) . ")</a></i>";
                 break;
             }
             $item = new $itdata['itemtype']();
             $item->getFromDB($itdata['items_id']);
             echo $item->getTypeName(1) . ": " . $item->getLink(array('comments' => true)) . "<br/>";
             $i++;
         }
     }
     echo "</td>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     // Need comment right to add a followup with the actiontime
     if (!$ID && Session::haveRight('followup', TicketFollowup::ADDALLTICKET)) {
         echo "<th>" . $tt->getBeginHiddenFieldText('actiontime');
         printf(__('%1$s%2$s'), __('Total duration'), $tt->getMandatoryMark('actiontime'));
         echo $tt->getEndHiddenFieldText('actiontime') . "</th>";
         echo "<td>";
         echo $tt->getBeginHiddenFieldValue('actiontime');
         Dropdown::showTimeStamp('actiontime', array('value' => $values['actiontime'], 'addfirstminutes' => true));
         echo $tt->getEndHiddenFieldValue('actiontime', $this);
         echo "</td>";
     }
     echo "</tr>";
     echo "</table>";
     if ($ID) {
         $this->showActorsPartForm($ID, $values);
     }
     $view_linked_tickets = $ID || $canupdate;
     echo "<table class='tab_cadre_fixe' id='mainformtable4'>";
     echo "<tr class='tab_bg_1'>";
     echo "<th width='{$colsize1}%'>" . $tt->getBeginHiddenFieldText('name');
     printf(__('%1$s%2$s'), __('Title'), $tt->getMandatoryMark('name'));
     echo $tt->getEndHiddenFieldText('name') . "</th>";
     echo "<td width='" . (100 - $colsize1) . "%' colspan='3'>";
     if (!$ID || $canupdate_descr) {
         echo $tt->getBeginHiddenFieldValue('name');
         echo "<input type='text' size='90' maxlength=250 name='name' class='form-control' " . " value=\"" . Html::cleanInputText($this->fields["name"]) . "\">";
         echo $tt->getEndHiddenFieldValue('name', $this);
     } else {
         if (empty($this->fields["name"])) {
             _e('Without title');
         } else {
             echo $this->fields["name"];
         }
     }
     echo "</td>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<th width='{$colsize1}%'>" . $tt->getBeginHiddenFieldText('content');
     printf(__('%1$s%2$s'), __('Description'), $tt->getMandatoryMark('content'));
     if (!$ID || $canupdate_descr) {
         $content = Toolbox::unclean_cross_side_scripting_deep(Html::entity_decode_deep($this->fields['content']));
         Html::showTooltip(nl2br(Html::Clean($content)));
     }
     echo $tt->getEndHiddenFieldText('content') . "</th>";
     echo "<td width='" . (100 - $colsize1) . "%' colspan='3'>";
     if (!$ID || $canupdate_descr) {
         // Admin =oui on autorise la modification de la description
         echo $tt->getBeginHiddenFieldValue('content');
         $rand = mt_rand();
         $rand_text = mt_rand();
         $cols = 90;
         $rows = 6;
         $content_id = "content{$rand}";
         if ($CFG_GLPI["use_rich_text"]) {
             $this->fields["content"] = $this->setRichTextContent($content_id, $this->fields["content"], $rand);
             $cols = 100;
             $rows = 10;
         } else {
             $this->fields["content"] = $this->setSimpleTextContent($this->fields["content"]);
         }
         echo "<div id='content{$rand_text}'>";
         echo "<textarea class='form-control'  id='{$content_id}' name='content' cols='{$cols}' rows='{$rows}'>" . $this->fields["content"] . "</textarea></div>";
         echo $tt->getEndHiddenFieldValue('content', $this);
     } else {
         $content = Toolbox::unclean_cross_side_scripting_deep(Html::entity_decode_deep($this->fields['content']));
         echo nl2br(Html::Clean($content));
     }
     echo "</td>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     if ($view_linked_tickets) {
         echo "<th width='{$colsize1}%'>" . _n('Linked ticket', 'Linked tickets', Session::getPluralNumber());
         $rand_linked_ticket = mt_rand();
         if ($canupdate) {
             echo "&nbsp;";
             echo "<img onClick=\"" . Html::jsShow("linkedticket{$rand_linked_ticket}") . "\"\n                   title=\"" . __s('Add') . "\" alt=\"" . __s('Add') . "\"\n                   class='pointer' src='" . $CFG_GLPI["root_doc"] . "/pics/add_dropdown.png'>";
         }
         echo '</th>';
         echo "<td width='" . (100 - $colsize1) . "%' colspan='3'>";
         if ($canupdate) {
             echo "<div style='display:none' id='linkedticket{$rand_linked_ticket}'>";
             echo "<table class='tab_format' width='100%'><tr><td width='30%'>";
             Ticket_Ticket::dropdownLinks('_link[link]', isset($values["_link"]) ? $values["_link"]['link'] : '');
             echo "<input type='hidden' name='_link[tickets_id_1]' value='{$ID}'>\n";
             echo "</td><td width='70%'>";
             $linkparam = array('name' => '_link[tickets_id_2]', 'displaywith' => array('id'));
             if (isset($values["_link"])) {
                 $linkparam['value'] = $values["_link"]['tickets_id_2'];
             }
             Ticket::dropdown($linkparam);
             echo "</td></tr></table>";
             echo "</div>";
             if (isset($values["_link"]) && !empty($values["_link"]['tickets_id_2'])) {
                 echo "<script language='javascript'>";
                 echo Html::jsShow("linkedticket{$rand_linked_ticket}");
                 echo "</script>";
             }
         }
         Ticket_Ticket::displayLinkedTicketsTo($ID);
         echo "</td>";
     }
     echo "</tr>";
     // View files added
     echo "<tr class='tab_bg_1'>";
     // Permit to add doc when creating a ticket
     echo "<th width='{$colsize1}%'>";
     echo $tt->getBeginHiddenFieldText('_documents_id');
     $doctitle = sprintf(__('File (%s)'), Document::getMaxUploadSize());
     printf(__('%1$s%2$s'), $doctitle, $tt->getMandatoryMark('_documents_id'));
     // Do not show if hidden.
     if (!$tt->isHiddenField('_documents_id')) {
         DocumentType::showAvailableTypesLink();
     }
     echo $tt->getEndHiddenFieldText('_documents_id');
     echo "</th>";
     echo "<td colspan='3' width='" . (100 - $colsize1) . "%' >";
     // Do not set values
     echo $tt->getEndHiddenFieldValue('_documents_id');
     if ($tt->isPredefinedField('_documents_id')) {
         if (isset($values['_documents_id']) && is_array($values['_documents_id']) && count($values['_documents_id'])) {
             echo "<span class='b'>" . __('Default documents:') . '</span>';
             echo "<br>";
             $doc = new Document();
             foreach ($values['_documents_id'] as $key => $val) {
                 if ($doc->getFromDB($val)) {
                     echo "<input type='hidden' name='_documents_id[{$key}]' value='{$val}'>";
                     echo "- " . $doc->getNameID() . "<br>";
                 }
             }
         }
     }
     echo "<div id='fileupload_info'></div>";
     echo "</td>";
     echo "</tr>";
     if ((!$ID || $canupdate || $canupdate_descr || Session::haveRightsOr(self::$rightname, array(self::ASSIGN, self::STEAL))) && !$options['template_preview']) {
         echo "<tr class='tab_bg_1'>";
         if ($ID) {
             if (Session::haveRightsOr(self::$rightname, array(UPDATE, DELETE, PURGE)) || $this->canDeleteItem() || $this->canUpdateItem()) {
                 echo "<td class='tab_bg_2 center' colspan='4'>";
                 if ($this->fields["is_deleted"] == 1) {
                     if (self::canPurge()) {
                         echo "<input type='submit' class='submit' name='restore' value='" . _sx('button', 'Restore') . "'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                     }
                 } else {
                     if (self::canUpdate()) {
                         echo "<input type='submit' class='submit' name='update' value='" . _sx('button', 'Save') . "'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                     }
                 }
                 if ($this->fields["is_deleted"] == 1) {
                     if (self::canPurge()) {
                         echo "<input type='submit' class='submit' name='purge' value='" . _sx('button', 'Delete permanently') . "' " . Html::addConfirmationOnAction(__('Confirm the final deletion?')) . ">";
                     }
                 } else {
                     if (self::canDelete()) {
                         echo "<input type='submit' class='submit' name='delete' value='" . _sx('button', 'Put in dustbin') . "'>";
                     }
                 }
                 echo "<input type='hidden' name='_read_date_mod' value='" . $this->getField('date_mod') . "'>";
                 echo "</td>";
             }
         } else {
             echo "<td class='tab_bg_2 center' colspan='4'>";
             echo "<input type='submit' name='add' value=\"" . _sx('button', 'Add') . "\" class='submit'>";
             if ($tt->isField('id') && $tt->fields['id'] > 0) {
                 echo "<input type='hidden' name='_tickettemplates_id' value='" . $tt->fields['id'] . "'>";
                 echo "<input type='hidden' name='_predefined_fields'\n                      value=\"" . Toolbox::prepareArrayForInput($predefined_fields) . "\">";
             }
         }
     }
     // File upload system
     $colspan = 2;
     if (!$CFG_GLPI['use_rich_text']) {
         $colspan = 4;
     }
     echo "<tr class='tab_bg_1'>";
     echo "<td colspan='{$colspan}'>";
     echo $tt->getBeginHiddenFieldValue('_documents_id');
     echo Html::file(array('multiple' => true, 'showfilecontainer' => 'fileupload_info', 'values' => array('filename' => $values['_filename'], 'tag' => $values['_tag_filename'])));
     echo "</td>";
     if ($CFG_GLPI['use_rich_text']) {
         echo "<td colspan='{$colspan}'>";
         if (!isset($rand)) {
             $rand = mt_rand();
         }
         echo Html::imagePaste(array('rand' => $rand));
         echo "</td>";
     }
     echo "</tr>";
     echo "</table>";
     echo "<input type='hidden' name='id' value='{$ID}'>";
     echo "</div>";
     if (!$options['template_preview']) {
         Html::closeForm();
     }
     return true;
 }
示例#19
0
 /**
  * Generic Function to display Items
  *
  * @param $itemtype              item type
  * @param $ID                    ID of the SEARCH_OPTION item
  * @param $data            array containing data results
  * @param $num                   item num in the request
  * @param $meta                  is a meta item ? (default 0)
  * @param $addobjectparams array added parameters for union search
  *
  * @return string to print
  **/
 static function giveItem($itemtype, $ID, array $data, $num, $meta = 0, array $addobjectparams = array())
 {
     global $CFG_GLPI, $DB;
     $searchopt =& self::getOptions($itemtype);
     if (isset($CFG_GLPI["union_search_type"][$itemtype]) && $CFG_GLPI["union_search_type"][$itemtype] == $searchopt[$ID]["table"]) {
         if (isset($searchopt[$ID]['addobjectparams']) && $searchopt[$ID]['addobjectparams']) {
             return self::giveItem($data["TYPE"], $ID, $data, $num, $meta, $searchopt[$ID]['addobjectparams']);
         }
         return self::giveItem($data["TYPE"], $ID, $data, $num, $meta);
     }
     if (count($addobjectparams)) {
         $searchopt[$ID] = array_merge($searchopt[$ID], $addobjectparams);
     }
     // Plugin can override core definition for its type
     if ($plug = isPluginItemType($itemtype)) {
         $function = 'plugin_' . $plug['plugin'] . '_giveItem';
         if (function_exists($function)) {
             $out = $function($itemtype, $ID, $data, $num);
             if (!empty($out)) {
                 return $out;
             }
         }
     }
     $NAME = "ITEM_";
     //       if ($meta) {
     //          $NAME = "META_";
     //       }
     if (isset($searchopt[$ID]["table"])) {
         $table = $searchopt[$ID]["table"];
         $field = $searchopt[$ID]["field"];
         $linkfield = $searchopt[$ID]["linkfield"];
         /// TODO try to clean all specific cases using SpecificToDisplay
         switch ($table . '.' . $field) {
             case "glpi_users.name":
                 // USER search case
                 if ($itemtype != 'User' && isset($searchopt[$ID]["forcegroupby"]) && $searchopt[$ID]["forcegroupby"]) {
                     $out = "";
                     $count_display = 0;
                     $added = array();
                     $showuserlink = 0;
                     if (Session::haveRight('user', READ)) {
                         $showuserlink = 1;
                     }
                     for ($k = 0; $k < $data[$num]['count']; $k++) {
                         if (isset($data[$num][$k]['name']) && $data[$num][$k]['name'] > 0 || isset($data[$num][$k][2]) && $data[$num][$k][2] != '') {
                             if ($count_display) {
                                 $out .= self::LBBR;
                             }
                             if ($itemtype == 'Ticket') {
                                 if (isset($data[$num][$k]['name']) && $data[$num][$k]['name'] > 0) {
                                     $userdata = getUserName($data[$num][$k]['name'], 2);
                                     $tooltip = "";
                                     if (Session::haveRight('user', READ)) {
                                         $tooltip = Html::showToolTip($userdata["comment"], array('link' => $userdata["link"], 'display' => false));
                                     }
                                     $out .= sprintf(__('%1$s %2$s'), $userdata['name'], $tooltip);
                                     $count_display++;
                                 }
                             } else {
                                 $out .= getUserName($data[$num][$k]['name'], $showuserlink);
                                 $count_display++;
                             }
                             // Manage alternative_email for tickets_users
                             if ($itemtype == 'Ticket' && isset($data[$num][$k][2])) {
                                 $split = explode(self::LONGSEP, $data[$num][$k][2]);
                                 for ($l = 0; $l < count($split); $l++) {
                                     $split2 = explode(" ", $split[$l]);
                                     if (count($split2) == 2 && $split2[0] == 0 && !empty($split2[1])) {
                                         if ($count_display) {
                                             $out .= self::LBBR;
                                         }
                                         $count_display++;
                                         $out .= "<a href='mailto:" . $split2[1] . "'>" . $split2[1] . "</a>";
                                     }
                                 }
                             }
                         }
                     }
                     return $out;
                 }
                 if ($itemtype != 'User') {
                     $toadd = '';
                     if ($itemtype == 'Ticket' && $data[$num][0]['id'] > 0) {
                         $userdata = getUserName($data[$num][0]['id'], 2);
                         $toadd = Html::showToolTip($userdata["comment"], array('link' => $userdata["link"], 'display' => false));
                     }
                     $usernameformat = formatUserName($data[$num][0]['id'], $data[$num][0]['name'], $data[$num][0]['realname'], $data[$num][0]['firstname'], 1);
                     return sprintf(__('%1$s %2$s'), $usernameformat, $toadd);
                 }
                 break;
             case "glpi_profiles.name":
                 if ($itemtype == 'User' && $ID == 20) {
                     $out = "";
                     $count_display = 0;
                     $added = array();
                     for ($k = 0; $k < $data[$num]['count']; $k++) {
                         if (strlen(trim($data[$num][$k]['name'])) > 0) {
                             $text = sprintf(__('%1$s - %2$s'), $data[$num][$k]['name'], Dropdown::getDropdownName('glpi_entities', $data[$num][$k]['entities_id']));
                             $comp = '';
                             if ($data[$num][$k]['is_recursive']) {
                                 $comp = __('R');
                                 if ($data[$num][$k]['is_dynamic']) {
                                     $comp = sprintf(__('%1$s%2$s'), $comp, ", ");
                                 }
                             }
                             if ($data[$num][$k]['is_dynamic']) {
                                 $comp = sprintf(__('%1$s%2$s'), $comp, __('D'));
                             }
                             if (!empty($comp)) {
                                 $text = sprintf(__('%1$s %2$s'), $text, "(" . $comp . ")");
                             }
                             if (!in_array($text, $added)) {
                                 if ($count_display) {
                                     $out .= self::LBBR;
                                 }
                                 $count_display++;
                                 $out .= $text;
                                 $added[] = $text;
                             }
                         }
                     }
                     return $out;
                 }
                 break;
             case "glpi_entities.completename":
                 if ($itemtype == 'User') {
                     $out = "";
                     $added = array();
                     $count_display = 0;
                     for ($k = 0; $k < $data[$num]['count']; $k++) {
                         if (strlen(trim($data[$num][$k]['name'])) > 0) {
                             $text = sprintf(__('%1$s - %2$s'), $data[$num][$k]['name'], Dropdown::getDropdownName('glpi_profiles', $data[$num][$k]['profiles_id']));
                             $comp = '';
                             if ($data[$num][$k]['is_recursive']) {
                                 $comp = __('R');
                                 if ($data[$num][$k]['is_dynamic']) {
                                     $comp = sprintf(__('%1$s%2$s'), $comp, ", ");
                                 }
                             }
                             if ($data[$num][$k]['is_dynamic']) {
                                 $comp = sprintf(__('%1$s%2$s'), $comp, __('D'));
                             }
                             if (!empty($comp)) {
                                 $text = sprintf(__('%1$s %2$s'), $text, "(" . $comp . ")");
                             }
                             if (!in_array($text, $added)) {
                                 if ($count_display) {
                                     $out .= self::LBBR;
                                 }
                                 $count_display++;
                                 $out .= $text;
                                 $added[] = $text;
                             }
                         }
                     }
                     return $out;
                 }
                 break;
             case "glpi_documenttypes.icon":
                 if (!empty($data[$num][0]['name'])) {
                     return "<img class='middle' alt='' src='" . $CFG_GLPI["typedoc_icon_dir"] . "/" . $data[$num][0]['name'] . "'>";
                 }
                 return "&nbsp;";
             case "glpi_documents.filename":
                 $doc = new Document();
                 if ($doc->getFromDB($data['id'])) {
                     return $doc->getDownloadLink();
                 }
                 return NOT_AVAILABLE;
             case "glpi_tickets_tickets.tickets_id_1":
                 $out = "";
                 $displayed = array();
                 for ($k = 0; $k < $data[$num]['count']; $k++) {
                     $linkid = $data[$num][$k]['tickets_id_2'] == $data['id'] ? $data[$num][$k]['name'] : $data[$num][$k]['tickets_id_2'];
                     if ($linkid > 0 && !isset($displayed[$linkid])) {
                         $text = "<a ";
                         $text .= "href=\"" . $CFG_GLPI["root_doc"] . "/front/ticket.form.php?id={$linkid}\">";
                         $text .= Dropdown::getDropdownName('glpi_tickets', $linkid) . "</a>";
                         if (count($displayed)) {
                             $out .= self::LBBR;
                         }
                         $displayed[$linkid] = $linkid;
                         $out .= $text;
                     }
                 }
                 return $out;
             case "glpi_problems.id":
                 if ($searchopt[$ID]["datatype"] == 'count') {
                     if ($data[$num][0]['name'] > 0 && Session::haveRight("problem", Problem::READALL)) {
                         if ($itemtype == 'ITILCategory') {
                             $options['criteria'][0]['field'] = 7;
                             $options['criteria'][0]['searchtype'] = 'equals';
                             $options['criteria'][0]['value'] = $data['id'];
                             $options['criteria'][0]['link'] = 'AND';
                         } else {
                             $options['criteria'][0]['field'] = 12;
                             $options['criteria'][0]['searchtype'] = 'equals';
                             $options['criteria'][0]['value'] = 'all';
                             $options['criteria'][0]['link'] = 'AND';
                             $options['metacriteria'][0]['itemtype'] = $itemtype;
                             $options['metacriteria'][0]['field'] = self::getOptionNumber($itemtype, 'name');
                             $options['metacriteria'][0]['searchtype'] = 'equals';
                             $options['metacriteria'][0]['value'] = $data['id'];
                             $options['metacriteria'][0]['link'] = 'AND';
                         }
                         $options['reset'] = 'reset';
                         $out = "<a id='problem{$itemtype}" . $data['id'] . "' ";
                         $out .= "href=\"" . $CFG_GLPI["root_doc"] . "/front/problem.php?" . Toolbox::append_params($options, '&amp;') . "\">";
                         $out .= $data[$num][0]['name'] . "</a>";
                         return $out;
                     }
                 }
                 break;
             case "glpi_tickets.id":
                 if ($searchopt[$ID]["datatype"] == 'count') {
                     if ($data[$num][0]['name'] > 0 && Session::haveRight("ticket", Ticket::READALL)) {
                         if ($itemtype == 'User') {
                             // Requester
                             if ($ID == 60) {
                                 $options['criteria'][0]['field'] = 4;
                                 $options['criteria'][0]['searchtype'] = 'equals';
                                 $options['criteria'][0]['value'] = $data['id'];
                                 $options['criteria'][0]['link'] = 'AND';
                             }
                             // Writer
                             if ($ID == 61) {
                                 $options['criteria'][0]['field'] = 22;
                                 $options['criteria'][0]['searchtype'] = 'equals';
                                 $options['criteria'][0]['value'] = $data['id'];
                                 $options['criteria'][0]['link'] = 'AND';
                             }
                             // Assign
                             if ($ID == 64) {
                                 $options['criteria'][0]['field'] = 5;
                                 $options['criteria'][0]['searchtype'] = 'equals';
                                 $options['criteria'][0]['value'] = $data['id'];
                                 $options['criteria'][0]['link'] = 'AND';
                             }
                         } else {
                             if ($itemtype == 'ITILCategory') {
                                 $options['criteria'][0]['field'] = 7;
                                 $options['criteria'][0]['searchtype'] = 'equals';
                                 $options['criteria'][0]['value'] = $data['id'];
                                 $options['criteria'][0]['link'] = 'AND';
                             } else {
                                 $options['criteria'][0]['field'] = 12;
                                 $options['criteria'][0]['searchtype'] = 'equals';
                                 $options['criteria'][0]['value'] = 'all';
                                 $options['criteria'][0]['link'] = 'AND';
                                 $options['metacriteria'][0]['itemtype'] = $itemtype;
                                 $options['metacriteria'][0]['field'] = self::getOptionNumber($itemtype, 'name');
                                 $options['metacriteria'][0]['searchtype'] = 'equals';
                                 $options['metacriteria'][0]['value'] = $data['id'];
                                 $options['metacriteria'][0]['link'] = 'AND';
                             }
                         }
                         $options['reset'] = 'reset';
                         $out = "<a id='ticket{$itemtype}" . $data['id'] . "' ";
                         $out .= "href=\"" . $CFG_GLPI["root_doc"] . "/front/ticket.php?" . Toolbox::append_params($options, '&amp;') . "\">";
                         $out .= $data[$num][0]['name'] . "</a>";
                         return $out;
                     }
                 }
                 break;
             case "glpi_tickets.due_date":
             case "glpi_problems.due_date":
             case "glpi_changes.due_date":
                 // Due date + progress
                 if ($ID == 151) {
                     $out = Html::convDate($data[$num][0]['name']);
                     // No due date in waiting status
                     if ($data[$num][0]['status'] == CommonITILObject::WAITING) {
                         return '';
                     }
                     if (empty($data[$num][0]['name'])) {
                         return '';
                     }
                     if ($data[$num][0]['status'] == Ticket::SOLVED || $data[$num][0]['status'] == Ticket::CLOSED) {
                         return $out;
                     }
                     $itemtype = getItemTypeForTable($table);
                     $item = new $itemtype();
                     $item->getFromDB($data['id']);
                     $percentage = 0;
                     $totaltime = 0;
                     $currenttime = 0;
                     if ($item->isField('slas_id') && $item->fields['slas_id'] != 0) {
                         // Have SLA
                         $sla = new SLA();
                         $sla->getFromDB($item->fields['slas_id']);
                         $currenttime = $sla->getActiveTimeBetween($item->fields['date'], date('Y-m-d H:i:s'));
                         $totaltime = $sla->getActiveTimeBetween($item->fields['date'], $data[$num][0]['name']);
                     } else {
                         $calendars_id = Entity::getUsedConfig('calendars_id', $item->fields['entities_id']);
                         if ($calendars_id != 0) {
                             // Ticket entity have calendar
                             $calendar = new Calendar();
                             $calendar->getFromDB($calendars_id);
                             $currenttime = $calendar->getActiveTimeBetween($item->fields['date'], date('Y-m-d H:i:s'));
                             $totaltime = $calendar->getActiveTimeBetween($item->fields['date'], $data[$num][0]['name']);
                         } else {
                             // No calendar
                             $currenttime = strtotime(date('Y-m-d H:i:s')) - strtotime($item->fields['date']);
                             $totaltime = strtotime($data[$num][0]['name']) - strtotime($item->fields['date']);
                         }
                     }
                     if ($totaltime != 0) {
                         $percentage = round(100 * $currenttime / $totaltime);
                     } else {
                         // Total time is null : no active time
                         $percentage = 100;
                     }
                     if ($percentage > 100) {
                         $percentage = 100;
                     }
                     $percentage_text = $percentage;
                     if ($_SESSION['glpiduedatewarning_unit'] == '%') {
                         $less_warn_limit = $_SESSION['glpiduedatewarning_less'];
                         $less_warn = 100 - $percentage;
                     } else {
                         if ($_SESSION['glpiduedatewarning_unit'] == 'hour') {
                             $less_warn_limit = $_SESSION['glpiduedatewarning_less'] * HOUR_TIMESTAMP;
                             $less_warn = $totaltime - $currenttime;
                         } else {
                             if ($_SESSION['glpiduedatewarning_unit'] == 'day') {
                                 $less_warn_limit = $_SESSION['glpiduedatewarning_less'] * DAY_TIMESTAMP;
                                 $less_warn = $totaltime - $currenttime;
                             }
                         }
                     }
                     if ($_SESSION['glpiduedatecritical_unit'] == '%') {
                         $less_crit_limit = $_SESSION['glpiduedatecritical_less'];
                         $less_crit = 100 - $percentage;
                     } else {
                         if ($_SESSION['glpiduedatecritical_unit'] == 'hour') {
                             $less_crit_limit = $_SESSION['glpiduedatecritical_less'] * HOUR_TIMESTAMP;
                             $less_crit = $totaltime - $currenttime;
                         } else {
                             if ($_SESSION['glpiduedatecritical_unit'] == 'day') {
                                 $less_crit_limit = $_SESSION['glpiduedatecritical_less'] * DAY_TIMESTAMP;
                                 $less_crit = $totaltime - $currenttime;
                             }
                         }
                     }
                     $color = $_SESSION['glpiduedateok_color'];
                     if ($less_crit < $less_crit_limit) {
                         $color = $_SESSION['glpiduedatecritical_color'];
                     } else {
                         if ($less_warn < $less_warn_limit) {
                             $color = $_SESSION['glpiduedatewarning_color'];
                         }
                     }
                     //Calculate bar progress
                     $out .= "<div class='center' style='background-color: #ffffff; width: 100%;\n                            border: 1px solid #9BA563; position: relative;' >";
                     $out .= "<div style='position:absolute;'>&nbsp;" . $percentage_text . "%</div>";
                     $out .= "<div class='center' style='background-color: " . $color . ";\n                            width: " . $percentage . "%; height: 12px' ></div>";
                     $out .= "</div>";
                     return $out;
                 }
                 break;
             case "glpi_softwarelicenses.number":
                 if ($data[$num][0]['min'] == -1) {
                     return __('Unlimited');
                 }
                 if (empty($data[$num][0]['name'])) {
                     return 0;
                 }
                 return $data[$num][0]['name'];
             case "glpi_auth_tables.name":
                 return Auth::getMethodName($data[$num][0]['name'], $data[$num][0]['auths_id'], 1, $data[$num][0]['ldapname'] . $data[$num][0]['mailname']);
             case "glpi_reservationitems.comment":
                 if (empty($data[$num][0]['name'])) {
                     return "<a title=\"" . __s('Modify the comment') . "\"\n                           href='" . $CFG_GLPI["root_doc"] . "/front/reservationitem.form.php?id=" . $data["refID"] . "' >" . __('None') . "</a>";
                 }
                 return "<a title=\"" . __s('Modify the comment') . "\"\n                        href='" . $CFG_GLPI["root_doc"] . "/front/reservationitem.form.php?id=" . $data['refID'] . "' >" . Html::resume_text($data[$num][0]['name']) . "</a>";
             case 'glpi_crontasks.description':
                 $tmp = new CronTask();
                 return $tmp->getDescription($data[$num][0]['name']);
             case 'glpi_changes.status':
                 $status = Change::getStatus($data[$num][0]['name']);
                 return "<img src=\"" . Change::getStatusIconURL($data[$num][0]['name']) . "\"\n                        alt=\"{$status}\" title=\"{$status}\">&nbsp;{$status}";
             case 'glpi_problems.status':
                 $status = Problem::getStatus($data[$num][0]['name']);
                 return "<img src=\"" . Problem::getStatusIconURL($data[$num][0]['name']) . "\"\n                        alt=\"{$status}\" title=\"{$status}\">&nbsp;{$status}";
             case 'glpi_tickets.status':
                 $status = Ticket::getStatus($data[$num][0]['name']);
                 return "<img src=\"" . Ticket::getStatusIconURL($data[$num][0]['name']) . "\"\n                        alt=\"{$status}\" title=\"{$status}\">&nbsp;{$status}";
             case 'glpi_projectstates.name':
                 $out = '';
                 $query = "SELECT `color`\n                         FROM `glpi_projectstates`\n                         WHERE `name` = '" . $data[$num][0]['name'] . "'";
                 foreach ($DB->request($query) as $color) {
                     $color = $color['color'];
                     $out = "<div style=\"background-color:" . $color . ";\">";
                     $name = $data[$num][0]['name'];
                     if (isset($data[$num][0]['trans'])) {
                         $name = $data[$num][0]['trans'];
                     }
                     if ($itemtype == 'ProjectState') {
                         $out .= "<a href='" . $CFG_GLPI["root_doc"] . "/front/projectstate.form.php?id=" . $data[$num][0]["id"] . "'>" . $name . "</a></div>";
                     } else {
                         $out .= $name . "</div>";
                     }
                 }
                 return $out;
             case 'glpi_items_tickets.items_id':
             case 'glpi_items_problems.items_id':
                 if (!empty($data[$num])) {
                     $items = array();
                     foreach ($data[$num] as $key => $val) {
                         if (is_numeric($key)) {
                             if (!empty($val['itemtype']) && ($item = getItemForItemtype($val['itemtype']))) {
                                 if ($item->getFromDB($val['name'])) {
                                     $items[] = $item->getLink(array('comments' => true));
                                 }
                             }
                         }
                     }
                     if (!empty($items)) {
                         return implode("<br>", $items);
                     }
                 }
                 return '&nbsp;';
             case 'glpi_items_tickets.itemtype':
             case 'glpi_items_problems.itemtype':
                 if (!empty($data[$num])) {
                     $itemtypes = array();
                     foreach ($data[$num] as $key => $val) {
                         if (is_numeric($key)) {
                             if (!empty($val['name'])) {
                                 if (substr($val['name'], 0, 6) == 'Plugin') {
                                     $plug = new $val['name']();
                                     $name = $plug->getTypeName();
                                     $itemtypes[] = __($name);
                                 } else {
                                     $itemtypes[] = __($val['name']);
                                 }
                             }
                         }
                     }
                     if (!empty($itemtypes)) {
                         return implode("<br>", $itemtypes);
                     }
                 }
                 return '&nbsp;';
             case 'glpi_tickets.name':
             case 'glpi_problems.name':
             case 'glpi_changes.name':
                 if (isset($data[$num][0]['content']) && isset($data[$num][0]['id']) && isset($data[$num][0]['status'])) {
                     $link = Toolbox::getItemTypeFormURL($itemtype);
                     $out = "<a id='{$itemtype}" . $data[$num][0]['id'] . "' href=\"" . $link;
                     $out .= strstr($link, '?') ? '&amp;' : '?';
                     $out .= 'id=' . $data[$num][0]['id'];
                     // Force solution tab if solved
                     if ($item = getItemForItemtype($itemtype)) {
                         if (in_array($data[$num][0]['status'], $item->getSolvedStatusArray())) {
                             $out .= "&amp;forcetab={$itemtype}\$2";
                         }
                     }
                     $out .= "\">";
                     $name = $data[$num][0]['name'];
                     if ($_SESSION["glpiis_ids_visible"] || empty($data[$num][0]['name'])) {
                         $name = sprintf(__('%1$s (%2$s)'), $name, $data[$num][0]['id']);
                     }
                     $out .= $name . "</a>";
                     $hdecode = Html::entity_decode_deep($data[$num][0]['content']);
                     $content = Toolbox::unclean_cross_side_scripting_deep($hdecode);
                     $out = sprintf(__('%1$s %2$s'), $out, Html::showToolTip(nl2br(Html::Clean($content)), array('applyto' => $itemtype . $data[$num][0]['id'], 'display' => false)));
                     return $out;
                 }
             case 'glpi_ticketvalidations.status':
                 $out = '';
                 for ($k = 0; $k < $data[$num]['count']; $k++) {
                     if ($data[$num][$k]['name']) {
                         $status = TicketValidation::getStatus($data[$num][$k]['name']);
                         $bgcolor = TicketValidation::getStatusColor($data[$num][$k]['name']);
                         $out .= (empty($out) ? '' : self::LBBR) . "<div style=\"background-color:" . $bgcolor . ";\">" . $status . '</div>';
                     }
                 }
                 return $out;
             case 'glpi_ticketsatisfactions.satisfaction':
                 if (self::$output_type == self::HTML_OUTPUT) {
                     return TicketSatisfaction::displaySatisfaction($data[$num][0]['name']);
                 }
                 break;
             case 'glpi_projects._virtual_planned_duration':
                 return Html::timestampToString(ProjectTask::getTotalPlannedDurationForProject($data["id"]), false);
             case 'glpi_projects._virtual_effective_duration':
                 return Html::timestampToString(ProjectTask::getTotalEffectiveDurationForProject($data["id"]), false);
             case 'glpi_cartridgeitems._virtual':
                 return Cartridge::getCount($data["id"], $data[$num][0]['alarm_threshold'], self::$output_type != self::HTML_OUTPUT);
             case 'glpi_printers._virtual':
                 return Cartridge::getCountForPrinter($data["id"], self::$output_type != self::HTML_OUTPUT);
             case 'glpi_consumableitems._virtual':
                 return Consumable::getCount($data["id"], $data[$num][0]['alarm_threshold'], self::$output_type != self::HTML_OUTPUT);
             case 'glpi_links._virtual':
                 $out = '';
                 $link = new Link();
                 if (($item = getItemForItemtype($itemtype)) && $item->getFromDB($data['id']) && $link->getfromDB($data[$num][0]['id']) && $item->fields['entities_id'] == $link->fields['entities_id']) {
                     if (count($data[$num])) {
                         $count_display = 0;
                         foreach ($data[$num] as $val) {
                             if (is_array($val)) {
                                 $links = Link::getAllLinksFor($item, $val);
                                 foreach ($links as $link) {
                                     if ($count_display) {
                                         $out .= self::LBBR;
                                     }
                                     $out .= $link;
                                     $count_display++;
                                 }
                             }
                         }
                     }
                 }
                 return $out;
             case 'glpi_reservationitems._virtual':
                 if ($data[$num][0]['is_active']) {
                     return "<a href='reservation.php?reservationitems_id=" . $data["refID"] . "' title=\"" . __s('See planning') . "\">" . "<img src=\"" . $CFG_GLPI["root_doc"] . "/pics/reservation-3.png\" alt='' title=''></a>";
                 } else {
                     return "&nbsp;";
                 }
         }
     }
     //// Default case
     // Link with plugin tables : need to know left join structure
     if (isset($table)) {
         if (preg_match("/^glpi_plugin_([a-z0-9]+)/", $table . '.' . $field, $matches)) {
             if (count($matches) == 2) {
                 $plug = $matches[1];
                 $function = 'plugin_' . $plug . '_giveItem';
                 if (function_exists($function)) {
                     $out = $function($itemtype, $ID, $data, $num);
                     if (!empty($out)) {
                         return $out;
                     }
                 }
             }
         }
     }
     $unit = '';
     if (isset($searchopt[$ID]['unit'])) {
         $unit = $searchopt[$ID]['unit'];
     }
     // Preformat items
     if (isset($searchopt[$ID]["datatype"])) {
         switch ($searchopt[$ID]["datatype"]) {
             case "itemlink":
                 $linkitemtype = getItemTypeForTable($searchopt[$ID]["table"]);
                 $out = "";
                 $count_display = 0;
                 $separate = self::LBBR;
                 if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) {
                     $separate = self::LBHR;
                 }
                 for ($k = 0; $k < $data[$num]['count']; $k++) {
                     if (isset($data[$num][$k]['id'])) {
                         if ($count_display) {
                             $out .= $separate;
                         }
                         $count_display++;
                         $page = $linkitemtype::getFormUrl();
                         $page .= strpos($page, '?') ? '&id' : '?id';
                         $name = Dropdown::getValueWithUnit($data[$num][$k]['name'], $unit);
                         if ($_SESSION["glpiis_ids_visible"] || empty($data[$num][$k]['name'])) {
                             $name = sprintf(__('%1$s (%2$s)'), $name, $data[$num][$k]['id']);
                         }
                         $out .= "<a id='" . $linkitemtype . "_" . $data['id'] . "_" . $data[$num][$k]['id'] . "' href='{$page}=" . $data[$num][$k]['id'] . "'>" . $name . "</a>";
                     }
                 }
                 return $out;
             case "text":
                 $separate = self::LBBR;
                 if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) {
                     $separate = self::LBHR;
                 }
                 $out = '';
                 $count_display = 0;
                 for ($k = 0; $k < $data[$num]['count']; $k++) {
                     if (strlen(trim($data[$num][$k]['name'])) > 0) {
                         if ($count_display) {
                             $out .= $separate;
                         }
                         $count_display++;
                         $text = "";
                         if (isset($searchopt[$ID]['htmltext']) && $searchopt[$ID]['htmltext']) {
                             $text = Html::clean(Toolbox::unclean_cross_side_scripting_deep(nl2br($data[$num][$k]['name'])));
                         } else {
                             $text = nl2br($data[$num][$k]['name']);
                         }
                         if (self::$output_type == self::HTML_OUTPUT && Toolbox::strlen($text) > $CFG_GLPI['cut']) {
                             $rand = mt_rand();
                             $out .= sprintf(__('%1$s %2$s'), "<span id='text{$rand}'>" . Html::resume_text($text, $CFG_GLPI['cut']) . '</span>', Html::showToolTip($text, array('applyto' => "text{$rand}", 'display' => false)));
                         } else {
                             $out .= $text;
                         }
                     }
                 }
                 return $out;
             case "date":
             case "date_delay":
                 $out = '';
                 for ($k = 0; $k < $data[$num]['count']; $k++) {
                     if (is_null($data[$num][$k]['name']) && isset($searchopt[$ID]['emptylabel']) && $searchopt[$ID]['emptylabel']) {
                         $out .= (empty($out) ? '' : self::LBBR) . $searchopt[$ID]['emptylabel'];
                     } else {
                         $out .= (empty($out) ? '' : self::LBBR) . Html::convDate($data[$num][$k]['name']);
                     }
                 }
                 return $out;
             case "datetime":
                 $out = '';
                 for ($k = 0; $k < $data[$num]['count']; $k++) {
                     if (is_null($data[$num][$k]['name']) && isset($searchopt[$ID]['emptylabel']) && $searchopt[$ID]['emptylabel']) {
                         $out .= (empty($out) ? '' : self::LBBR) . $searchopt[$ID]['emptylabel'];
                     } else {
                         $out .= (empty($out) ? '' : self::LBBR) . Html::convDateTime($data[$num][$k]['name']);
                     }
                 }
                 return $out;
             case "timestamp":
                 $withseconds = false;
                 if (isset($searchopt[$ID]['withseconds'])) {
                     $withseconds = $searchopt[$ID]['withseconds'];
                 }
                 $withdays = true;
                 if (isset($searchopt[$ID]['withdays'])) {
                     $withdays = $searchopt[$ID]['withdays'];
                 }
                 $out = '';
                 for ($k = 0; $k < $data[$num]['count']; $k++) {
                     $out .= (empty($out) ? '' : '<br>') . Html::timestampToString($data[$num][$k]['name'], $withseconds, $withdays);
                 }
                 return $out;
             case "email":
                 $out = '';
                 $count_display = 0;
                 for ($k = 0; $k < $data[$num]['count']; $k++) {
                     if ($count_display) {
                         $out .= self::LBBR;
                     }
                     $count_display++;
                     if (!empty($data[$num][$k]['name'])) {
                         $out .= empty($out) ? '' : self::LBBR;
                         $out .= "<a href='mailto:" . $data[$num][$k]['name'] . "'>" . $data[$num][$k]['name'];
                         $out .= "</a>";
                     }
                 }
                 return empty($out) ? "&nbsp;" : $out;
             case "weblink":
                 $orig_link = trim($data[$num][0]['name']);
                 if (!empty($orig_link)) {
                     // strip begin of link
                     $link = preg_replace('/https?:\\/\\/(www[^\\.]*\\.)?/', '', $orig_link);
                     $link = preg_replace('/\\/$/', '', $link);
                     if (Toolbox::strlen($link) > $CFG_GLPI["url_maxlength"]) {
                         $link = Toolbox::substr($link, 0, $CFG_GLPI["url_maxlength"]) . "...";
                     }
                     return "<a href=\"" . formatOutputWebLink($orig_link) . "\" target='_blank'>{$link}</a>";
                 }
                 return "&nbsp;";
             case "count":
             case "number":
                 $out = "";
                 $count_display = 0;
                 for ($k = 0; $k < $data[$num]['count']; $k++) {
                     if (strlen(trim($data[$num][$k]['name'])) > 0) {
                         if ($count_display) {
                             $out .= self::LBBR;
                         }
                         $count_display++;
                         if (isset($searchopt[$ID]['toadd']) && isset($searchopt[$ID]['toadd'][$data[$num][$k]['name']])) {
                             $out .= $searchopt[$ID]['toadd'][$data[$num][$k]['name']];
                         } else {
                             $number = str_replace(' ', '&nbsp;', Html::formatNumber($data[$num][$k]['name'], false, 0));
                             $out .= Dropdown::getValueWithUnit($number, $unit);
                         }
                     }
                 }
                 return $out;
             case "decimal":
                 $out = "";
                 $count_display = 0;
                 for ($k = 0; $k < $data[$num]['count']; $k++) {
                     if (strlen(trim($data[$num][$k]['name'])) > 0) {
                         if ($count_display) {
                             $out .= self::LBBR;
                         }
                         $count_display++;
                         if (isset($searchopt[$ID]['toadd']) && isset($searchopt[$ID]['toadd'][$data[$num][$k]['name']])) {
                             $out .= $searchopt[$ID]['toadd'][$data[$num][$k]['name']];
                         } else {
                             $number = str_replace(' ', '&nbsp;', Html::formatNumber($data[$num][$k]['name']));
                             $out .= Dropdown::getValueWithUnit($number, $unit);
                         }
                     }
                 }
                 return $out;
             case "bool":
                 $out = "";
                 $count_display = 0;
                 for ($k = 0; $k < $data[$num]['count']; $k++) {
                     if (strlen(trim($data[$num][$k]['name'])) > 0) {
                         if ($count_display) {
                             $out .= self::LBBR;
                         }
                         $count_display++;
                         $out .= Dropdown::getValueWithUnit(Dropdown::getYesNo($data[$num][$k]['name']), $unit);
                     }
                 }
                 return $out;
             case "itemtypename":
                 if ($obj = getItemForItemtype($data[$num][0]['name'])) {
                     return $obj->getTypeName();
                 }
                 return "";
             case "language":
                 if (isset($CFG_GLPI['languages'][$data[$num][0]['name']])) {
                     return $CFG_GLPI['languages'][$data[$num][0]['name']][0];
                 }
                 return __('Default value');
         }
     }
     // Manage items with need group by / group_concat
     $out = "";
     $count_display = 0;
     $separate = self::LBBR;
     if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) {
         $separate = self::LBHR;
     }
     for ($k = 0; $k < $data[$num]['count']; $k++) {
         if (strlen(trim($data[$num][$k]['name'])) > 0) {
             if ($count_display) {
                 $out .= $separate;
             }
             $count_display++;
             // Get specific display if available
             $itemtype = getItemTypeForTable($table);
             if ($item = getItemForItemtype($itemtype)) {
                 $tmpdata = $data[$num][$k];
                 // Copy name to real field
                 $tmpdata[$field] = $data[$num][$k]['name'];
                 $specific = $item->getSpecificValueToDisplay($field, $tmpdata, array('html' => true, 'searchopt' => $searchopt[$ID]));
             }
             if (!empty($specific)) {
                 $out .= $specific;
             } else {
                 if (isset($searchopt[$ID]['toadd']) && isset($searchopt[$ID]['toadd'][$data[$num][$k]['name']])) {
                     $out .= $searchopt[$ID]['toadd'][$data[$num][$k]['name']];
                 } else {
                     // Empty is 0 or empty
                     if (empty($split[0]) && isset($searchopt[$ID]['emptylabel'])) {
                         $out .= $searchopt[$ID]['emptylabel'];
                     } else {
                         // Trans field exists
                         if (isset($data[$num][$k]['trans']) && !empty($data[$num][$k]['trans'])) {
                             $out .= Dropdown::getValueWithUnit($data[$num][$k]['trans'], $unit);
                         } else {
                             $out .= Dropdown::getValueWithUnit($data[$num][$k]['name'], $unit);
                         }
                     }
                 }
             }
         }
     }
     return $out;
     // Trans in group concat
     if (count($split) == 3 && !empty($split[1])) {
         return Dropdown::getValueWithUnit($split[1], $unit);
     }
     return Dropdown::getValueWithUnit($split[0], $unit);
 }
 /**
  * Print the validation list into item
  *
  * @param $item class
  **/
 function showSummary($item)
 {
     global $DB, $CFG_GLPI;
     if (!Session::haveRightsOr(static::$rightname, array_merge(static::getCreateRights(), static::getValidateRights(), static::getPurgeRights()))) {
         return false;
     }
     $tID = $item->fields['id'];
     $tmp = array(static::$items_id => $tID);
     $canadd = $this->can(-1, CREATE, $tmp);
     $rand = mt_rand();
     if ($canadd) {
         echo "<form method='post' name=form action='" . Toolbox::getItemTypeFormURL(static::$itemtype) . "'>";
     }
     echo "<table class='tab_cadre_fixe'>";
     echo "<tr>";
     echo "<th colspan='3'>" . self::getTypeName(Session::getPluralNumber()) . "</th>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . __('Global approval status') . "</td>";
     echo "<td colspan='2'>";
     if (Session::haveRightsOr(static::$rightname, TicketValidation::getCreateRights())) {
         self::dropdownStatus("global_validation", array('value' => $item->fields["global_validation"]));
     } else {
         echo TicketValidation::getStatus($item->fields["global_validation"]);
     }
     echo "</td></tr>";
     echo "<tr>";
     echo "<th colspan='2'>" . _x('item', 'State') . "</th>";
     echo "<th colspan='2'>";
     echo self::getValidationStats($tID);
     echo "</th>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . __('Minimum validation required') . "</td>";
     if ($canadd) {
         echo "<td>";
         echo $item->getValueToSelect('validation_percent', 'validation_percent', $item->fields["validation_percent"]);
         echo "</td>";
         echo "<td><input type='submit' name='update' class='submit' value='" . _sx('button', 'Save') . "'>";
         if (!empty($tID)) {
             echo "<input type='hidden' name='id' value='{$tID}'>";
         }
         echo "</td>";
     } else {
         echo "<td colspan='2'>";
         echo Dropdown::getValueWithUnit($item->fields["validation_percent"], "%");
         echo "</td>";
     }
     echo "</tr>";
     echo "</table>";
     if ($canadd) {
         Html::closeForm();
     }
     echo "<div id='viewvalidation" . $tID . "{$rand}'></div>\n";
     if ($canadd) {
         echo "<script type='text/javascript' >\n";
         echo "function viewAddValidation" . $tID . "{$rand}() {\n";
         $params = array('type' => $this->getType(), 'parenttype' => static::$itemtype, static::$items_id => $tID, 'id' => -1);
         Ajax::updateItemJsCode("viewvalidation" . $tID . "{$rand}", $CFG_GLPI["root_doc"] . "/ajax/viewsubitem.php", $params);
         echo "};";
         echo "</script>\n";
         if (!in_array($item->fields['status'], array_merge($item->getSolvedStatusArray(), $item->getClosedStatusArray()))) {
             echo "<div class='center'>";
             echo "<a class='vsubmit' href='javascript:viewAddValidation" . $tID . "{$rand}();'>";
             echo __('Send an approval request') . "</a></div><br>\n";
         }
     }
     $query = "SELECT *\n                FROM `" . $this->getTable() . "`\n                WHERE `" . static::$items_id . "` = '" . $item->getField('id') . "'";
     if (!$canadd) {
         $query .= " AND `users_id_validate` = '" . Session::getLoginUserID() . "'";
     }
     $query .= " ORDER BY submission_date DESC";
     $result = $DB->query($query);
     $number = $DB->numrows($result);
     if ($number) {
         $colonnes = array(_x('item', 'State'), __('Request date'), __('Approval requester'), __('Request comments'), __('Approval status'), __('Approver'), __('Approval comments'));
         $nb_colonnes = count($colonnes);
         echo "<table class='tab_cadre_fixehov'>";
         echo "<tr class='noHover'><th colspan='" . $nb_colonnes . "'>" . __('Approvals for the ticket') . "</th></tr>";
         $header = "<tr>";
         foreach ($colonnes as $colonne) {
             $header .= "<th>" . $colonne . "</th>";
         }
         $header .= "</tr>";
         echo $header;
         Session::initNavigateListItems($this->getType(), sprintf(__('%1$s = %2$s'), $item->getTypeName(1), $item->fields["name"]));
         while ($row = $DB->fetch_assoc($result)) {
             $canedit = $this->canEdit($row["id"]);
             Session::addToNavigateListItems($this->getType(), $row["id"]);
             $bgcolor = self::getStatusColor($row['status']);
             $status = self::getStatus($row['status']);
             echo "<tr class='tab_bg_1' " . ($canedit ? "style='cursor:pointer' onClick=\"viewEditValidation" . $item->fields['id'] . $row["id"] . "{$rand}();\"" : '') . " id='viewvalidation" . $this->fields[static::$items_id] . $row["id"] . "{$rand}'>";
             echo "<td>";
             if ($canedit) {
                 echo "\n<script type='text/javascript' >\n";
                 echo "function viewEditValidation" . $item->fields['id'] . $row["id"] . "{$rand}() {\n";
                 $params = array('type' => $this->getType(), 'parenttype' => static::$itemtype, static::$items_id => $this->fields[static::$items_id], 'id' => $row["id"]);
                 Ajax::updateItemJsCode("viewvalidation" . $item->fields['id'] . "{$rand}", $CFG_GLPI["root_doc"] . "/ajax/viewsubitem.php", $params);
                 echo "};";
                 echo "</script>\n";
             }
             echo "<div style='background-color:" . $bgcolor . ";'>" . $status . "</div></td>";
             echo "<td>" . Html::convDateTime($row["submission_date"]) . "</td>";
             echo "<td>" . getUserName($row["users_id"]) . "</td>";
             echo "<td>" . $row["comment_submission"] . "</td>";
             echo "<td>" . Html::convDateTime($row["validation_date"]) . "</td>";
             echo "<td>" . getUserName($row["users_id_validate"]) . "</td>";
             echo "<td>" . $row["comment_validation"] . "</td>";
             echo "</tr>";
         }
         echo $header;
         echo "</table>";
     } else {
         echo "<div class='center b'>" . __('No item found') . "</div>";
     }
 }