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' />". " <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; }
public function displayField($canEdit = true) { if ($canEdit) { $required = $this->isRequired() ? ' required' : ''; echo '<input type="hidden" class="form-control" name="formcreator_field_' . $this->fields['id'] . '" value="" />' . PHP_EOL; echo '<input type="file" class="form-control" name="formcreator_field_' . $this->fields['id'] . '" id="formcreator_field_' . $this->fields['id'] . '" />'; } else { $doc = new Document(); $answer = $this->getAnswer(); if ($doc->getFromDB($answer)) { echo $doc->getDownloadLink(); } } }
/** * 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 " "; 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 " "; 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 " "; // // 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 " "; // 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 " "; // // 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 " "; 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, '&') . "\">"; $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, '&') . "\">"; $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;'> " . $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}\"> {$status}"; case 'glpi_problems.status': $status = Problem::getStatus($data[$NAME . $num]); return "<img src=\"" . Problem::getStatusIconURL($data[$NAME . $num]) . "\"\n alt=\"{$status}\" title=\"{$status}\"> {$status}"; case 'glpi_tickets.status': $status = Ticket::getStatus($data[$NAME . $num]); return "<img src=\"" . Ticket::getStatusIconURL($data[$NAME . $num]) . "\"\n alt=\"{$status}\" title=\"{$status}\"> {$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 ' '; 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, '?') ? '&' : '?'; $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, '?') ? '&' : '?'; $out .= 'id=' . $data[$NAME . $num . "_2"]; // Force solution tab if solved if ($data[$NAME . $num . "_4"] == CommonITILObject::SOLVED) { $out .= "&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, '?') ? '&' : '?'; $out .= 'id=' . $data[$NAME . $num . "_2"]; if (isset($searchopt[$ID]['forcetab'])) { $out .= "&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) ? " " : $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 " "; 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(' ', ' ', 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(' ', ' ', 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(' ', ' ', Html::formatNumber($split2[0])); $out .= Dropdown::getValueWithUnit($number, $unit); } } } return $out; } $number = str_replace(' ', ' ', 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); }
static function showGeolocLocation($itemtype, $id, $positions_id = 0) { global $CFG_GLPI; $documents_id = self::getDocument($id); $locations_id = $id; $Doc = new Document(); if (isset($documents_id) && $Doc->getFromDB($documents_id)) { $target = $CFG_GLPI["root_doc"] . "/plugins/positions/front/geoloc.php?positions_id=" . $positions_id . "&download=1&locations_id=" . $locations_id; echo "<script type='text/javascript'>\n Position.openWindow('{$target}');\n </script>"; } }
/** * Copy order documents into the newly generated item * @since 1.5.3 * @param unknown_type $itemtype * @param unknown_type $items_id * @param unknown_type $orders_id * @param unknown_type $entity */ static function copyDocuments($itemtype, $items_id, $orders_id, $entity) { global $CFG_GLPI; $config = PluginOrderConfig::getConfig(); if ($config->canCopyDocuments() && in_array($itemtype, $CFG_GLPI["document_types"])) { $document_item = new Document_Item(); $document = new Document(); foreach (getAllDatasFromTable('glpi_documents_items', "`itemtype`='PluginOrderOrder'\n AND `items_id`='{$orders_id}'") as $doc) { $document->getFromDB($doc['documents_id']); $mime = $document->fields['mime']; $newdocument = clone $document; $newdocument->fields['entities_id'] = $entity; unset($newdocument->fields['id']); $newID = $document->add($newdocument->fields); $tmp['itemtype'] = $itemtype; $tmp['items_id'] = $items_id; $tmp['documents_id'] = $newID; $document_item->add($tmp); //force mimetype $document->update(array('id' => $newID, 'mime' => $mime)); } } }
You should have received a copy of the GNU General Public License along with GLPI. If not, see <http://www.gnu.org/licenses/>. -------------------------------------------------------------------------- */ /** @file * @brief */ include '../inc/includes.php'; if (!$CFG_GLPI["use_public_faq"]) { Session::checkLoginUser(); } $doc = new Document(); if (isset($_GET['docid'])) { // docid for document if (!$doc->getFromDB($_GET['docid'])) { Html::displayErrorAndDie(__('Unknown file'), true); } if (!file_exists(GLPI_DOC_DIR . "/" . $doc->fields['filepath'])) { Html::displayErrorAndDie(__('File not found'), true); // Not found } else { if ($doc->canViewFile($_GET)) { if ($doc->fields['sha1sum'] && $doc->fields['sha1sum'] != sha1_file(GLPI_DOC_DIR . "/" . $doc->fields['filepath'])) { Html::displayErrorAndDie(__('File is altered (bad checksum)'), true); // Doc alterated } else { $doc->send(); } } else { Html::displayErrorAndDie(__('Unauthorized access to this file'), true);
/** * Generic Function to display Items * * @param $itemtype item type * @param $ID ID of the SEARCH_OPTION item * @param $data array containing data results * @param $num item num in the request * @param $meta is a meta item ? (default 0) * @param $addobjectparams array added parameters for union search * * @return string to print **/ static function giveItem($itemtype, $ID, array $data, $num, $meta = 0, array $addobjectparams = array()) { global $CFG_GLPI, $DB; $searchopt =& self::getOptions($itemtype); if (isset($CFG_GLPI["union_search_type"][$itemtype]) && $CFG_GLPI["union_search_type"][$itemtype] == $searchopt[$ID]["table"]) { if (isset($searchopt[$ID]['addobjectparams']) && $searchopt[$ID]['addobjectparams']) { return self::giveItem($data["TYPE"], $ID, $data, $num, $meta, $searchopt[$ID]['addobjectparams']); } return self::giveItem($data["TYPE"], $ID, $data, $num, $meta); } if (count($addobjectparams)) { $searchopt[$ID] = array_merge($searchopt[$ID], $addobjectparams); } // Plugin can override core definition for its type if ($plug = isPluginItemType($itemtype)) { $function = 'plugin_' . $plug['plugin'] . '_giveItem'; if (function_exists($function)) { $out = $function($itemtype, $ID, $data, $num); if (!empty($out)) { return $out; } } } $NAME = "ITEM_"; // if ($meta) { // $NAME = "META_"; // } if (isset($searchopt[$ID]["table"])) { $table = $searchopt[$ID]["table"]; $field = $searchopt[$ID]["field"]; $linkfield = $searchopt[$ID]["linkfield"]; /// TODO try to clean all specific cases using SpecificToDisplay switch ($table . '.' . $field) { case "glpi_users.name": // USER search case if ($itemtype != 'User' && isset($searchopt[$ID]["forcegroupby"]) && $searchopt[$ID]["forcegroupby"]) { $out = ""; $count_display = 0; $added = array(); $showuserlink = 0; if (Session::haveRight('user', READ)) { $showuserlink = 1; } for ($k = 0; $k < $data[$num]['count']; $k++) { if (isset($data[$num][$k]['name']) && $data[$num][$k]['name'] > 0 || isset($data[$num][$k][2]) && $data[$num][$k][2] != '') { if ($count_display) { $out .= self::LBBR; } if ($itemtype == 'Ticket') { if (isset($data[$num][$k]['name']) && $data[$num][$k]['name'] > 0) { $userdata = getUserName($data[$num][$k]['name'], 2); $tooltip = ""; if (Session::haveRight('user', READ)) { $tooltip = Html::showToolTip($userdata["comment"], array('link' => $userdata["link"], 'display' => false)); } $out .= sprintf(__('%1$s %2$s'), $userdata['name'], $tooltip); $count_display++; } } else { $out .= getUserName($data[$num][$k]['name'], $showuserlink); $count_display++; } // Manage alternative_email for tickets_users if ($itemtype == 'Ticket' && isset($data[$num][$k][2])) { $split = explode(self::LONGSEP, $data[$num][$k][2]); for ($l = 0; $l < count($split); $l++) { $split2 = explode(" ", $split[$l]); if (count($split2) == 2 && $split2[0] == 0 && !empty($split2[1])) { if ($count_display) { $out .= self::LBBR; } $count_display++; $out .= "<a href='mailto:" . $split2[1] . "'>" . $split2[1] . "</a>"; } } } } } return $out; } if ($itemtype != 'User') { $toadd = ''; if ($itemtype == 'Ticket' && $data[$num][0]['id'] > 0) { $userdata = getUserName($data[$num][0]['id'], 2); $toadd = Html::showToolTip($userdata["comment"], array('link' => $userdata["link"], 'display' => false)); } $usernameformat = formatUserName($data[$num][0]['id'], $data[$num][0]['name'], $data[$num][0]['realname'], $data[$num][0]['firstname'], 1); return sprintf(__('%1$s %2$s'), $usernameformat, $toadd); } break; case "glpi_profiles.name": if ($itemtype == 'User' && $ID == 20) { $out = ""; $count_display = 0; $added = array(); for ($k = 0; $k < $data[$num]['count']; $k++) { if (strlen(trim($data[$num][$k]['name'])) > 0) { $text = sprintf(__('%1$s - %2$s'), $data[$num][$k]['name'], Dropdown::getDropdownName('glpi_entities', $data[$num][$k]['entities_id'])); $comp = ''; if ($data[$num][$k]['is_recursive']) { $comp = __('R'); if ($data[$num][$k]['is_dynamic']) { $comp = sprintf(__('%1$s%2$s'), $comp, ", "); } } if ($data[$num][$k]['is_dynamic']) { $comp = sprintf(__('%1$s%2$s'), $comp, __('D')); } if (!empty($comp)) { $text = sprintf(__('%1$s %2$s'), $text, "(" . $comp . ")"); } if (!in_array($text, $added)) { if ($count_display) { $out .= self::LBBR; } $count_display++; $out .= $text; $added[] = $text; } } } return $out; } break; case "glpi_entities.completename": if ($itemtype == 'User') { $out = ""; $added = array(); $count_display = 0; for ($k = 0; $k < $data[$num]['count']; $k++) { if (strlen(trim($data[$num][$k]['name'])) > 0) { $text = sprintf(__('%1$s - %2$s'), $data[$num][$k]['name'], Dropdown::getDropdownName('glpi_profiles', $data[$num][$k]['profiles_id'])); $comp = ''; if ($data[$num][$k]['is_recursive']) { $comp = __('R'); if ($data[$num][$k]['is_dynamic']) { $comp = sprintf(__('%1$s%2$s'), $comp, ", "); } } if ($data[$num][$k]['is_dynamic']) { $comp = sprintf(__('%1$s%2$s'), $comp, __('D')); } if (!empty($comp)) { $text = sprintf(__('%1$s %2$s'), $text, "(" . $comp . ")"); } if (!in_array($text, $added)) { if ($count_display) { $out .= self::LBBR; } $count_display++; $out .= $text; $added[] = $text; } } } return $out; } break; case "glpi_documenttypes.icon": if (!empty($data[$num][0]['name'])) { return "<img class='middle' alt='' src='" . $CFG_GLPI["typedoc_icon_dir"] . "/" . $data[$num][0]['name'] . "'>"; } return " "; case "glpi_documents.filename": $doc = new Document(); if ($doc->getFromDB($data['id'])) { return $doc->getDownloadLink(); } return NOT_AVAILABLE; case "glpi_tickets_tickets.tickets_id_1": $out = ""; $displayed = array(); for ($k = 0; $k < $data[$num]['count']; $k++) { $linkid = $data[$num][$k]['tickets_id_2'] == $data['id'] ? $data[$num][$k]['name'] : $data[$num][$k]['tickets_id_2']; if ($linkid > 0 && !isset($displayed[$linkid])) { $text = "<a "; $text .= "href=\"" . $CFG_GLPI["root_doc"] . "/front/ticket.form.php?id={$linkid}\">"; $text .= Dropdown::getDropdownName('glpi_tickets', $linkid) . "</a>"; if (count($displayed)) { $out .= self::LBBR; } $displayed[$linkid] = $linkid; $out .= $text; } } return $out; case "glpi_problems.id": if ($searchopt[$ID]["datatype"] == 'count') { if ($data[$num][0]['name'] > 0 && Session::haveRight("problem", Problem::READALL)) { if ($itemtype == 'ITILCategory') { $options['criteria'][0]['field'] = 7; $options['criteria'][0]['searchtype'] = 'equals'; $options['criteria'][0]['value'] = $data['id']; $options['criteria'][0]['link'] = 'AND'; } else { $options['criteria'][0]['field'] = 12; $options['criteria'][0]['searchtype'] = 'equals'; $options['criteria'][0]['value'] = 'all'; $options['criteria'][0]['link'] = 'AND'; $options['metacriteria'][0]['itemtype'] = $itemtype; $options['metacriteria'][0]['field'] = self::getOptionNumber($itemtype, 'name'); $options['metacriteria'][0]['searchtype'] = 'equals'; $options['metacriteria'][0]['value'] = $data['id']; $options['metacriteria'][0]['link'] = 'AND'; } $options['reset'] = 'reset'; $out = "<a id='problem{$itemtype}" . $data['id'] . "' "; $out .= "href=\"" . $CFG_GLPI["root_doc"] . "/front/problem.php?" . Toolbox::append_params($options, '&') . "\">"; $out .= $data[$num][0]['name'] . "</a>"; return $out; } } break; case "glpi_tickets.id": if ($searchopt[$ID]["datatype"] == 'count') { if ($data[$num][0]['name'] > 0 && Session::haveRight("ticket", Ticket::READALL)) { if ($itemtype == 'User') { // Requester if ($ID == 60) { $options['criteria'][0]['field'] = 4; $options['criteria'][0]['searchtype'] = 'equals'; $options['criteria'][0]['value'] = $data['id']; $options['criteria'][0]['link'] = 'AND'; } // Writer if ($ID == 61) { $options['criteria'][0]['field'] = 22; $options['criteria'][0]['searchtype'] = 'equals'; $options['criteria'][0]['value'] = $data['id']; $options['criteria'][0]['link'] = 'AND'; } // Assign if ($ID == 64) { $options['criteria'][0]['field'] = 5; $options['criteria'][0]['searchtype'] = 'equals'; $options['criteria'][0]['value'] = $data['id']; $options['criteria'][0]['link'] = 'AND'; } } else { if ($itemtype == 'ITILCategory') { $options['criteria'][0]['field'] = 7; $options['criteria'][0]['searchtype'] = 'equals'; $options['criteria'][0]['value'] = $data['id']; $options['criteria'][0]['link'] = 'AND'; } else { $options['criteria'][0]['field'] = 12; $options['criteria'][0]['searchtype'] = 'equals'; $options['criteria'][0]['value'] = 'all'; $options['criteria'][0]['link'] = 'AND'; $options['metacriteria'][0]['itemtype'] = $itemtype; $options['metacriteria'][0]['field'] = self::getOptionNumber($itemtype, 'name'); $options['metacriteria'][0]['searchtype'] = 'equals'; $options['metacriteria'][0]['value'] = $data['id']; $options['metacriteria'][0]['link'] = 'AND'; } } $options['reset'] = 'reset'; $out = "<a id='ticket{$itemtype}" . $data['id'] . "' "; $out .= "href=\"" . $CFG_GLPI["root_doc"] . "/front/ticket.php?" . Toolbox::append_params($options, '&') . "\">"; $out .= $data[$num][0]['name'] . "</a>"; return $out; } } break; case "glpi_tickets.due_date": case "glpi_problems.due_date": case "glpi_changes.due_date": // Due date + progress if ($ID == 151) { $out = Html::convDate($data[$num][0]['name']); // No due date in waiting status if ($data[$num][0]['status'] == CommonITILObject::WAITING) { return ''; } if (empty($data[$num][0]['name'])) { return ''; } if ($data[$num][0]['status'] == Ticket::SOLVED || $data[$num][0]['status'] == Ticket::CLOSED) { return $out; } $itemtype = getItemTypeForTable($table); $item = new $itemtype(); $item->getFromDB($data['id']); $percentage = 0; $totaltime = 0; $currenttime = 0; if ($item->isField('slas_id') && $item->fields['slas_id'] != 0) { // Have SLA $sla = new SLA(); $sla->getFromDB($item->fields['slas_id']); $currenttime = $sla->getActiveTimeBetween($item->fields['date'], date('Y-m-d H:i:s')); $totaltime = $sla->getActiveTimeBetween($item->fields['date'], $data[$num][0]['name']); } else { $calendars_id = Entity::getUsedConfig('calendars_id', $item->fields['entities_id']); if ($calendars_id != 0) { // Ticket entity have calendar $calendar = new Calendar(); $calendar->getFromDB($calendars_id); $currenttime = $calendar->getActiveTimeBetween($item->fields['date'], date('Y-m-d H:i:s')); $totaltime = $calendar->getActiveTimeBetween($item->fields['date'], $data[$num][0]['name']); } else { // No calendar $currenttime = strtotime(date('Y-m-d H:i:s')) - strtotime($item->fields['date']); $totaltime = strtotime($data[$num][0]['name']) - strtotime($item->fields['date']); } } if ($totaltime != 0) { $percentage = round(100 * $currenttime / $totaltime); } else { // Total time is null : no active time $percentage = 100; } if ($percentage > 100) { $percentage = 100; } $percentage_text = $percentage; if ($_SESSION['glpiduedatewarning_unit'] == '%') { $less_warn_limit = $_SESSION['glpiduedatewarning_less']; $less_warn = 100 - $percentage; } else { if ($_SESSION['glpiduedatewarning_unit'] == 'hour') { $less_warn_limit = $_SESSION['glpiduedatewarning_less'] * HOUR_TIMESTAMP; $less_warn = $totaltime - $currenttime; } else { if ($_SESSION['glpiduedatewarning_unit'] == 'day') { $less_warn_limit = $_SESSION['glpiduedatewarning_less'] * DAY_TIMESTAMP; $less_warn = $totaltime - $currenttime; } } } if ($_SESSION['glpiduedatecritical_unit'] == '%') { $less_crit_limit = $_SESSION['glpiduedatecritical_less']; $less_crit = 100 - $percentage; } else { if ($_SESSION['glpiduedatecritical_unit'] == 'hour') { $less_crit_limit = $_SESSION['glpiduedatecritical_less'] * HOUR_TIMESTAMP; $less_crit = $totaltime - $currenttime; } else { if ($_SESSION['glpiduedatecritical_unit'] == 'day') { $less_crit_limit = $_SESSION['glpiduedatecritical_less'] * DAY_TIMESTAMP; $less_crit = $totaltime - $currenttime; } } } $color = $_SESSION['glpiduedateok_color']; if ($less_crit < $less_crit_limit) { $color = $_SESSION['glpiduedatecritical_color']; } else { if ($less_warn < $less_warn_limit) { $color = $_SESSION['glpiduedatewarning_color']; } } //Calculate bar progress $out .= "<div class='center' style='background-color: #ffffff; width: 100%;\n border: 1px solid #9BA563; position: relative;' >"; $out .= "<div style='position:absolute;'> " . $percentage_text . "%</div>"; $out .= "<div class='center' style='background-color: " . $color . ";\n width: " . $percentage . "%; height: 12px' ></div>"; $out .= "</div>"; return $out; } break; case "glpi_softwarelicenses.number": if ($data[$num][0]['min'] == -1) { return __('Unlimited'); } if (empty($data[$num][0]['name'])) { return 0; } return $data[$num][0]['name']; case "glpi_auth_tables.name": return Auth::getMethodName($data[$num][0]['name'], $data[$num][0]['auths_id'], 1, $data[$num][0]['ldapname'] . $data[$num][0]['mailname']); case "glpi_reservationitems.comment": if (empty($data[$num][0]['name'])) { return "<a title=\"" . __s('Modify the comment') . "\"\n href='" . $CFG_GLPI["root_doc"] . "/front/reservationitem.form.php?id=" . $data["refID"] . "' >" . __('None') . "</a>"; } return "<a title=\"" . __s('Modify the comment') . "\"\n href='" . $CFG_GLPI["root_doc"] . "/front/reservationitem.form.php?id=" . $data['refID'] . "' >" . Html::resume_text($data[$num][0]['name']) . "</a>"; case 'glpi_crontasks.description': $tmp = new CronTask(); return $tmp->getDescription($data[$num][0]['name']); case 'glpi_changes.status': $status = Change::getStatus($data[$num][0]['name']); return "<img src=\"" . Change::getStatusIconURL($data[$num][0]['name']) . "\"\n alt=\"{$status}\" title=\"{$status}\"> {$status}"; case 'glpi_problems.status': $status = Problem::getStatus($data[$num][0]['name']); return "<img src=\"" . Problem::getStatusIconURL($data[$num][0]['name']) . "\"\n alt=\"{$status}\" title=\"{$status}\"> {$status}"; case 'glpi_tickets.status': $status = Ticket::getStatus($data[$num][0]['name']); return "<img src=\"" . Ticket::getStatusIconURL($data[$num][0]['name']) . "\"\n alt=\"{$status}\" title=\"{$status}\"> {$status}"; case 'glpi_projectstates.name': $out = ''; $query = "SELECT `color`\n FROM `glpi_projectstates`\n WHERE `name` = '" . $data[$num][0]['name'] . "'"; foreach ($DB->request($query) as $color) { $color = $color['color']; $out = "<div style=\"background-color:" . $color . ";\">"; $name = $data[$num][0]['name']; if (isset($data[$num][0]['trans'])) { $name = $data[$num][0]['trans']; } if ($itemtype == 'ProjectState') { $out .= "<a href='" . $CFG_GLPI["root_doc"] . "/front/projectstate.form.php?id=" . $data[$num][0]["id"] . "'>" . $name . "</a></div>"; } else { $out .= $name . "</div>"; } } return $out; case 'glpi_items_tickets.items_id': case 'glpi_items_problems.items_id': if (!empty($data[$num])) { $items = array(); foreach ($data[$num] as $key => $val) { if (is_numeric($key)) { if (!empty($val['itemtype']) && ($item = getItemForItemtype($val['itemtype']))) { if ($item->getFromDB($val['name'])) { $items[] = $item->getLink(array('comments' => true)); } } } } if (!empty($items)) { return implode("<br>", $items); } } return ' '; case 'glpi_items_tickets.itemtype': case 'glpi_items_problems.itemtype': if (!empty($data[$num])) { $itemtypes = array(); foreach ($data[$num] as $key => $val) { if (is_numeric($key)) { if (!empty($val['name'])) { if (substr($val['name'], 0, 6) == 'Plugin') { $plug = new $val['name'](); $name = $plug->getTypeName(); $itemtypes[] = __($name); } else { $itemtypes[] = __($val['name']); } } } } if (!empty($itemtypes)) { return implode("<br>", $itemtypes); } } return ' '; case 'glpi_tickets.name': case 'glpi_problems.name': case 'glpi_changes.name': if (isset($data[$num][0]['content']) && isset($data[$num][0]['id']) && isset($data[$num][0]['status'])) { $link = Toolbox::getItemTypeFormURL($itemtype); $out = "<a id='{$itemtype}" . $data[$num][0]['id'] . "' href=\"" . $link; $out .= strstr($link, '?') ? '&' : '?'; $out .= 'id=' . $data[$num][0]['id']; // Force solution tab if solved if ($item = getItemForItemtype($itemtype)) { if (in_array($data[$num][0]['status'], $item->getSolvedStatusArray())) { $out .= "&forcetab={$itemtype}\$2"; } } $out .= "\">"; $name = $data[$num][0]['name']; if ($_SESSION["glpiis_ids_visible"] || empty($data[$num][0]['name'])) { $name = sprintf(__('%1$s (%2$s)'), $name, $data[$num][0]['id']); } $out .= $name . "</a>"; $hdecode = Html::entity_decode_deep($data[$num][0]['content']); $content = Toolbox::unclean_cross_side_scripting_deep($hdecode); $out = sprintf(__('%1$s %2$s'), $out, Html::showToolTip(nl2br(Html::Clean($content)), array('applyto' => $itemtype . $data[$num][0]['id'], 'display' => false))); return $out; } case 'glpi_ticketvalidations.status': $out = ''; for ($k = 0; $k < $data[$num]['count']; $k++) { if ($data[$num][$k]['name']) { $status = TicketValidation::getStatus($data[$num][$k]['name']); $bgcolor = TicketValidation::getStatusColor($data[$num][$k]['name']); $out .= (empty($out) ? '' : self::LBBR) . "<div style=\"background-color:" . $bgcolor . ";\">" . $status . '</div>'; } } return $out; case 'glpi_ticketsatisfactions.satisfaction': if (self::$output_type == self::HTML_OUTPUT) { return TicketSatisfaction::displaySatisfaction($data[$num][0]['name']); } break; case 'glpi_projects._virtual_planned_duration': return Html::timestampToString(ProjectTask::getTotalPlannedDurationForProject($data["id"]), false); case 'glpi_projects._virtual_effective_duration': return Html::timestampToString(ProjectTask::getTotalEffectiveDurationForProject($data["id"]), false); case 'glpi_cartridgeitems._virtual': return Cartridge::getCount($data["id"], $data[$num][0]['alarm_threshold'], self::$output_type != self::HTML_OUTPUT); case 'glpi_printers._virtual': return Cartridge::getCountForPrinter($data["id"], self::$output_type != self::HTML_OUTPUT); case 'glpi_consumableitems._virtual': return Consumable::getCount($data["id"], $data[$num][0]['alarm_threshold'], self::$output_type != self::HTML_OUTPUT); case 'glpi_links._virtual': $out = ''; $link = new Link(); if (($item = getItemForItemtype($itemtype)) && $item->getFromDB($data['id']) && $link->getfromDB($data[$num][0]['id']) && $item->fields['entities_id'] == $link->fields['entities_id']) { if (count($data[$num])) { $count_display = 0; foreach ($data[$num] as $val) { if (is_array($val)) { $links = Link::getAllLinksFor($item, $val); foreach ($links as $link) { if ($count_display) { $out .= self::LBBR; } $out .= $link; $count_display++; } } } } } return $out; case 'glpi_reservationitems._virtual': if ($data[$num][0]['is_active']) { return "<a href='reservation.php?reservationitems_id=" . $data["refID"] . "' title=\"" . __s('See planning') . "\">" . "<img src=\"" . $CFG_GLPI["root_doc"] . "/pics/reservation-3.png\" alt='' title=''></a>"; } else { return " "; } } } //// Default case // Link with plugin tables : need to know left join structure if (isset($table)) { if (preg_match("/^glpi_plugin_([a-z0-9]+)/", $table . '.' . $field, $matches)) { if (count($matches) == 2) { $plug = $matches[1]; $function = 'plugin_' . $plug . '_giveItem'; if (function_exists($function)) { $out = $function($itemtype, $ID, $data, $num); if (!empty($out)) { return $out; } } } } } $unit = ''; if (isset($searchopt[$ID]['unit'])) { $unit = $searchopt[$ID]['unit']; } // Preformat items if (isset($searchopt[$ID]["datatype"])) { switch ($searchopt[$ID]["datatype"]) { case "itemlink": $linkitemtype = getItemTypeForTable($searchopt[$ID]["table"]); $out = ""; $count_display = 0; $separate = self::LBBR; if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) { $separate = self::LBHR; } for ($k = 0; $k < $data[$num]['count']; $k++) { if (isset($data[$num][$k]['id'])) { if ($count_display) { $out .= $separate; } $count_display++; $page = $linkitemtype::getFormUrl(); $page .= strpos($page, '?') ? '&id' : '?id'; $name = Dropdown::getValueWithUnit($data[$num][$k]['name'], $unit); if ($_SESSION["glpiis_ids_visible"] || empty($data[$num][$k]['name'])) { $name = sprintf(__('%1$s (%2$s)'), $name, $data[$num][$k]['id']); } $out .= "<a id='" . $linkitemtype . "_" . $data['id'] . "_" . $data[$num][$k]['id'] . "' href='{$page}=" . $data[$num][$k]['id'] . "'>" . $name . "</a>"; } } return $out; case "text": $separate = self::LBBR; if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) { $separate = self::LBHR; } $out = ''; $count_display = 0; for ($k = 0; $k < $data[$num]['count']; $k++) { if (strlen(trim($data[$num][$k]['name'])) > 0) { if ($count_display) { $out .= $separate; } $count_display++; $text = ""; if (isset($searchopt[$ID]['htmltext']) && $searchopt[$ID]['htmltext']) { $text = Html::clean(Toolbox::unclean_cross_side_scripting_deep(nl2br($data[$num][$k]['name']))); } else { $text = nl2br($data[$num][$k]['name']); } if (self::$output_type == self::HTML_OUTPUT && Toolbox::strlen($text) > $CFG_GLPI['cut']) { $rand = mt_rand(); $out .= sprintf(__('%1$s %2$s'), "<span id='text{$rand}'>" . Html::resume_text($text, $CFG_GLPI['cut']) . '</span>', Html::showToolTip($text, array('applyto' => "text{$rand}", 'display' => false))); } else { $out .= $text; } } } return $out; case "date": case "date_delay": $out = ''; for ($k = 0; $k < $data[$num]['count']; $k++) { if (is_null($data[$num][$k]['name']) && isset($searchopt[$ID]['emptylabel']) && $searchopt[$ID]['emptylabel']) { $out .= (empty($out) ? '' : self::LBBR) . $searchopt[$ID]['emptylabel']; } else { $out .= (empty($out) ? '' : self::LBBR) . Html::convDate($data[$num][$k]['name']); } } return $out; case "datetime": $out = ''; for ($k = 0; $k < $data[$num]['count']; $k++) { if (is_null($data[$num][$k]['name']) && isset($searchopt[$ID]['emptylabel']) && $searchopt[$ID]['emptylabel']) { $out .= (empty($out) ? '' : self::LBBR) . $searchopt[$ID]['emptylabel']; } else { $out .= (empty($out) ? '' : self::LBBR) . Html::convDateTime($data[$num][$k]['name']); } } return $out; case "timestamp": $withseconds = false; if (isset($searchopt[$ID]['withseconds'])) { $withseconds = $searchopt[$ID]['withseconds']; } $withdays = true; if (isset($searchopt[$ID]['withdays'])) { $withdays = $searchopt[$ID]['withdays']; } $out = ''; for ($k = 0; $k < $data[$num]['count']; $k++) { $out .= (empty($out) ? '' : '<br>') . Html::timestampToString($data[$num][$k]['name'], $withseconds, $withdays); } return $out; case "email": $out = ''; $count_display = 0; for ($k = 0; $k < $data[$num]['count']; $k++) { if ($count_display) { $out .= self::LBBR; } $count_display++; if (!empty($data[$num][$k]['name'])) { $out .= empty($out) ? '' : self::LBBR; $out .= "<a href='mailto:" . $data[$num][$k]['name'] . "'>" . $data[$num][$k]['name']; $out .= "</a>"; } } return empty($out) ? " " : $out; case "weblink": $orig_link = trim($data[$num][0]['name']); if (!empty($orig_link)) { // strip begin of link $link = preg_replace('/https?:\\/\\/(www[^\\.]*\\.)?/', '', $orig_link); $link = preg_replace('/\\/$/', '', $link); if (Toolbox::strlen($link) > $CFG_GLPI["url_maxlength"]) { $link = Toolbox::substr($link, 0, $CFG_GLPI["url_maxlength"]) . "..."; } return "<a href=\"" . formatOutputWebLink($orig_link) . "\" target='_blank'>{$link}</a>"; } return " "; case "count": case "number": $out = ""; $count_display = 0; for ($k = 0; $k < $data[$num]['count']; $k++) { if (strlen(trim($data[$num][$k]['name'])) > 0) { if ($count_display) { $out .= self::LBBR; } $count_display++; if (isset($searchopt[$ID]['toadd']) && isset($searchopt[$ID]['toadd'][$data[$num][$k]['name']])) { $out .= $searchopt[$ID]['toadd'][$data[$num][$k]['name']]; } else { $number = str_replace(' ', ' ', Html::formatNumber($data[$num][$k]['name'], false, 0)); $out .= Dropdown::getValueWithUnit($number, $unit); } } } return $out; case "decimal": $out = ""; $count_display = 0; for ($k = 0; $k < $data[$num]['count']; $k++) { if (strlen(trim($data[$num][$k]['name'])) > 0) { if ($count_display) { $out .= self::LBBR; } $count_display++; if (isset($searchopt[$ID]['toadd']) && isset($searchopt[$ID]['toadd'][$data[$num][$k]['name']])) { $out .= $searchopt[$ID]['toadd'][$data[$num][$k]['name']]; } else { $number = str_replace(' ', ' ', Html::formatNumber($data[$num][$k]['name'])); $out .= Dropdown::getValueWithUnit($number, $unit); } } } return $out; case "bool": $out = ""; $count_display = 0; for ($k = 0; $k < $data[$num]['count']; $k++) { if (strlen(trim($data[$num][$k]['name'])) > 0) { if ($count_display) { $out .= self::LBBR; } $count_display++; $out .= Dropdown::getValueWithUnit(Dropdown::getYesNo($data[$num][$k]['name']), $unit); } } return $out; case "itemtypename": if ($obj = getItemForItemtype($data[$num][0]['name'])) { return $obj->getTypeName(); } return ""; case "language": if (isset($CFG_GLPI['languages'][$data[$num][0]['name']])) { return $CFG_GLPI['languages'][$data[$num][0]['name']][0]; } return __('Default value'); } } // Manage items with need group by / group_concat $out = ""; $count_display = 0; $separate = self::LBBR; if (isset($searchopt[$ID]['splititems']) && $searchopt[$ID]['splititems']) { $separate = self::LBHR; } for ($k = 0; $k < $data[$num]['count']; $k++) { if (strlen(trim($data[$num][$k]['name'])) > 0) { if ($count_display) { $out .= $separate; } $count_display++; // Get specific display if available $itemtype = getItemTypeForTable($table); if ($item = getItemForItemtype($itemtype)) { $tmpdata = $data[$num][$k]; // Copy name to real field $tmpdata[$field] = $data[$num][$k]['name']; $specific = $item->getSpecificValueToDisplay($field, $tmpdata, array('html' => true, 'searchopt' => $searchopt[$ID])); } if (!empty($specific)) { $out .= $specific; } else { if (isset($searchopt[$ID]['toadd']) && isset($searchopt[$ID]['toadd'][$data[$num][$k]['name']])) { $out .= $searchopt[$ID]['toadd'][$data[$num][$k]['name']]; } else { // Empty is 0 or empty if (empty($split[0]) && isset($searchopt[$ID]['emptylabel'])) { $out .= $searchopt[$ID]['emptylabel']; } else { // Trans field exists if (isset($data[$num][$k]['trans']) && !empty($data[$num][$k]['trans'])) { $out .= Dropdown::getValueWithUnit($data[$num][$k]['trans'], $unit); } else { $out .= Dropdown::getValueWithUnit($data[$num][$k]['name'], $unit); } } } } } } return $out; // Trans in group concat if (count($split) == 3 && !empty($split[1])) { return Dropdown::getValueWithUnit($split[1], $unit); } return Dropdown::getValueWithUnit($split[0], $unit); }
function prepareInputForUpdate($input) { global $LANG, $CFG_GLPI; // Get ticket : need for comparison $this->getFromDB($input['id']); if (isset($input["date"]) && empty($input["date"])) { unset($input["date"]); } if (isset($input["closedate"]) && empty($input["closedate"])) { unset($input["closedate"]); } if (isset($input["solvedate"]) && empty($input["solvedate"])) { unset($input["solvedate"]); } // check mandatory fields if ($CFG_GLPI["is_ticket_title_mandatory"] && isset($input['name'])) { $title = trim($input['name']); if (empty($title)) { addMessageAfterRedirect($LANG['tracking'][6], false, ERROR); unset($input['name']); } } if ($CFG_GLPI["is_ticket_content_mandatory"] && isset($input['content'])) { $content = trim($input['content']); if (empty($content)) { addMessageAfterRedirect($LANG['tracking'][7], false, ERROR); unset($input['content']); } } // Security checks if (is_numeric(getLoginUserID(false)) && !haveRight("assign_ticket", "1")) { if (isset($input["_ticket_assign"]) && isset($input['_ticket_assign']['_type']) && $input['_ticket_assign']['_type'] == 'user') { // must own_ticket to grab a non assign ticket if ($this->countUsers(self::ASSIGN) == 0) { if (!haveRight("steal_ticket", "1") && !haveRight("own_ticket", "1") || !isset($input["_ticket_assign"]['users_id']) || $input["_ticket_assign"]['users_id'] != getLoginUserID()) { unset($input["_ticket_assign"]); } } else { // Can not steal or can steal and not assign to me if (!haveRight("steal_ticket", "1") || !isset($input["_ticket_assign"]['users_id']) || $input["_ticket_assign"]['users_id'] != getLoginUserID()) { unset($input["_ticket_assign"]); } } } // No supplier assign if (isset($input["suppliers_id_assign"])) { unset($input["suppliers_id_assign"]); } // No group if (isset($input["_ticket_assign"]) && isset($input['_ticket_assign']['_type']) && $input['_ticket_assign']['_type'] == 'group') { unset($input["_ticket_assign"]); } } if (is_numeric(getLoginUserID(false)) && !haveRight("update_ticket", "1")) { $allowed_fields = array('id'); if ($this->canApprove() && isset($input["status"])) { $allowed_fields[] = 'status'; } // for post-only with validate right $ticketval = new TicketValidation(); if (TicketValidation::canValidate($this->fields['id']) || $ticketval->canCreate()) { $allowed_fields[] = 'global_validation'; } // Manage assign and steal right if (haveRight('assign_ticket', 1) || haveRight('steal_ticket', 1)) { $allowed_fields[] = '_ticket_assign'; } if (haveRight('assign_ticket', 1)) { $allowed_fields[] = 'suppliers_id_assign'; } // Can only update initial fields if no followup or task already added if ($this->numberOfFollowups() == 0 && $this->numberOfTasks() == 0 && $this->isUser(self::REQUESTER, getLoginUserID())) { $allowed_fields[] = 'content'; $allowed_fields[] = 'urgency'; $allowed_fields[] = 'ticketcategories_id'; $allowed_fields[] = 'itemtype'; $allowed_fields[] = 'items_id'; $allowed_fields[] = 'name'; } if ($this->canSolve()) { $allowed_fields[] = 'ticketsolutiontypes_id'; $allowed_fields[] = 'solution'; } foreach ($allowed_fields as $field) { if (isset($input[$field])) { $ret[$field] = $input[$field]; } } $input = $ret; } // Manage fields from auto update : map rule actions to standard ones if (isset($input['_auto_update'])) { if (isset($input['_users_id_assign'])) { $input['_ticket_assign']['_type'] = 'user'; $input['_ticket_assign']['users_id'] = $input['_users_id_assign']; } if (isset($input['_groups_id_assign'])) { $input['_ticket_assign']['_type'] = 'group'; $input['_ticket_assign']['groups_id'] = $input['_groups_id_assign']; } if (isset($input['_users_id_requester'])) { $input['_ticket_requester']['_type'] = 'user'; $input['_ticket_requester']['users_id'] = $input['_users_id_requester']; } if (isset($input['_groups_id_requester'])) { $input['_ticket_requester']['_type'] = 'group'; $input['_ticket_requester']['groups_id'] = $input['_groups_id_requester']; } if (isset($input['_users_id_observer'])) { $input['_ticket_observer']['_type'] = 'user'; $input['_ticket_observer']['users_id'] = $input['_users_id_observer']; } if (isset($input['_groups_id_observer'])) { $input['_ticket_observer']['_type'] = 'group'; $input['_ticket_observer']['groups_id'] = $input['_groups_id_observer']; } } if (isset($input['_link'])) { $ticket_ticket = new Ticket_Ticket(); if (!empty($input['_link']['tickets_id_2']) && $ticket_ticket->can(-1, 'w', $input['_link'])) { if ($ticket_ticket->add($input['_link'])) { $input['_forcenotif'] = true; } } } if (isset($input['_ticket_requester'])) { if (isset($input['_ticket_requester']['_type'])) { $input['_ticket_requester']['type'] = self::REQUESTER; $input['_ticket_requester']['tickets_id'] = $input['id']; switch ($input['_ticket_requester']['_type']) { case "user": if (isset($input['_ticket_requester']['alternative_email']) && $input['_ticket_requester']['alternative_email'] && !NotificationMail::isUserAddressValid($input['_ticket_requester']['alternative_email'])) { addMessageAfterRedirect($LANG['mailing'][111] . ' : ' . $LANG['mailing'][110], false, ERROR); $input['_ticket_requester']['alternative_email'] = ''; } if (isset($input['_ticket_requester']['alternative_email']) && $input['_ticket_requester']['alternative_email'] || $input['_ticket_requester']['users_id'] > 0) { $ticket_user = new Ticket_User(); if ($ticket_user->can(-1, 'w', $input['_ticket_requester'])) { $ticket_user->add($input['_ticket_requester']); $input['_forcenotif'] = true; } } break; case "group": $group_ticket = new Group_Ticket(); if ($group_ticket->can(-1, 'w', $input['_ticket_requester'])) { $group_ticket->add($input['_ticket_requester']); $input['_forcenotif'] = true; } break; } } } if (isset($input['_ticket_observer'])) { if (isset($input['_ticket_observer']['_type'])) { $input['_ticket_observer']['type'] = self::OBSERVER; $input['_ticket_observer']['tickets_id'] = $input['id']; switch ($input['_ticket_observer']['_type']) { case "user": if (isset($input['_ticket_observer']['alternative_email']) && $input['_ticket_observer']['alternative_email'] && !NotificationMail::isUserAddressValid($input['_ticket_observer']['alternative_email'])) { $input['_ticket_observer']['alternative_email'] = ''; addMessageAfterRedirect($LANG['mailing'][111] . ' : ' . $LANG['mailing'][110], false, ERROR); } if (isset($input['_ticket_observer']['alternative_email']) && $input['_ticket_observer']['alternative_email'] || $input['_ticket_observer']['users_id'] > 0) { $ticket_user = new Ticket_User(); if ($ticket_user->can(-1, 'w', $input['_ticket_observer'])) { $ticket_user->add($input['_ticket_observer']); $input['_forcenotif'] = true; } } break; case "group": $group_ticket = new Group_Ticket(); if ($group_ticket->can(-1, 'w', $input['_ticket_observer'])) { $group_ticket->add($input['_ticket_observer']); $input['_forcenotif'] = true; } break; } } } if (isset($input['_ticket_assign'])) { if (isset($input['_ticket_assign']['_type'])) { $input['_ticket_assign']['type'] = self::ASSIGN; $input['_ticket_assign']['tickets_id'] = $input['id']; switch ($input['_ticket_assign']['_type']) { case "user": $ticket_user = new Ticket_User(); if ($ticket_user->can(-1, 'w', $input['_ticket_assign'])) { $ticket_user->add($input['_ticket_assign']); $input['_forcenotif'] = true; if (!isset($input['status']) && $this->fields['status'] == 'new' || isset($input['status']) && $input['status'] == 'new') { $input['status'] = 'assign'; } } break; case "group": $group_ticket = new Group_Ticket(); if ($group_ticket->can(-1, 'w', $input['_ticket_assign'])) { $group_ticket->add($input['_ticket_assign']); $input['_forcenotif'] = true; if (!isset($input['status']) && $this->fields['status'] == 'new' || isset($input['status']) && $input['status'] == 'new') { $input['status'] = 'assign'; } } break; } } } // set last updater when non auto update if (!isset($input['_auto_update']) && ($lastupdater = getLoginUserID(true))) { $input['users_id_lastupdater'] = $lastupdater; } if (isset($input["items_id"]) && $input["items_id"] >= 0 && isset($input["itemtype"])) { if (isset($this->fields['groups_id']) && $this->fields['groups_id'] == 0 && (!isset($input['groups_id']) || $input['groups_id'] == 0)) { if ($input["itemtype"] && class_exists($input["itemtype"])) { $item = new $input["itemtype"](); $item->getFromDB($input["items_id"]); if ($item->isField('groups_id')) { $input["groups_id"] = $item->getField('groups_id'); } } } } else { if (isset($input["itemtype"]) && empty($input["itemtype"])) { $input["items_id"] = 0; } else { unset($input["items_id"]); unset($input["itemtype"]); } } // Add document if needed $this->getFromDB($input["id"]); // entities_id field required if (!isset($input['_donotadddocs']) || !$input['_donotadddocs']) { $docadded = $this->addFiles($input["id"]); } /* if (count($docadded)>0) { $input["date_mod"]=$_SESSION["glpi_currenttime"]; if ($CFG_GLPI["add_followup_on_update_ticket"]) { $input['_doc_added']=$docadded; } } */ if (isset($input["document"]) && $input["document"] > 0) { $doc = new Document(); if ($doc->getFromDB($input["document"])) { $docitem = new Document_Item(); if ($docitem->add(array('documents_id' => $input["document"], 'itemtype' => $this->getType(), 'items_id' => $input["id"]))) { // Force date_mod of tracking $input["date_mod"] = $_SESSION["glpi_currenttime"]; $input['_doc_added'][] = $doc->fields["name"]; } } unset($input["document"]); } //Action for send_validation rule if (isset($input["_add_validation"]) && $input["_add_validation"] > 0) { $validation = new Ticketvalidation(); $values['tickets_id'] = $input['id']; $values['users_id_validate'] = $input["_add_validation"]; if (isset($input["_auto_update"])) { $values['_auto_update'] = true; } if ($validation->can(-1, 'w', $values)) { $validation->add($values); Event::log($this->fields['id'], "ticket", 4, "tracking", $_SESSION["glpiname"] . " " . $LANG['log'][21]); } } if (isset($input["status"]) && $input["status"] != 'solved' && $input["status"] != 'closed') { $input['solvedate'] = 'NULL'; } if (isset($input["status"]) && $input["status"] != 'closed') { $input['closedate'] = 'NULL'; } return $input; }
/** * Copy order documents into the newly generated item * @since 1.5.3 * @param unknown_type $itemtype * @param unknown_type $items_id * @param unknown_type $orders_id * @param unknown_type $entity */ public static function copyDocuments($itemtype, $items_id, $orders_id, $entity) { global $CFG_GLPI; $config = PluginOrderConfig::getConfig(); if ($config->canCopyDocuments() && in_array($itemtype, $CFG_GLPI["document_types"])) { $document = new Document(); $docitem = new Document_Item(); $item = new $itemtype(); $item->getFromDB($items_id); $is_recursive = 0; foreach (getAllDatasFromTable('glpi_documents_items', "`itemtype`='PluginOrderOrder'\n AND `items_id`='{$orders_id}'") as $doc) { //Create a new document $document->getFromDB($doc['documents_id']); if ($document->getEntityID() != $entity && !$document->fields['is_recursive'] || !in_array($entity, getSonsOf('glpi_entities', $document->getEntityID()))) { $found_docs = getAllDatasFromTable('glpi_documents', "`entities_id`='{$entity}'\n AND `sha1sum`='" . $document->fields['sha1sum'] . "'"); if (empty($found_docs)) { $tmpdoc = $document->fields; $tmpdoc['entities_id'] = $entity; unset($tmpdoc['id']); $documents_id = $document->add($tmpdoc); $is_recursive = $document->fields['is_recursive']; } else { $found_doc = array_pop($found_docs); $documents_id = $found_doc['id']; $is_recursive = $found_doc['is_recursive']; } } else { $documents_id = $document->getID(); $is_recursive = $document->fields['is_recursive']; } //Link the document to the newly generated item $fields['documents_id'] = $documents_id; $fields['entities_id'] = $entity; $fields['items_id'] = $items_id; $fields['itemtype'] = $itemtype; $fields['is_recursive'] = $is_recursive; $newID = $docitem->add($fields); } } }
/** * Send mai lin queue * * @param $ID integer ID of the item * * @return true if send false if not **/ function sendMailById($ID) { global $CFG_GLPI; if ($this->getFromDB($ID)) { $mmail = new GLPIMailer(); $headers = importArrayFromDB($this->fields['headers']); if (is_array($headers) && count($headers)) { foreach ($headers as $key => $val) { $mmail->AddCustomHeader("{$key}: {$val}"); } } // Add custom header for mail grouping in reader $mmail->AddCustomHeader("In-Reply-To: GLPI-" . $this->fields["itemtype"] . "-" . $this->fields["items_id"]); $mmail->SetFrom($this->fields['sender'], $this->fields['sendername']); if ($this->fields['replyto']) { $mmail->AddReplyTo($this->fields['replyto'], $this->fields['replytoname']); } $mmail->Subject = $this->fields['name']; if (empty($this->fields['body_html'])) { $mmail->isHTML(false); $mmail->Body = $this->fields['body_text']; } else { $mmail->isHTML(true); $mmail->Body = ''; $this->fields['body_html'] = Html::entity_decode_deep($this->fields['body_html']); $documents = importArrayFromDB($this->fields['documents']); $link_doc = array(); if (is_array($documents) && count($documents)) { $doc = new Document(); foreach ($documents as $docID) { $doc->getFromDB($docID); // Add embeded image if tag present in ticket content if (preg_match_all('/' . Document::getImageTag($doc->fields['tag']) . '/', $this->fields['body_html'], $matches, PREG_PATTERN_ORDER)) { $mmail->AddEmbeddedImage(GLPI_DOC_DIR . "/" . $doc->fields['filepath'], Document::getImageTag($doc->fields['tag']), $doc->fields['filename'], 'base64', $doc->fields['mime']); // Else Add link to the document } else { $link_doc[] = "<a href='" . rtrim($CFG_GLPI["url_base"], '/') . "/front/document.send.php?docid=" . $doc->fields['id'] . "' >" . $doc->fields['name'] . "</a>"; } } } $mmail->Body .= $this->fields['body_html']; if (count($link_doc)) { $mmail->Body .= '<p style="border:1px solid #cccccc;padding:5px">' . '<b>' . _n('Associated item', 'Associated items', Session::getPluralNumber()) . ' : </b>' . implode(', ', $link_doc) . '</p>'; } $mmail->AltBody = $this->fields['body_text']; } $mmail->AddAddress($this->fields['recipient'], $this->fields['recipientname']); if (!empty($this->fields['messageid'])) { $mmail->MessageID = "<" . $this->fields['messageid'] . ">"; } $messageerror = __('Error in sending the email'); if (!$mmail->Send()) { Session::addMessageAfterRedirect($messageerror . "<br>" . $mmail->ErrorInfo, true); $mmail->ClearAddresses(); $this->update(array('id' => $this->fields['id'], 'sent_try' => $this->fields['sent_try'] + 1)); return false; } else { //TRANS to be written in logs %1$s is the to email / %2$s is the subject of the mail Toolbox::logInFile("mail", sprintf(__('%1$s: %2$s'), sprintf(__('An email was sent to %s'), $this->fields['recipient']), $this->fields['name'] . "\n")); $mmail->ClearAddresses(); $this->update(array('id' => $this->fields['id'], 'sent_time' => $_SESSION['glpi_currenttime'])); $this->delete(array('id' => $this->fields['id'])); return true; } } else { return false; } }
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'] . " "; } 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 = " "; } //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 " "; 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 " "; 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 " "; 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 " "; 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}'> {$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 ' '; case 'glpi_tickets.id': $link = getItemTypeFormURLMobile('Ticket'); $out = "<a id='ticket" . $data[$NAME . $num . "_2"] . "' href=\"" . $link; $out .= strstr($link, '?') ? '&' : '?'; $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, '?') ? '&' : '?'; $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) ? " " : $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 " "; 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 " "; 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(' ', ' ', Html::formatNumber($split[$k], false, 0)) . $unit; } } return $out; } return str_replace(' ', ' ', 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(' ', ' ', Html::formatNumber($split[$k])) . $unit; } } return $out; } return str_replace(' ', ' ', 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; }
/** * 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'] . " " . 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 = " " . 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 " "; 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 " "; 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 " "; 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 " "; 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, '&') . "\">"; $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}\"> {$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 ' '; case 'glpi_tickets.name': $link = getItemTypeFormURL('Ticket'); $out = "<a id='ticket" . $data[$NAME . $num . "_2"] . "' href=\"" . $link; $out .= strstr($link, '?') ? '&' : '?'; $out .= 'id=' . $data[$NAME . $num . "_2"]; // Force solution tab if solved if ($data[$NAME . $num . "_4"] == 'solved') { $out .= "&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, '?') ? '&' : '?'; $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) ? " " : $out; case "email": $email = trim($data[$NAME . $num]); if (!empty($email)) { return "<a href='mailto:{$email}'>{$email}</a>"; } return " "; 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 " "; 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(' ', ' ', formatNumber($split[$k], false, 0)) . $unit; } } return $out; } return str_replace(' ', ' ', 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(' ', ' ', formatNumber($split[$k])) . $unit; } } return $out; } return str_replace(' ', ' ', 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; }
/** * Show documents associated to an item * * @since version 0.84 * * @param $item CommonDBTM object for which associated documents must be displayed * @param $withtemplate (default '') **/ static function showForItem(CommonDBTM $item, $withtemplate = '') { global $DB, $CFG_GLPI; $ID = $item->getField('id'); if ($item->isNewID($ID)) { return false; } if ($item->getType() != 'Ticket' && $item->getType() != 'KnowbaseItem' && $item->getType() != 'Reminder' && !Document::canView()) { return false; } if (!$item->can($item->fields['id'], READ)) { return false; } $columns = array('name' => __('Name'), 'entity' => __('Entity'), 'filename' => __('File'), 'link' => __('Web link'), 'headings' => __('Heading'), 'mime' => __('MIME type')); if ($CFG_GLPI['use_rich_text']) { $columns['tag'] = __('Tag'); } $columns['assocdate'] = __('Date'); if (empty($withtemplate)) { $withtemplate = 0; } $linkparam = ''; if (get_class($item) == 'Ticket') { $linkparam = "&tickets_id=" . $item->fields['id']; } if (isset($_GET["order"]) && $_GET["order"] == "ASC") { $order = "ASC"; } else { $order = "DESC"; } if (isset($_GET["sort"]) && !empty($_GET["sort"]) && isset($columns[$_GET["sort"]])) { $sort = "`" . $_GET["sort"] . "`"; } else { $sort = "`assocdate`"; } $canedit = $item->canAddItem('Document') && Document::canView(); $rand = mt_rand(); $is_recursive = $item->isRecursive(); $query = "SELECT `glpi_documents_items`.`id` AS assocID,\n `glpi_documents_items`.`date_mod` AS assocdate,\n `glpi_entities`.`id` AS entityID,\n `glpi_entities`.`completename` AS entity,\n `glpi_documentcategories`.`completename` AS headings,\n `glpi_documents`.*\n FROM `glpi_documents_items`\n LEFT JOIN `glpi_documents`\n ON (`glpi_documents_items`.`documents_id`=`glpi_documents`.`id`)\n LEFT JOIN `glpi_entities` ON (`glpi_documents`.`entities_id`=`glpi_entities`.`id`)\n LEFT JOIN `glpi_documentcategories`\n ON (`glpi_documents`.`documentcategories_id`=`glpi_documentcategories`.`id`)\n WHERE `glpi_documents_items`.`items_id` = '{$ID}'\n AND `glpi_documents_items`.`itemtype` = '" . $item->getType() . "' "; if (Session::getLoginUserID()) { $query .= getEntitiesRestrictRequest(" AND", "glpi_documents", '', '', true); } else { // Anonymous access from FAQ $query .= " AND `glpi_documents`.`entities_id`= '0' "; } // Document : search links in both order using union if ($item->getType() == 'Document') { $query .= "UNION\n SELECT `glpi_documents_items`.`id` AS assocID,\n `glpi_documents_items`.`date_mod` AS assocdate,\n `glpi_entities`.`id` AS entityID,\n `glpi_entities`.`completename` AS entity,\n `glpi_documentcategories`.`completename` AS headings,\n `glpi_documents`.*\n FROM `glpi_documents_items`\n LEFT JOIN `glpi_documents`\n ON (`glpi_documents_items`.`items_id`=`glpi_documents`.`id`)\n LEFT JOIN `glpi_entities`\n ON (`glpi_documents`.`entities_id`=`glpi_entities`.`id`)\n LEFT JOIN `glpi_documentcategories`\n ON (`glpi_documents`.`documentcategories_id`=`glpi_documentcategories`.`id`)\n WHERE `glpi_documents_items`.`documents_id` = '{$ID}'\n AND `glpi_documents_items`.`itemtype` = '" . $item->getType() . "' "; if (Session::getLoginUserID()) { $query .= getEntitiesRestrictRequest(" AND", "glpi_documents", '', '', true); } else { // Anonymous access from FAQ $query .= " AND `glpi_documents`.`entities_id`='0' "; } } $query .= " ORDER BY {$sort} {$order}"; $result = $DB->query($query); $number = $DB->numrows($result); $i = 0; $documents = array(); $used = array(); if ($numrows = $DB->numrows($result)) { while ($data = $DB->fetch_assoc($result)) { $documents[$data['assocID']] = $data; $used[$data['id']] = $data['id']; } } if ($item->canAddItem('Document') && $withtemplate < 2) { // Restrict entity for knowbase $entities = ""; $entity = $_SESSION["glpiactive_entity"]; if ($item->isEntityAssign()) { /// Case of personal items : entity = -1 : create on active entity (Reminder case)) if ($item->getEntityID() >= 0) { $entity = $item->getEntityID(); } if ($item->isRecursive()) { $entities = getSonsOf('glpi_entities', $entity); } else { $entities = $entity; } } $limit = getEntitiesRestrictRequest(" AND ", "glpi_documents", '', $entities, true); $q = "SELECT COUNT(*)\n FROM `glpi_documents`\n WHERE `is_deleted` = '0'\n {$limit}"; $result = $DB->query($q); $nb = $DB->result($result, 0, 0); if ($item->getType() == 'Document') { $used[$ID] = $ID; } echo "<div class='firstbloc'>"; echo "<form name='documentitem_form{$rand}' id='documentitem_form{$rand}' method='post'\n action='" . Toolbox::getItemTypeFormURL('Document') . "' enctype=\"multipart/form-data\">"; echo "<table class='tab_cadre_fixe'>"; echo "<tr class='tab_bg_2'><th colspan='5'>" . __('Add a document') . "</th></tr>"; echo "<tr class='tab_bg_1'>"; echo "<td class='center'>"; _e('Heading'); echo "</td><td width='20%'>"; DocumentCategory::dropdown(array('entity' => $entities)); echo "</td>"; echo "<td class='right'>"; echo "<input type='hidden' name='entities_id' value='{$entity}'>"; echo "<input type='hidden' name='is_recursive' value='{$is_recursive}'>"; echo "<input type='hidden' name='itemtype' value='" . $item->getType() . "'>"; echo "<input type='hidden' name='items_id' value='{$ID}'>"; if ($item->getType() == 'Ticket') { echo "<input type='hidden' name='tickets_id' value='{$ID}'>"; } echo Html::file(); echo "</td><td class='left'>"; echo "(" . Document::getMaxUploadSize() . ") "; echo "</td>"; echo "<td class='center' width='20%'>"; echo "<input type='submit' name='add' value=\"" . _sx('button', 'Add a new file') . "\"\n class='submit'>"; echo "</td></tr>"; echo "</table>"; Html::closeForm(); if (Document::canView() && $nb > count($used)) { echo "<form name='document_form{$rand}' id='document_form{$rand}' method='post'\n action='" . Toolbox::getItemTypeFormURL(__CLASS__) . "'>"; echo "<table class='tab_cadre_fixe'>"; echo "<tr class='tab_bg_1'>"; echo "<td colspan='4' class='center'>"; echo "<input type='hidden' name='itemtype' value='" . $item->getType() . "'>"; echo "<input type='hidden' name='items_id' value='{$ID}'>"; if ($item->getType() == 'Ticket') { echo "<input type='hidden' name='tickets_id' value='{$ID}'>"; echo "<input type='hidden' name='documentcategories_id' value='" . $CFG_GLPI["documentcategories_id_forticket"] . "'>"; } Document::dropdown(array('entity' => $entities, 'used' => $used)); echo "</td><td class='center' width='20%'>"; echo "<input type='submit' name='add' value=\"" . _sx('button', 'Associate an existing document') . "\" class='submit'>"; echo "</td>"; echo "</tr>"; echo "</table>"; Html::closeForm(); } echo "</div>"; } echo "<div class='spaced'>"; if ($canedit && $number && $withtemplate < 2) { Html::openMassiveActionsForm('mass' . __CLASS__ . $rand); $massiveactionparams = array('num_displayed' => $number, 'container' => 'mass' . __CLASS__ . $rand); Html::showMassiveActions($massiveactionparams); } $sort_img = "<img src=\"" . $CFG_GLPI["root_doc"] . "/pics/" . ($order == "DESC" ? "puce-down.png" : "puce-up.png") . "\" alt='' title=''>"; echo "<table class='tab_cadre_fixehov table-striped table-hover'>"; $header_begin = "<tr>"; $header_top = ''; $header_bottom = ''; $header_end = ''; if ($canedit && $number && $withtemplate < 2) { $header_top .= "<th width='11'>" . Html::getCheckAllAsCheckbox('mass' . __CLASS__ . $rand); $header_top .= "</th>"; $header_bottom .= "<th width='11'>" . Html::getCheckAllAsCheckbox('mass' . __CLASS__ . $rand); $header_bottom .= "</th>"; } foreach ($columns as $key => $val) { $header_end .= "<th>" . ($sort == "`{$key}`" ? $sort_img : "") . "<a href='javascript:reloadTab(\"sort={$key}&order=" . ($order == "ASC" ? "DESC" : "ASC") . "&start=0\");'>{$val}</a></th>"; } $header_end .= "</tr>"; echo $header_begin . $header_top . $header_end; $used = array(); if ($number) { // Don't use this for document associated to document // To not loose navigation list for current document if ($item->getType() != 'Document') { Session::initNavigateListItems('Document', sprintf(__('%1$s = %2$s'), $item->getTypeName(1), $item->getName())); } $document = new Document(); foreach ($documents as $data) { $docID = $data["id"]; $link = NOT_AVAILABLE; $downloadlink = NOT_AVAILABLE; if ($document->getFromDB($docID)) { $link = $document->getLink(); $downloadlink = $document->getDownloadLink($linkparam); } if ($item->getType() != 'Document') { Session::addToNavigateListItems('Document', $docID); } $used[$docID] = $docID; $assocID = $data["assocID"]; echo "<tr class='tab_bg_1" . ($data["is_deleted"] ? "_2" : "") . "'>"; if ($canedit && $withtemplate < 2) { echo "<td width='10'>"; Html::showMassiveActionCheckBox(__CLASS__, $data["assocID"]); echo "</td>"; } echo "<td class='center'>{$link}</td>"; echo "<td class='center'>" . $data['entity'] . "</td>"; echo "<td class='center'>{$downloadlink}</td>"; echo "<td class='center'>"; if (!empty($data["link"])) { echo "<a target=_blank href='" . formatOutputWebLink($data["link"]) . "'>" . $data["link"]; echo "</a>"; } else { echo " "; } echo "</td>"; echo "<td class='center'>" . Dropdown::getDropdownName("glpi_documentcategories", $data["documentcategories_id"]); echo "</td>"; echo "<td class='center'>" . $data["mime"] . "</td>"; if ($CFG_GLPI['use_rich_text']) { echo "<td class='center'>"; echo !empty($data["tag"]) ? Document::getImageTag($data["tag"]) : ''; echo "</td>"; } echo "<td class='center'>" . Html::convDateTime($data["assocdate"]) . "</td>"; echo "</tr>"; $i++; } echo $header_begin . $header_bottom . $header_end; } echo "</table>"; if ($canedit && $number && $withtemplate < 2) { $massiveactionparams['ontop'] = false; Html::showMassiveActions($massiveactionparams); Html::closeForm(); } echo "</div>"; }
function dropdownTaskItems($ID, $name, $used = array()) { global $DB, $CFG_GLPI; $restrict = "`plugin_projet_projets_id` = '{$ID}'"; $items = getAllDatasFromTable("glpi_plugin_projet_projets_items", $restrict); $restrictdoc = "`items_id` = '{$ID}' AND `itemtype` = 'PluginProjetProjet'"; $docs = getAllDatasFromTable("glpi_documents_items", $restrictdoc); $restrictcontract = "`items_id` = '{$ID}' AND `itemtype` = 'PluginProjetProjet'"; $contracts = getAllDatasFromTable("glpi_contracts_items", $restrictcontract); echo "<select name='{$name}'>"; echo "<option value='0' selected>" . Dropdown::EMPTY_VALUE . "</option>"; if (!empty($items)) { foreach ($items as $item) { $table = getTableForItemType($item["itemtype"]); $query = "SELECT `" . $table . "`.*\n FROM `glpi_plugin_projet_projets_items`\n INNER JOIN `" . $table . "` ON (`" . $table . "`.`id` = `glpi_plugin_projet_projets_items`.`items_id`)\n WHERE `glpi_plugin_projet_projets_items`.`itemtype` = '" . $item["itemtype"] . "'\n AND `glpi_plugin_projet_projets_items`.`items_id` = '" . $item["items_id"] . "' "; if (count($used)) { $query .= " AND `" . $table . "`.`id` NOT IN (0"; foreach ($used as $ID) { $query .= ",{$ID}"; } $query .= ")"; } $query .= " GROUP BY `" . $table . "`.`name`"; $query .= " ORDER BY `" . $table . "`.`name`"; $result_linked = $DB->query($query); if ($DB->numrows($result_linked)) { while ($data = $DB->fetch_assoc($result_linked)) { $name = $data["name"]; $itemclass = new $item["itemtype"](); if ($item["itemtype"] == 'User') { $name = getUserName($data["id"]); } echo "<option value='" . $data["id"] . "," . $item["itemtype"] . "'>" . $itemclass->getTypeName() . " - " . $name; if (empty($data["name"]) || $_SESSION["glpiis_ids_visible"] == 1) { echo " ("; echo $data["id"] . ")"; } echo "</option>"; } } } } if (!empty($docs)) { foreach ($docs as $doc) { $docclass = new Document(); if ($docclass->getFromDB($doc["documents_id"])) { $name = $docclass->fields["name"]; echo "<option value='" . $doc["documents_id"] . ",Document'>" . $docclass->getTypeName() . " - " . $name; if (empty($name) || $_SESSION["glpiis_ids_visible"] == 1) { echo " ("; echo $doc["documents_id"] . ")"; } echo "</option>"; } } } if (!empty($contracts)) { foreach ($contracts as $contract) { $contractclass = new Contract(); if ($contractclass->getFromDB($contract["contracts_id"])) { $name = $contractclass->fields["name"]; echo "<option value='" . $contract["contracts_id"] . ",Contract'>" . $contractclass->getTypeName() . " - " . $name; if (empty($name) || $_SESSION["glpiis_ids_visible"] == 1) { echo " ("; echo $contract["contracts_id"] . ")"; } echo "</option>"; } } } echo "</select>"; }
/** * Print the wainting ticket form * * @param $ID integer ID of the item * @param $options array * - target filename : where to go when done. * - withtemplate boolean : template or basic item * * @return Nothing (display) * */ static function showList($item, $canedit) { global $CFG_GLPI; // validation des droits if (!self::canView()) { return false; } if (isset($_REQUEST["start"])) { $start = $_REQUEST["start"]; } else { $start = 0; } $rand = mt_rand(); // Get close informations $data = self::getCloseTicketFromDB($item->getField('id'), array('start' => $start, 'limit' => $_SESSION['glpilist_limit'])); if (!count($data)) { echo "<div class='center'>"; echo "<table class='tab_cadre_fixe'>"; echo "<tr><th>" . __('No historical') . "</th></tr>"; echo "</table>"; echo "</div><br>"; } else { $doc = new Document(); echo "<div class='center'>"; // Display the pager Html::printAjaxPager(__('Close ticket informations', 'moreticket'), $start, count($data)); if ($canedit) { Html::openMassiveActionsForm('mass' . __CLASS__ . $rand); $massiveactionparams = array('item' => __CLASS__, 'container' => 'mass' . __CLASS__ . $rand); Html::showMassiveActions($massiveactionparams); } echo "<table class='tab_cadre_fixe'>"; echo "<tr>"; echo "<th width='10'>"; if ($canedit) { echo Html::getCheckAllAsCheckbox('mass' . __CLASS__ . $rand); } echo "</th>"; echo "<th>" . __('Date') . "</th>"; echo "<th>" . __('Comments') . "</th>"; echo "<th>" . __('Writer') . "</th>"; echo "<th>" . __('Document') . "</th>"; echo "</tr>"; foreach ($data as $closeTicket) { echo "<tr class='tab_bg_2'>"; echo "<td width='10'>"; if ($canedit) { Html::showMassiveActionCheckBox(__CLASS__, $closeTicket['id']); } echo "</td>"; echo "<td>"; echo Html::convDateTime($closeTicket['date']); echo "</td>"; echo "<td>"; echo $closeTicket['comment']; echo "</td>"; echo "<td>"; echo getUserName($closeTicket['requesters_id']); echo "</td>"; echo "<td>"; if ($doc->getFromDB($closeTicket['documents_id'])) { echo $doc->getLink(); } echo "</td>"; echo "</tr>"; } if ($canedit) { $massiveactionparams['ontop'] = false; Html::showMassiveActions($massiveactionparams); Html::closeForm(); } echo "</table>"; echo "</div>"; Html::printAjaxPager(__('Close ticket informations', 'moreticket'), $start, count($data)); } }
/** * @since version 0.90 * * @param $item * @param $withtemplate (default '') * @param $options array */ static function showListForItem(CommonDBTM $item, $withtemplate = '', $options = array()) { global $DB, $CFG_GLPI; //default options $params['rand'] = mt_rand(); if (is_array($options) && count($options)) { foreach ($options as $key => $val) { $params[$key] = $val; } } $canedit = $item->canAddItem('Document') && Document::canView(); $columns = array('name' => __('Name'), 'entity' => __('Entity'), 'filename' => __('File'), 'link' => __('Web link'), 'headings' => __('Heading'), 'mime' => __('MIME type')); if ($CFG_GLPI['use_rich_text']) { $columns['tag'] = __('Tag'); } $columns['assocdate'] = __('Date'); if (isset($_GET["order"]) && $_GET["order"] == "ASC") { $order = "ASC"; } else { $order = "DESC"; } if (isset($_GET["sort"]) && !empty($_GET["sort"]) && isset($columns[$_GET["sort"]])) { $sort = "`" . $_GET["sort"] . "`"; } else { $sort = "`assocdate`"; } if (empty($withtemplate)) { $withtemplate = 0; } $linkparam = ''; if (get_class($item) == 'Ticket') { $linkparam = "&tickets_id=" . $item->fields['id']; } $query = "SELECT `glpi_documents_items`.`id` AS assocID,\n `glpi_documents_items`.`date_mod` AS assocdate,\n `glpi_entities`.`id` AS entityID,\n `glpi_entities`.`completename` AS entity,\n `glpi_documentcategories`.`completename` AS headings,\n `glpi_documents`.*\n FROM `glpi_documents_items`\n LEFT JOIN `glpi_documents`\n ON (`glpi_documents_items`.`documents_id`=`glpi_documents`.`id`)\n LEFT JOIN `glpi_entities` ON (`glpi_documents`.`entities_id`=`glpi_entities`.`id`)\n LEFT JOIN `glpi_documentcategories`\n ON (`glpi_documents`.`documentcategories_id`=`glpi_documentcategories`.`id`)\n WHERE `glpi_documents_items`.`items_id` = '" . $item->getID() . "'\n AND `glpi_documents_items`.`itemtype` = '" . $item->getType() . "' "; if (Session::getLoginUserID()) { $query .= getEntitiesRestrictRequest(" AND", "glpi_documents", '', '', true); } else { // Anonymous access from FAQ $query .= " AND `glpi_documents`.`entities_id`= '0' "; } // Document : search links in both order using union if ($item->getType() == 'Document') { $query .= "UNION\n SELECT `glpi_documents_items`.`id` AS assocID,\n `glpi_documents_items`.`date_mod` AS assocdate,\n `glpi_entities`.`id` AS entityID,\n `glpi_entities`.`completename` AS entity,\n `glpi_documentcategories`.`completename` AS headings,\n `glpi_documents`.*\n FROM `glpi_documents_items`\n LEFT JOIN `glpi_documents`\n ON (`glpi_documents_items`.`items_id`=`glpi_documents`.`id`)\n LEFT JOIN `glpi_entities`\n ON (`glpi_documents`.`entities_id`=`glpi_entities`.`id`)\n LEFT JOIN `glpi_documentcategories`\n ON (`glpi_documents`.`documentcategories_id`=`glpi_documentcategories`.`id`)\n WHERE `glpi_documents_items`.`documents_id` = '" . $item->getID() . "'\n AND `glpi_documents_items`.`itemtype` = '" . $item->getType() . "' "; if (Session::getLoginUserID()) { $query .= getEntitiesRestrictRequest(" AND", "glpi_documents", '', '', true); } else { // Anonymous access from FAQ $query .= " AND `glpi_documents`.`entities_id`='0' "; } } $query .= " ORDER BY {$sort} {$order}"; $result = $DB->query($query); $number = $DB->numrows($result); $i = 0; $documents = array(); $used = array(); if ($numrows = $DB->numrows($result)) { while ($data = $DB->fetch_assoc($result)) { $documents[$data['assocID']] = $data; $used[$data['id']] = $data['id']; } } echo "<div class='spaced'>"; if ($canedit && $number && $withtemplate < 2) { Html::openMassiveActionsForm('mass' . __CLASS__ . $params['rand']); $massiveactionparams = array('num_displayed' => $number, 'container' => 'mass' . __CLASS__ . $params['rand']); Html::showMassiveActions($massiveactionparams); } $sort_img = "<img src=\"" . $CFG_GLPI["root_doc"] . "/pics/" . ($order == "DESC" ? "puce-down.png" : "puce-up.png") . "\" alt='' title=''>"; echo "<table class='tab_cadre_fixehov'>"; $header_begin = "<tr>"; $header_top = ''; $header_bottom = ''; $header_end = ''; if ($canedit && $number && $withtemplate < 2) { $header_top .= "<th width='11'>" . Html::getCheckAllAsCheckbox('mass' . __CLASS__ . $params['rand']); $header_top .= "</th>"; $header_bottom .= "<th width='11'>" . Html::getCheckAllAsCheckbox('mass' . __CLASS__ . $params['rand']); $header_bottom .= "</th>"; } foreach ($columns as $key => $val) { $header_end .= "<th>" . ($sort == "`{$key}`" ? $sort_img : "") . "<a href='javascript:reloadTab(\"sort={$key}&order=" . ($order == "ASC" ? "DESC" : "ASC") . "&start=0\");'>{$val}</a></th>"; } $header_end .= "</tr>"; echo $header_begin . $header_top . $header_end; $used = array(); if ($number) { // Don't use this for document associated to document // To not loose navigation list for current document if ($item->getType() != 'Document') { Session::initNavigateListItems('Document', sprintf(__('%1$s = %2$s'), $item->getTypeName(1), $item->getName())); } $document = new Document(); foreach ($documents as $data) { $docID = $data["id"]; $link = NOT_AVAILABLE; $downloadlink = NOT_AVAILABLE; if ($document->getFromDB($docID)) { $link = $document->getLink(); $downloadlink = $document->getDownloadLink($linkparam); } if ($item->getType() != 'Document') { Session::addToNavigateListItems('Document', $docID); } $used[$docID] = $docID; $assocID = $data["assocID"]; echo "<tr class='tab_bg_1" . ($data["is_deleted"] ? "_2" : "") . "'>"; if ($canedit && $withtemplate < 2) { echo "<td width='10'>"; Html::showMassiveActionCheckBox(__CLASS__, $data["assocID"]); echo "</td>"; } echo "<td class='center'>{$link}</td>"; echo "<td class='center'>" . $data['entity'] . "</td>"; echo "<td class='center'>{$downloadlink}</td>"; echo "<td class='center'>"; if (!empty($data["link"])) { echo "<a target=_blank href='" . formatOutputWebLink($data["link"]) . "'>" . $data["link"]; echo "</a>"; } else { echo " "; } echo "</td>"; echo "<td class='center'>" . Dropdown::getDropdownName("glpi_documentcategories", $data["documentcategories_id"]); echo "</td>"; echo "<td class='center'>" . $data["mime"] . "</td>"; if ($CFG_GLPI['use_rich_text']) { echo "<td class='center'>"; echo !empty($data["tag"]) ? Document::getImageTag($data["tag"]) : ''; echo "</td>"; } echo "<td class='center'>" . Html::convDateTime($data["assocdate"]) . "</td>"; echo "</tr>"; $i++; } echo $header_begin . $header_bottom . $header_end; } echo "</table>"; if ($canedit && $number && $withtemplate < 2) { $massiveactionparams['ontop'] = false; Html::showMassiveActions($massiveactionparams); Html::closeForm(); } echo "</div>"; }
/** * Show documents associated to an item * * @since version 0.84 * * @param $item CommonDBTM object for which associated documents must be displayed * @param $withtemplate (default '') **/ static function showForItem(CommonDBTM $item, $withtemplate = '') { global $DB, $CFG_GLPI; $ID = $item->getField('id'); if ($item->isNewID($ID)) { return false; } if ($item->getType() != 'Ticket' && $item->getType() != 'KnowbaseItem' && !Session::haveRight('document', 'r')) { return false; } if (!$item->can($item->fields['id'], 'r')) { return false; } if (empty($withtemplate)) { $withtemplate = 0; } $linkparam = ''; if (get_class($item) == 'Ticket') { $linkparam = "&tickets_id=" . $item->fields['id']; } $canedit = $item->canadditem('Document'); $rand = mt_rand(); $is_recursive = $item->isRecursive(); $query = "SELECT `glpi_documents_items`.`id` AS assocID,\n `glpi_entities`.`id` AS entity,\n `glpi_documents`.`name` AS assocName,\n `glpi_documents`.*\n FROM `glpi_documents_items`\n LEFT JOIN `glpi_documents`\n ON (`glpi_documents_items`.`documents_id`=`glpi_documents`.`id`)\n LEFT JOIN `glpi_entities` ON (`glpi_documents`.`entities_id`=`glpi_entities`.`id`)\n WHERE `glpi_documents_items`.`items_id` = '{$ID}'\n AND `glpi_documents_items`.`itemtype` = '" . $item->getType() . "' "; if (Session::getLoginUserID()) { $query .= getEntitiesRestrictRequest(" AND", "glpi_documents", '', '', true); } else { // Anonymous access from FAQ $query .= " AND `glpi_documents`.`entities_id`= '0' "; } // Document : search links in both order using union if ($item->getType() == 'Document') { $query .= "UNION\n SELECT `glpi_documents_items`.`id` AS assocID,\n `glpi_entities`.`id` AS entity,\n `glpi_documents`.`name` AS assocName,\n `glpi_documents`.*\n FROM `glpi_documents_items`\n LEFT JOIN `glpi_documents`\n ON (`glpi_documents_items`.`items_id`=`glpi_documents`.`id`)\n LEFT JOIN `glpi_entities`\n ON (`glpi_documents`.`entities_id`=`glpi_entities`.`id`)\n WHERE `glpi_documents_items`.`documents_id` = '{$ID}'\n AND `glpi_documents_items`.`itemtype` = '" . $item->getType() . "' "; if (Session::getLoginUserID()) { $query .= getEntitiesRestrictRequest(" AND", "glpi_documents", '', '', true); } else { // Anonymous access from FAQ $query .= " AND `glpi_documents`.`entities_id`='0' "; } } $query .= " ORDER BY `assocName`"; $result = $DB->query($query); $number = $DB->numrows($result); $i = 0; $documents = array(); $used = array(); if ($numrows = $DB->numrows($result)) { while ($data = $DB->fetch_assoc($result)) { $documents[$data['assocID']] = $data; $used[$data['id']] = $data['id']; } } if ($canedit && $withtemplate < 2) { // Restrict entity for knowbase $entities = ""; $entity = $_SESSION["glpiactive_entity"]; if ($item->isEntityAssign()) { /// Case of personal items : entity = -1 : create on active entity (Reminder case)) if ($item->getEntityID() >= 0) { $entity = $item->getEntityID(); } if ($item->isRecursive()) { $entities = getSonsOf('glpi_entities', $entity); } else { $entities = $entity; } } $limit = getEntitiesRestrictRequest(" AND ", "glpi_documents", '', $entities, true); $q = "SELECT COUNT(*)\n FROM `glpi_documents`\n WHERE `is_deleted` = '0'\n {$limit}"; $result = $DB->query($q); $nb = $DB->result($result, 0, 0); if ($item->getType() == 'Document') { $used[$ID] = $ID; } echo "<div class='firstbloc'>"; echo "<form name='documentitem_form{$rand}' id='documentitem_form{$rand}' method='post'\n action='" . Toolbox::getItemTypeFormURL('Document') . "' enctype=\"multipart/form-data\">"; echo "<table class='tab_cadre_fixe'>"; echo "<tr class='tab_bg_2'><th colspan='5'>" . __('Add a document') . "</th></tr>"; echo "<tr class='tab_bg_1'>"; echo "<td class='center'>"; _e('Heading'); echo '</td><td>'; DocumentCategory::dropdown(array('entity' => $entities)); echo "</td>"; echo "<td class='right'>"; echo "<input type='hidden' name='entities_id' value='{$entity}'>"; echo "<input type='hidden' name='is_recursive' value='{$is_recursive}'>"; echo "<input type='hidden' name='itemtype' value='" . $item->getType() . "'>"; echo "<input type='hidden' name='items_id' value='{$ID}'>"; if ($item->getType() == 'Ticket') { echo "<input type='hidden' name='tickets_id' value='{$ID}'>"; } echo "<input type='file' name='filename' size='25'>"; echo "</td><td class='left'>"; echo "(" . Document::getMaxUploadSize() . ") "; echo "</td>"; echo "<td class='center' width='20%'>"; echo "<input type='submit' name='add' value=\"" . _sx('button', 'Add a new file') . "\"\n class='submit'>"; echo "</td></tr>"; echo "</table>"; Html::closeForm(); if (Session::haveRight('document', 'r') && $nb > count($used)) { echo "<form name='document_form{$rand}' id='document_form{$rand}' method='post'\n action='" . Toolbox::getItemTypeFormURL(__CLASS__) . "'>"; echo "<table class='tab_cadre_fixe'>"; echo "<tr class='tab_bg_1'>"; echo "<td colspan='4' class='center'>"; echo "<input type='hidden' name='entities_id' value='{$entity}'>"; echo "<input type='hidden' name='is_recursive' value='{$is_recursive}'>"; echo "<input type='hidden' name='itemtype' value='" . $item->getType() . "'>"; echo "<input type='hidden' name='items_id' value='{$ID}'>"; if ($item->getType() == 'Ticket') { echo "<input type='hidden' name='tickets_id' value='{$ID}'>"; echo "<input type='hidden' name='documentcategories_id' value='" . $CFG_GLPI["documentcategories_id_forticket"] . "'>"; } Document::dropdown(array('entity' => $entities, 'used' => $used)); echo "</td><td class='center' width='20%'>"; echo "<input type='submit' name='add' value=\"" . _sx('button', 'Associate an existing document') . "\" class='submit'>"; echo "</td>"; echo "</tr>"; echo "</table>"; Html::closeForm(); } echo "</div>"; } echo "<div class='spaced'>"; if ($canedit && $number && $withtemplate < 2) { Html::openMassiveActionsForm('mass' . __CLASS__ . $rand); $massiveactionparams = array('num_displayed' => $number); Html::showMassiveActions(__CLASS__, $massiveactionparams); } echo "<table class='tab_cadre_fixe'>"; echo "<tr>"; if ($canedit && $number && $withtemplate < 2) { echo "<th width='10'>" . Html::getCheckAllAsCheckbox('mass' . __CLASS__ . $rand) . "</th>"; } echo "<th>" . __('Name') . "</th>"; echo "<th>" . __('Entity') . "</th>"; echo "<th>" . __('File') . "</th>"; echo "<th>" . __('Web link') . "</th>"; echo "<th>" . __('Heading') . "</th>"; echo "<th>" . __('MIME type') . "</th>"; echo "</tr>"; $used = array(); if ($number) { // Don't use this for document associated to document // To not loose navigation list for current document if ($item->getType() != 'Document') { Session::initNavigateListItems('Document', sprintf(__('%1$s = %2$s'), $item->getTypeName(1), $item->getName())); } $document = new Document(); foreach ($documents as $data) { $docID = $data["id"]; $link = NOT_AVAILABLE; $downloadlink = NOT_AVAILABLE; if ($document->getFromDB($docID)) { $link = $document->getLink(); $downloadlink = $document->getDownloadLink($linkparam); } if ($item->getType() != 'Document') { Session::addToNavigateListItems('Document', $docID); } $used[$docID] = $docID; $assocID = $data["assocID"]; echo "<tr class='tab_bg_1" . ($data["is_deleted"] ? "_2" : "") . "'>"; if ($canedit && $withtemplate < 2) { echo "<td width='10'>"; Html::showMassiveActionCheckBox(__CLASS__, $data["assocID"]); echo "</td>"; } echo "<td class='center'>{$link}</td>"; echo "<td class='center'>" . Dropdown::getDropdownName("glpi_entities", $data['entity']); echo "</td>"; echo "<td class='center'>{$downloadlink}</td>"; echo "<td class='center'>"; if (!empty($data["link"])) { echo "<a target=_blank href='" . formatOutputWebLink($data["link"]) . "'>" . $data["link"]; echo "</a>"; } else { echo " "; } echo "</td>"; echo "<td class='center'>" . Dropdown::getDropdownName("glpi_documentcategories", $data["documentcategories_id"]); echo "</td>"; echo "<td class='center'>" . $data["mime"] . "</td>"; echo "</tr>"; $i++; } } echo "</table>"; if ($canedit && $number && $withtemplate < 2) { $massiveactionparams['ontop'] = false; Html::showMassiveActions(__CLASS__, $massiveactionparams); Html::closeForm(); } echo "</div>"; }
/** * Get a Document the authenticated user can view or anonymous (for public FAQ) * * @param $params array of options (document, ticket) * @param $protocol the commonication protocol used * * @return a hashtable **/ static function methodGetDocument($params, $protocol) { if (isset($params['help'])) { return array('document' => 'integer,mandatory', 'ticket' => 'interger,optional', 'id2name' => 'bool,optional', 'help' => 'bool,optional'); } // Allowed for anonymous user for public FAQ (right check in canViewFile) $doc = new Document(); // Option parameter ticket if (isset($params['ticket']) && !is_numeric($params['ticket'])) { return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', 'ticket=' . $params['ticket']); } $options = array(); if (isset($params['ticket'])) { $options['tickets_id'] = $params['ticket']; } // Mandatory parameter document if (!isset($params['document'])) { return self::Error($protocol, WEBSERVICES_ERROR_MISSINGPARAMETER, '', 'document'); } if (!is_numeric($params['document'])) { return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', 'document=' . $params['document']); } if (!$doc->getFromDB($params['document'])) { return self::Error($protocol, WEBSERVICES_ERROR_NOTFOUND); } if (!$doc->canViewFile($options)) { return self::Error($protocol, WEBSERVICES_ERROR_NOTALLOWED); } $resp = $doc->fields; $resp['base64'] = base64_encode(file_get_contents(GLPI_DOC_DIR . "/" . $doc->fields['filepath'])); if (isset($params['id2name'])) { $resp['users_name'] = Html::clean(getUserName($doc->fields['users_id'])); $resp['documentcategories_name'] = Html::clean(Dropdown::getDropdownName('glpi_documentcategories', $doc->fields['documentcategories_id'])); } return $resp; }
/** * Copy order documents into the newly generated item * @since 1.5.3 * @param unknown_type $itemtype * @param unknown_type $items_id * @param unknown_type $orders_id * @param unknown_type $entity */ public static function copyDocuments($itemtype, $items_id, $orders_id, $entity) { global $CFG_GLPI; $config = PluginOrderConfig::getConfig(); if ($config->canCopyDocuments() && in_array($itemtype, $CFG_GLPI["document_types"])) { $document = new Document(); foreach (getAllDatasFromTable('glpi_documents_items', "`itemtype`='PluginOrderOrder' AND `items_id`='{$orders_id}'") as $doc) { $document->getFromDB($doc['documents_id']); $newdocument = clone $document; $newdocument->fields['entities_id'] = $entity; $newdocument->fields['items_id'] = $items_id; $newdocument->fields['itemtype'] = $itemtype; unset($newdocument->fields['id']); $document->add($newdocument->fields); } } }
/** * @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; }
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 " "; 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> "; 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'> </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 " <a class='vsubmit' href='" . $this->getLinkURL() . "&forcetab=TicketFollowup\$1&_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 " <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 " <a href='" . $this->getFormURL() . "?id=" . $ID . "&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 . "&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 " "; 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') . "'> "; } } else { if (self::canUpdate()) { echo "<input type='submit' class='submit' name='update' value='" . _sx('button', 'Save') . "'> "; } } 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; }
function prepareInputForUpdate($input) { // Add document if needed $this->getFromDB($input["id"]); // entities_id field required if (!isset($input['_donotadddocs']) || !$input['_donotadddocs']) { $docadded = $this->addFiles(1, isset($input['_disablenotif']) ? $input['_disablenotif'] : 0); if (isset($this->input['_forcenotif'])) { $input['_forcenotif'] = $this->input['_forcenotif']; unset($input['_disablenotif']); } if (isset($this->input['content'])) { $input['content'] = $this->input['content']; } } if (isset($input["document"]) && $input["document"] > 0) { $doc = new Document(); if ($doc->getFromDB($input["document"])) { $docitem = new Document_Item(); if ($docitem->add(array('documents_id' => $input["document"], 'itemtype' => $this->getType(), 'items_id' => $input["id"]))) { // Force date_mod of tracking $input["date_mod"] = $_SESSION["glpi_currenttime"]; $input['_doc_added'][] = $doc->fields["name"]; } } unset($input["document"]); } if (isset($input["date"]) && empty($input["date"])) { unset($input["date"]); } if (isset($input["closedate"]) && empty($input["closedate"])) { unset($input["closedate"]); } if (isset($input["solvedate"]) && empty($input["solvedate"])) { unset($input["solvedate"]); } if (isset($input['_itil_requester'])) { if (isset($input['_itil_requester']['_type'])) { $input['_itil_requester']['type'] = CommonITILActor::REQUESTER; $input['_itil_requester'][$this->getForeignKeyField()] = $input['id']; switch ($input['_itil_requester']['_type']) { case "user": if (!empty($this->userlinkclass)) { if (isset($input['_itil_requester']['alternative_email']) && $input['_itil_requester']['alternative_email'] && !NotificationMail::isUserAddressValid($input['_itil_requester']['alternative_email'])) { $input['_itil_requester']['alternative_email'] = ''; Session::addMessageAfterRedirect(__('Invalid email address'), false, ERROR); } if (isset($input['_itil_requester']['alternative_email']) && $input['_itil_requester']['alternative_email'] || $input['_itil_requester']['users_id'] > 0) { $useractors = new $this->userlinkclass(); if (isset($input['_auto_update']) || $useractors->can(-1, CREATE, $input['_itil_requester'])) { $input['_itil_requester']['_from_object'] = true; $useractors->add($input['_itil_requester']); $input['_forcenotif'] = true; } } } break; case "group": if (!empty($this->grouplinkclass) && $input['_itil_requester']['groups_id'] > 0) { $groupactors = new $this->grouplinkclass(); if (isset($input['_auto_update']) || $groupactors->can(-1, CREATE, $input['_itil_requester'])) { $input['_itil_requester']['_from_object'] = true; $groupactors->add($input['_itil_requester']); $input['_forcenotif'] = true; } } break; } } } if (isset($input['_itil_observer'])) { if (isset($input['_itil_observer']['_type'])) { $input['_itil_observer']['type'] = CommonITILActor::OBSERVER; $input['_itil_observer'][$this->getForeignKeyField()] = $input['id']; switch ($input['_itil_observer']['_type']) { case "user": if (!empty($this->userlinkclass)) { if (isset($input['_itil_observer']['alternative_email']) && $input['_itil_observer']['alternative_email'] && !NotificationMail::isUserAddressValid($input['_itil_observer']['alternative_email'])) { $input['_itil_observer']['alternative_email'] = ''; Session::addMessageAfterRedirect(__('Invalid email address'), false, ERROR); } if (isset($input['_itil_observer']['alternative_email']) && $input['_itil_observer']['alternative_email'] || $input['_itil_observer']['users_id'] > 0) { $useractors = new $this->userlinkclass(); if (isset($input['_auto_update']) || $useractors->can(-1, CREATE, $input['_itil_observer'])) { $input['_itil_observer']['_from_object'] = true; $useractors->add($input['_itil_observer']); $input['_forcenotif'] = true; } } } break; case "group": if (!empty($this->grouplinkclass) && $input['_itil_observer']['groups_id'] > 0) { $groupactors = new $this->grouplinkclass(); if (isset($input['_auto_update']) || $groupactors->can(-1, CREATE, $input['_itil_observer'])) { $input['_itil_observer']['_from_object'] = true; $groupactors->add($input['_itil_observer']); $input['_forcenotif'] = true; } } break; } } } if (isset($input['_itil_assign'])) { if (isset($input['_itil_assign']['_type'])) { $input['_itil_assign']['type'] = CommonITILActor::ASSIGN; $input['_itil_assign'][$this->getForeignKeyField()] = $input['id']; switch ($input['_itil_assign']['_type']) { case "user": if (!empty($this->userlinkclass) && $input['_itil_assign']['users_id'] > 0) { $useractors = new $this->userlinkclass(); if (isset($input['_auto_update']) || $useractors->can(-1, CREATE, $input['_itil_assign'])) { $input['_itil_assign']['_from_object'] = true; $useractors->add($input['_itil_assign']); $input['_forcenotif'] = true; if (!isset($input['status']) && in_array($this->fields['status'], $this->getNewStatusArray()) || isset($input['status']) && in_array($input['status'], $this->getNewStatusArray())) { if (in_array(self::ASSIGNED, array_keys($this->getAllStatusArray()))) { $input['status'] = self::ASSIGNED; } } } } break; case "group": if (!empty($this->grouplinkclass) && $input['_itil_assign']['groups_id'] > 0) { $groupactors = new $this->grouplinkclass(); if (isset($input['_auto_update']) || $groupactors->can(-1, CREATE, $input['_itil_assign'])) { $input['_itil_assign']['_from_object'] = true; $groupactors->add($input['_itil_assign']); $input['_forcenotif'] = true; if (!isset($input['status']) && in_array($this->fields['status'], $this->getNewStatusArray()) || isset($input['status']) && in_array($input['status'], $this->getNewStatusArray())) { if (in_array(self::ASSIGNED, array_keys($this->getAllStatusArray()))) { $input['status'] = self::ASSIGNED; } } } } break; case "supplier": if (!empty($this->supplierlinkclass) && $input['_itil_assign']['suppliers_id'] > 0) { $supplieractors = new $this->supplierlinkclass(); if (isset($input['_auto_update']) || $supplieractors->can(-1, CREATE, $input['_itil_assign'])) { $input['_itil_assign']['_from_object'] = true; $supplieractors->add($input['_itil_assign']); $input['_forcenotif'] = true; if (!isset($input['status']) && in_array($this->fields['status'], $this->getNewStatusArray()) || isset($input['status']) && in_array($input['status'], $this->getNewStatusArray())) { if (in_array(self::ASSIGNED, array_keys($this->getAllStatusArray()))) { $input['status'] = self::ASSIGNED; } } } } break; } } } $this->addAdditionalActors($input); // set last updater if interactive user if (!Session::isCron()) { $input['users_id_lastupdater'] = Session::getLoginUserID(); } if (isset($input["status"]) && !in_array($input["status"], array_merge($this->getSolvedStatusArray(), $this->getClosedStatusArray()))) { $input['solvedate'] = 'NULL'; } if (isset($input["status"]) && !in_array($input["status"], $this->getClosedStatusArray())) { $input['closedate'] = 'NULL'; } return $input; }
/** * Show documents associated to an item * * @param $item CommonDBTM object for which associated documents must be displayed * @param $withtemplate **/ static function showAssociated(CommonDBTM $item, $withtemplate = '') { global $DB, $CFG_GLPI, $LANG; $ID = $item->getField('id'); if ($item->isNewID($ID)) { return false; } if ($item->getType() != 'Ticket' && $item->getType() != 'KnowbaseItem' && !haveRight('document', 'r')) { return false; } if (!$item->can($item->fields['id'], 'r')) { return false; } if (empty($withtemplate)) { $withtemplate = 0; } $linkparam = ''; if (get_class($item) == 'Ticket') { $linkparam = "&tickets_id=" . $item->fields['id']; } $canedit = $item->can($ID, 'w'); $is_recursive = $item->isRecursive(); $query = "SELECT `glpi_documents_items`.`id` AS assocID,\n `glpi_entities`.`id` AS entity,\n `glpi_documents`.`name` AS assocName,\n `glpi_documents`.*\n FROM `glpi_documents_items`\n LEFT JOIN `glpi_documents`\n ON (`glpi_documents_items`.`documents_id`=`glpi_documents`.`id`)\n LEFT JOIN `glpi_entities` ON (`glpi_documents`.`entities_id`=`glpi_entities`.`id`)\n WHERE `glpi_documents_items`.`items_id` = '{$ID}'\n AND `glpi_documents_items`.`itemtype` = '" . $item->getType() . "' "; if (getLoginUserID()) { $query .= getEntitiesRestrictRequest(" AND", "glpi_documents", '', '', true); } else { // Anonymous access from FAQ $query .= " AND `glpi_documents`.`entities_id`= '0' "; } // Document : search links in both order using union if ($item->getType() == 'Document') { $query .= "UNION\n SELECT `glpi_documents_items`.`id` AS assocID,\n `glpi_entities`.`id` AS entity,\n `glpi_documents`.`name` AS assocName,\n `glpi_documents`.*\n FROM `glpi_documents_items`\n LEFT JOIN `glpi_documents`\n ON (`glpi_documents_items`.`items_id`=`glpi_documents`.`id`)\n LEFT JOIN `glpi_entities`\n ON (`glpi_documents`.`entities_id`=`glpi_entities`.`id`)\n WHERE `glpi_documents_items`.`documents_id` = '{$ID}'\n AND `glpi_documents_items`.`itemtype` = '" . $item->getType() . "' "; if (getLoginUserID()) { $query .= getEntitiesRestrictRequest(" AND", "glpi_documents", '', '', true); } else { // Anonymous access from FAQ $query .= " AND `glpi_documents`.`entities_id`='0' "; } } $query .= " ORDER BY `assocName`"; $result = $DB->query($query); $number = $DB->numrows($result); $i = 0; if ($withtemplate != 2) { echo "<form method='post' action=\"" . $CFG_GLPI["root_doc"] . "/front/document.form.php\" enctype=\"multipart/form-data\">"; } echo "<div class='spaced'><table class='tab_cadre_fixe'>"; echo "<tr><th colspan='7'>"; if ($DB->numrows($result) == 0) { echo $LANG['document'][17]; } else { if ($DB->numrows($result) == 1) { echo $LANG['document'][21]; } else { echo $LANG['document'][20]; } } echo "</th></tr>"; echo "<tr><th>" . $LANG['common'][16] . "</th>"; echo "<th>" . $LANG['entity'][0] . "</th>"; echo "<th>" . $LANG['document'][2] . "</th>"; echo "<th>" . $LANG['document'][33] . "</th>"; echo "<th>" . $LANG['document'][3] . "</th>"; echo "<th>" . $LANG['document'][4] . "</th>"; if ($withtemplate < 2) { echo "<th> </th>"; } echo "</tr>"; $used = array(); if ($number) { // Don't use this for document associated to document // To not loose navigation list for current document if ($item->getType() != 'Document') { initNavigateListItems('Document', $item->getTypeName() . " = " . $item->getName()); } $document = new Document(); while ($data = $DB->fetch_assoc($result)) { $docID = $data["id"]; $link = NOT_AVAILABLE; $downloadlink = NOT_AVAILABLE; if ($document->getFromDB($docID)) { $link = $document->getLink(); $downloadlink = $document->getDownloadLink($linkparam); } if ($item->getType() != 'Document') { addToNavigateListItems('Document', $docID); } $used[$docID] = $docID; $assocID = $data["assocID"]; echo "<tr class='tab_bg_1" . ($data["is_deleted"] ? "_2" : "") . "'>"; echo "<td class='center'>{$link}</td>"; echo "<td class='center'>" . Dropdown::getDropdownName("glpi_entities", $data['entity']); echo "</td>"; echo "<td class='center'>{$downloadlink}</td>"; echo "<td class='center'>"; if (!empty($data["link"])) { echo "<a target=_blank href='" . formatOutputWebLink($data["link"]) . "'>" . $data["link"]; echo "</a>"; } else { echo " "; } echo "</td>"; echo "<td class='center'>" . Dropdown::getDropdownName("glpi_documentcategories", $data["documentcategories_id"]); echo "</td>"; echo "<td class='center'>" . $data["mime"] . "</td>"; if ($withtemplate < 2) { echo "<td class='tab_bg_2 center b'>"; if ($canedit && $_SESSION["glpiactiveprofile"]["interface"] != 'helpdesk') { echo "<a href='" . $CFG_GLPI["root_doc"]; echo "/front/document.form.php?deletedocumentitem=1&id={$assocID}"; echo "&itemtype=" . $item->getType() . "&items_id={$ID}&documents_id={$docID}'>"; echo $LANG['buttons'][6] . "</a>"; } else { echo " "; } echo "</td>"; } echo "</tr>"; $i++; } } if ($canedit) { // hack for ticket || get_class($item)=='Ticket') { // Restrict entity for knowbase $entities = ""; $entity = $_SESSION["glpiactive_entity"]; if ($item->isEntityAssign()) { $entity = $item->getEntityID(); if ($item->isRecursive()) { $entities = getSonsOf('glpi_entities', $entity); } else { $entities = $entity; } } if ($withtemplate < 2) { $limit = getEntitiesRestrictRequest(" AND ", "glpi_documents", '', $entities, true); $q = "SELECT count(*)\n FROM `glpi_documents`\n WHERE `is_deleted` = '0'\n {$limit}"; $result = $DB->query($q); $nb = $DB->result($result, 0, 0); echo "<tr class='tab_bg_1'><td class='center' colspan='3'>"; echo "<input type='hidden' name='entities_id' value='{$entity}'>"; echo "<input type='hidden' name='is_recursive' value='{$is_recursive}'>"; echo "<input type='hidden' name='itemtype' value='" . $item->getType() . "'>"; echo "<input type='hidden' name='items_id' value='{$ID}'>"; if ($item->getType() == 'Ticket') { echo "<input type='hidden' name='documentcategories_id' value='" . $CFG_GLPI["documentcategories_id_forticket"] . "'>"; echo "<input type='hidden' name='tickets_id' value='{$ID}'>"; } echo "<input type='file' name='filename' size='25'> "; echo "(" . self::getMaxUploadSize() . ") "; echo "<input type='submit' name='add' value=\"" . $LANG['buttons'][8] . "\" class='submit'>"; echo "</td>"; if ($item->getType() == 'Document') { $used[$ID] = $ID; } if (haveRight('document', 'r') && $nb > count($used)) { echo "<td class='left' colspan='2'>"; self::dropdown(array('entity' => $entities, 'used' => $used)); echo "</td><td class='center'>"; echo "<input type='submit' name='adddocumentitem' value=\"" . $LANG['buttons'][8] . "\" class='submit'>"; echo "</td><td> </td>"; } else { echo "<td colspan='4'> </td>"; } echo "</tr>"; } } echo "</table></form></div>"; }
/** * Transfer documents * * @param $itemtype original type of transfered item * @param $ID original ID of the document * @param $newID new ID of the document **/ function transferDocuments($itemtype, $ID, $newID) { global $DB; $need_clean_process = false; // if keep if ($this->options['keep_document']) { $document = new Document(); // Get contracts for the item $query = "SELECT *\n FROM `glpi_documents_items`\n WHERE `items_id` = '{$ID}'\n AND `itemtype` = '{$itemtype}'\n AND `documents_id` NOT IN " . $this->item_recurs['Document']; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { // Foreach get item while ($data = $DB->fetch_array($result)) { $need_clean_process = false; $item_ID = $data['documents_id']; $newdocID = -1; // is already transfer ? if (isset($this->already_transfer['Document'][$item_ID])) { $newdocID = $this->already_transfer['Document'][$item_ID]; if ($newdocID != $item_ID) { $need_clean_process = true; } } else { // No // Can be transfer without copy ? = all linked items need to be transfer (so not copy) $canbetransfer = true; $query = "SELECT DISTINCT `itemtype`\n FROM `glpi_documents_items`\n WHERE `documents_id` = '{$item_ID}'"; if ($result_type = $DB->query($query)) { if ($DB->numrows($result_type) > 0) { while (($data_type = $DB->fetch_array($result_type)) && $canbetransfer) { $dtype = $data_type['itemtype']; if (isset($this->item_search[$dtype])) { // No items to transfer -> exists links $query_search = "SELECT count(*) AS CPT\n FROM `glpi_documents_items`\n WHERE `documents_id` = '{$item_ID}'\n AND `itemtype` = '{$dtype}'\n AND `items_id`\n NOT IN " . $this->item_search[$dtype]; // contacts, contracts, and enterprises are linked as device. if (isset($this->item_recurs[$dtype])) { $query_search .= " AND `items_id`\n NOT IN " . $this->item_recurs[$dtype]; } $result_search = $DB->query($query_search); if ($DB->result($result_search, 0, 'CPT') > 0) { $canbetransfer = false; } } } } } // Yes : transfer if ($canbetransfer) { $this->transferItem('Document', $item_ID, $item_ID); $newdocID = $item_ID; } else { $need_clean_process = true; $document->getFromDB($item_ID); // No : search contract $query = "SELECT *\n FROM `glpi_documents`\n WHERE `entities_id` = '" . $this->to . "'\n AND `name` = '" . addslashes($document->fields['name']) . "'"; if ($result_search = $DB->query($query)) { if ($DB->numrows($result_search) > 0) { $newdocID = $DB->result($result_search, 0, 'id'); $this->addToAlreadyTransfer('Document', $item_ID, $newdocID); } } // found : use it // not found : copy doc if ($newdocID < 0) { // 1 - create new item unset($document->fields['id']); $input = $document->fields; // Not set new entity Do by transferItem unset($document->fields); $newdocID = $document->add($input); // 2 - transfer as copy $this->transferItem('Document', $item_ID, $newdocID); } } } // Update links if ($ID == $newID) { if ($item_ID != $newdocID) { $query = "UPDATE `glpi_documents_items`\n SET `documents_id` = '{$newdocID}'\n WHERE `id` = '" . $data['id'] . "'"; $DB->query($query); } // Same Item -> update links } else { // Copy Item -> copy links if ($item_ID != $newdocID) { $query = "INSERT\n INTO `glpi_documents_items`\n (`documents_id`, `items_id`, `itemtype`)\n VALUES ('{$newdocID}','{$newID}','{$itemtype}')"; $DB->query($query); } else { // same doc for new item update link $query = "UPDATE\n `glpi_documents_items`\n SET `items_id` = '{$newID}'\n WHERE `id` = '" . $data['id'] . "'"; $DB->query($query); } } // If clean and unused -> if ($need_clean_process && $this->options['clean_document']) { $query = "SELECT COUNT(*) AS CPT\n FROM `glpi_documents_items`\n WHERE `documents_id` = '{$item_ID}'"; if ($result_remaining = $DB->query($query)) { if ($DB->result($result_remaining, 0, 'CPT') == 0) { if ($this->options['clean_document'] == 1) { $document->delete(array('id' => $item_ID)); } if ($this->options['clean_document'] == 2) { // purge $document->delete(array('id' => $item_ID), 1); } } } } } } } } else { // else unlink $query = "DELETE\n FROM `glpi_documents_items`\n WHERE `items_id` = '{$ID}'\n AND `itemtype` = '{$itemtype}'"; $DB->query($query); } }
static function showInstrucciontecnica($item, $instID, $itemtype) { global $DB, $CFG_GLPI; $objeto = $item->getType(); $appli = new $objeto(); $appli->getFromDB($item->fields['id']); //$canedit = $appli->can($appli->fields['id'],'w'); $canedit = $appli->canCreate(); //$canedit = Session::haveRight('update_ticket', 1); echo "<div class='center'>"; echo "<form name='form_pedido' id='form_pedido' method='post' action='../plugins/formcreator/front/instruccion.form.php'>"; echo "<table class='tab_cadre_fixe'>"; echo "<th colspan=2>" . __('Informacion del pedido', 'Informacion del pedido') . "</th>"; echo "<tr>"; echo "<th>" . __('Pedido de catalogo', 'Pedido de catalogo') . " :" . "</th>"; echo "<td>"; if ($canedit) { //Dropdown::show('PluginFormcreatorForm', array('name' => 'peticion_id', // 'value' => $instID)); $table = getTableForItemtype('PluginFormcreatorForm'); $sections = array(); $sql = "SELECT `id`, `name`\n\t\t\t\t\t\t\tFROM {$table}\n\t\t\t\t\t\t\tORDER BY `name`"; $result = $GLOBALS['DB']->query($sql); while ($section = $GLOBALS['DB']->fetch_array($result)) { $sections[$section['id']] = $section['name']; } $sections = array("0" => "----") + $sections; Dropdown::showFromArray('peticion_id', $sections, array('value' => $instID)); } else { echo Dropdown::getDropdownName("glpi_plugin_formcreator_forms", $instID); } echo "</td>"; //----------------------------- echo "</tr>"; echo "<tr class='tab_bg_1'>"; echo "<td colspan='2' align = 'center'>"; echo "<input type='submit' name='actualizarPedido' value='Actualizar' class='submit'>"; echo "</td></tr>"; echo "</table>"; echo "<input type='hidden' name='itemtype' value='" . $item->getType() . "'>"; echo "<input type='hidden' name='tickets_id' value='" . $item->fields['id'] . "'>"; //echo "</form>"; Html::closeForm(); echo "</div>"; echo "<div class='center'>"; echo "<table class='tab_cadre_fixehov'>"; $query = "SELECT DISTINCT `itemtype`\n\t\t\t\t\tFROM `glpi_documents_items`\n\t\t\t\t\tWHERE `items_id` = '{$instID}' AND `itemtype` = '{$itemtype}'\n\t\t\t\t\tORDER BY `itemtype`"; $result = $DB->query($query); $number = $DB->numrows($result); $i = 0; if (Session::isMultiEntitiesMode()) { $colsup = 1; } else { $colsup = 0; } if ($number > 0) { echo "<tr><th>" . __('Heading') . "</th>"; echo "<th>" . __('Name') . "</th>"; echo "<th>" . __('Web link') . "</th>"; echo "<th>" . __('File') . "</th>"; echo "<th>" . __('Entity') . "</th>"; echo "</tr>"; } for ($i = 0; $i < $number; $i++) { $type = $DB->result($result, $i, "itemtype"); if (!class_exists($type)) { continue; } $item = new $type(); if ($canedit) { //if ($item->canView()) { $column = "name"; $query1 = "SELECT glpi_documents.*, glpi_documents_items.id AS IDD, glpi_entities.id AS entity\n\t\t\t\tFROM glpi_documents_items, glpi_documents LEFT JOIN glpi_entities ON (glpi_entities.id = glpi_documents.entities_id)\n\t\t\t\tWHERE glpi_documents.id = glpi_documents_items.documents_id\n\t\t\t\t\tAND glpi_documents_items.itemtype = '" . $itemtype . "'\n\t\t\t\t\tAND glpi_documents_items.items_id = " . $instID . "\n\t\t\t\t\tAND glpi_documents.is_deleted = 0\n\t\t\t\tORDER BY glpi_entities.completename, glpi_documents.name"; if ($result_linked1 = $DB->query($query1)) { if ($DB->numrows($result_linked1)) { $document = new Document(); while ($data = $DB->fetch_assoc($result_linked1)) { $item->getFromDB($data["id"]); Session::addToNavigateListItems($type, $data["id"]); $ID = ""; $downloadlink = NOT_AVAILABLE; if ($document->getFromDB($data["id"])) { $downloadlink = $document->getDownloadLink(); } if ($_SESSION["glpiis_ids_visible"] || empty($data["name"])) { $ID = " (" . $data["id"] . ")"; } $name = __('Informacion de pedido', 'Informacion de pedido'); //item->getLink(); echo "<tr class='tab_bg_1'>"; // echo "<td class='center'>".$name."</td>"; echo "<td class='center'>" . Dropdown::getDropdownName("glpi_documentcategories", $data["documentcategories_id"]); echo "</td>"; $nombre = $data['name']; echo "<td class='center' " . (isset($data['deleted']) && $data['deleted'] ? "class='tab_bg_2_2'" : "") . ">" . $nombre . "</td>"; echo "<td class='center'>"; if (!empty($data["link"])) { echo "<a target=_blank href='" . formatOutputWebLink($data["link"]) . "'>" . $data["link"]; echo "</a>"; } else { echo " "; } echo "</td>"; echo "<td class='center'>{$downloadlink}</td>"; if (Session::isMultiEntitiesMode()) { echo "<td class='center'>" . Dropdown::getDropdownName("glpi_entities", $data['entity']) . "</td>"; } echo "</tr>"; } } } } } echo "</table>"; echo "</div>"; }