/** * Displays tab content * This function adapted from Search::showGenericSearch with controls removed * @param bool $formcontrol : display form buttons * @return nothing, displays a seach form */ static function showCriteria(PluginFusioninventoryDeployGroup $item, $formcontrol = true, $p) { global $CFG_GLPI, $DB; $is_dynamic = $item->isDynamicGroup(); $itemtype = "PluginFusioninventoryComputer"; $can_update = $item->canEdit($item->getID()); if ($can_update) { //show generic search form (duplicated from Search class) echo "<form name='group_search_form' method='POST'>"; echo "<input type='hidden' name='plugin_fusioninventory_deploygroups_id' value='" . $item->getID() . "'>"; echo "<input type='hidden' name='id' value='" . $item->getID() . "'>"; // add tow hidden fields to permit delete of (meta)criteria echo "<input type='hidden' name='criteria' value=''>"; echo "<input type='hidden' name='metacriteria' value=''>"; } echo "<div class='tabs_criteria'>"; echo "<table class='tab_cadre_fixe'>"; echo "<tr><th>" . _n('Criterion', 'Criteria', 2) . "</th></tr>"; echo "<tr><td>"; echo "<div id='searchcriteria'>"; $nb_criteria = count($p['criteria']); if ($nb_criteria == 0) { $nb_criteria++; } $nb_meta_criteria = isset($p['metacriteria']) ? count($p['metacriteria']) : 0; $nbsearchcountvar = 'nbcriteria' . strtolower($itemtype) . mt_rand(); $nbmetasearchcountvar = 'nbmetacriteria' . strtolower($itemtype) . mt_rand(); $searchcriteriatableid = 'criteriatable' . strtolower($itemtype) . mt_rand(); // init criteria count $js = "var {$nbsearchcountvar}=" . $nb_criteria . ";"; $js .= "var {$nbmetasearchcountvar}=" . $nb_meta_criteria . ";"; echo Html::scriptBlock($js); echo "<table class='tab_format' id='{$searchcriteriatableid}'>"; // Displays normal search parameters for ($i = 0; $i < $nb_criteria; $i++) { $_POST['itemtype'] = $itemtype; $_POST['num'] = $i; include GLPI_ROOT . '/ajax/searchrow.php'; } $metanames = array(); $linked = Search::getMetaItemtypeAvailable('Computer'); if (is_array($linked) && count($linked) > 0) { for ($i = 0; $i < $nb_meta_criteria; $i++) { $_POST['itemtype'] = $itemtype; $_POST['num'] = $i; include GLPI_ROOT . '/ajax/searchmetarow.php'; } } echo "</table>\n"; echo "</td>"; echo "</tr>"; echo "</table>\n"; // For dropdown echo "<input type='hidden' name='itemtype' value='{$itemtype}'>"; if ($can_update) { // add new button to search form (to store and preview) echo "<div class='center'>"; if ($is_dynamic) { echo "<input type='submit' value=\" " . _sx('button', 'Save') . " \" class='submit' name='save'>"; } else { echo "<input type='submit' value=\" " . __('Preview') . " \" class='submit' name='preview'>"; } echo "</div>"; } echo "</td></tr></table>"; echo "</div>"; //restore search session variables //$_SESSION['glpisearch'] = $glpisearch_session; // Reset to start when submit new search echo "<input type='hidden' name='start' value='0'>"; Html::closeForm(); //clean with javascript search control /* $clean_script = "jQuery( document ).ready(function( $ ) { $('#parent_criteria img').remove(); $('.tabs_criteria img[name=img_deleted').remove(); });"; echo Html::scriptBlock($clean_script);*/ }
/** * Print generic search form * * Params need to parsed before using Search::manageParams function * * @param $itemtype type to display the form * @param $params array of parameters may include sort, is_deleted, criteria, metacriteria * * @return nothing (displays) **/ static function showGenericSearch($itemtype, array $params) { global $CFG_GLPI; // Default values of parameters $p['sort'] = ''; $p['is_deleted'] = 0; $p['criteria'] = array(); $p['metacriteria'] = array(); if (class_exists($itemtype)) { $p['target'] = $itemtype::getSearchURL(); } else { $p['target'] = Toolbox::getItemTypeSearchURL($itemtype); } $p['showreset'] = true; $p['showbookmark'] = true; $p['addhidden'] = array(); $p['actionname'] = 'search'; $p['actionvalue'] = _sx('button', 'Search'); foreach ($params as $key => $val) { $p[$key] = $val; } echo "<form name='searchform{$itemtype}' method='get' action=\"" . $p['target'] . "\">"; echo "<div id='searchcriterias'>"; $nbsearchcountvar = 'nbcriteria' . strtolower($itemtype) . mt_rand(); $nbmetasearchcountvar = 'nbmetacriteria' . strtolower($itemtype) . mt_rand(); $searchcriteriatableid = 'criteriatable' . strtolower($itemtype) . mt_rand(); // init criteria count $js = "var {$nbsearchcountvar}=" . count($p['criteria']) . ";"; $js .= "var {$nbmetasearchcountvar}=" . count($p['metacriteria']) . ";"; echo Html::scriptBlock($js); echo "<table class='tab_cadre_fixe' >"; echo "<tr class='tab_bg_1'>"; if (count($p['criteria']) + count($p['metacriteria']) > 1) { echo "<td width='10' class='center'>"; echo "<a href=\"javascript:toggleTableDisplay('{$searchcriteriatableid}','searchcriteriasimg',\n '" . $CFG_GLPI["root_doc"] . "/pics/deplier_down.png',\n '" . $CFG_GLPI["root_doc"] . "/pics/deplier_up.png')\">"; echo "<img alt='' name='searchcriteriasimg' src=\"" . $CFG_GLPI["root_doc"] . "/pics/deplier_up.png\">"; echo "</td>"; } echo "<td>"; echo "<table class='tab_format' id='{$searchcriteriatableid}'>"; // Display normal search parameters for ($i = 0; $i < count($p['criteria']); $i++) { $_POST['itemtype'] = $itemtype; $_POST['num'] = $i; include GLPI_ROOT . '/ajax/searchrow.php'; } $metanames = array(); $linked = self::getMetaItemtypeAvailable($itemtype); if (is_array($linked) && count($linked) > 0) { for ($i = 0; $i < count($p['metacriteria']); $i++) { $_POST['itemtype'] = $itemtype; $_POST['num'] = $i; include GLPI_ROOT . '/ajax/searchmetarow.php'; } } echo "</table>\n"; echo "</td>\n"; echo "<td width='150px'>"; echo "<table width='100%'>"; // Display deleted selection echo "<tr>"; // Display submit button echo "<td width='80' class='center'>"; echo "<input type='submit' name='" . $p['actionname'] . "' value=\"" . $p['actionvalue'] . "\" class='submit' >"; echo "</td>"; if ($p['showbookmark'] || $p['showreset']) { echo "<td>"; if ($p['showbookmark']) { Bookmark::showSaveButton(Bookmark::SEARCH, $itemtype); } if ($p['showreset']) { echo "<a href='" . $p['target'] . (strpos($p['target'], '?') ? '&' : '?') . "reset=reset' >"; echo " <img title=\"" . __s('Blank') . "\" alt=\"" . __s('Blank') . "\" src='" . $CFG_GLPI["root_doc"] . "/pics/reset.png' class='calendrier pointer'></a>"; } echo "</td>"; } echo "</tr></table>\n"; echo "</td></tr>"; echo "</table>\n"; if (count($p['addhidden'])) { foreach ($p['addhidden'] as $key => $val) { echo Html::hidden($key, array('value' => $val)); } } // For dropdown echo Html::hidden('itemtype', array('value' => $itemtype)); // Reset to start when submit new search echo Html::hidden('start', array('value' => 0)); echo "</div>"; Html::closeForm(); }
/** * Creates an input file field. Send file names in _$name field as array. * Files are uploaded in files/_tmp/ directory * * @since version 0.85 * * @param $options array of options * - name string field name (default filename) * - multiple boolean allow multiple file upload (default false) * - onlyimages boolean restrict to image files (default false) * - showfilecontainer string DOM ID of the container showing file uploaded: * use selector to display * - showfilesize boolean show file size with file name * - rand string already computed rand value * - pasteZone string DOM ID of the paste zone * - dropZone string DOM ID of the drop zone * * @return string input file field **/ static function file($options = array()) { global $CFG_GLPI; $randupload = mt_rand(); $p['name'] = 'filename'; $p['multiple'] = false; $p['onlyimages'] = false; $p['showfilecontainer'] = ''; $p['showfilesize'] = true; $p['pasteZone'] = false; $p['dropZone'] = 'dropdoc' . $randupload; $p['rand'] = $randupload; $p['values'] = array(); if (is_array($options) && count($options)) { foreach ($options as $key => $val) { $p[$key] = $val; } } $addshowfilecontainer = false; if (empty($p['showfilecontainer'])) { $addshowfilecontainer = true; $p['showfilecontainer'] = "filedata{$randupload}"; } //echo "<input type='file' name='filename' value='".$this->fields["filename"]."' size='39'>"; $out = "<div class='fileupload' id='" . $p['dropZone'] . "'>"; $out .= "<span class='b'>" . __('Drag and drop your file here, or') . '</span><br>'; $out .= "<input id='fileupload{$randupload}' type='file' name='" . $p['name'] . "[]' data-url='" . $CFG_GLPI["root_doc"] . "/front/fileupload.php?name=" . $p['name'] . "&showfilesize=" . $p['showfilesize'] . "'>"; if ($addshowfilecontainer) { $out .= "<div id='" . $p['showfilecontainer'] . "'></div>"; } $script = self::fileScript($p) . "\n uploadFile" . $p['rand'] . "();"; $out .= Html::scriptBlock($script); $out .= "<div id='progress{$randupload}' style='display:none'>" . "<div class='uploadbar' style='width: 0%;'></div></div>"; $out .= "</div>"; return $out; }
/** * Show tabs * * @param $options array of parameters to add to URLs and ajax * - withtemplate is a template view ? * * @return Nothing () **/ function showNavigationHeader($options = array()) { global $CFG_GLPI; // for objects not in table like central if (isset($this->fields['id'])) { $ID = $this->fields['id']; } else { if (isset($options['id'])) { $ID = $options['id']; } else { $ID = 0; } } $target = $_SERVER['PHP_SELF']; $extraparamhtml = ""; $extraparam = ""; $withtemplate = ""; if (is_array($options) && count($options)) { $cleanoptions = $options; if (isset($options['withtemplate'])) { $withtemplate = $options['withtemplate']; unset($cleanoptions['withtemplate']); } foreach ($cleanoptions as $key => $val) { // Do not include id options if ($key[0] == '_' || $key == 'id') { unset($cleanoptions[$key]); } } $extraparamhtml = "&" . Toolbox::append_params($cleanoptions, '&'); $extraparam = "&" . Toolbox::append_params($cleanoptions); } if (empty($withtemplate) && !$this->isNewID($ID) && $this->getType() && $this->displaylist) { $glpilistitems =& $_SESSION['glpilistitems'][$this->getType()]; $glpilisttitle =& $_SESSION['glpilisttitle'][$this->getType()]; $glpilisturl =& $_SESSION['glpilisturl'][$this->getType()]; if (empty($glpilisturl)) { $glpilisturl = $this->getSearchURL(); } // echo "<div id='menu_navigate'>"; $next = $prev = $first = $last = -1; $current = false; if (is_array($glpilistitems)) { $current = array_search($ID, $glpilistitems); if ($current !== false) { if (isset($glpilistitems[$current + 1])) { $next = $glpilistitems[$current + 1]; } if (isset($glpilistitems[$current - 1])) { $prev = $glpilistitems[$current - 1]; } $first = $glpilistitems[0]; if ($first == $ID) { $first = -1; } $last = $glpilistitems[count($glpilistitems) - 1]; if ($last == $ID) { $last = -1; } } } $cleantarget = HTML::cleanParametersURL($target); echo "<div class='navigationheader'><table class='tab_cadre_pager'>"; echo "<tr class='tab_bg_2'>"; if ($first >= 0) { echo "<td class='left' width='16px'><a href='{$cleantarget}?id={$first}{$extraparamhtml}'>" . "<img src='" . $CFG_GLPI["root_doc"] . "/pics/first.png' alt=\"" . __s('First') . "\" title=\"" . __s('First') . "\" class='pointer'></a></td>"; } else { echo "<td class='left' width='16px'><img src='" . $CFG_GLPI["root_doc"] . "/pics/first_off.png' alt=\"" . __s('First') . "\" title=\"" . __s('First') . "\"></td>"; } if ($prev >= 0) { echo "<td class='left' width='16px'><a href='{$cleantarget}?id={$prev}{$extraparamhtml}' id='previouspage'>" . "<img src='" . $CFG_GLPI["root_doc"] . "/pics/left.png' alt=\"" . __s('Previous') . "\" title=\"" . __s('Previous') . "\" class='pointer'></a></td>"; $js = '$("body").keydown(function(e) { if ($("input, textarea").is(":focus") === false) { if(e.keyCode == 37 && e.ctrlKey) { window.location = $("#previouspage").attr("href"); } } });'; echo Html::scriptBlock($js); } else { echo "<td class='left' width='16px'><img src='" . $CFG_GLPI["root_doc"] . "/pics/left_off.png' alt=\"" . __s('Previous') . "\" title=\"" . __s('Previous') . "\"></td>"; } echo "<td width='200px'><a href=\"" . $glpilisturl . "\">"; if ($glpilisttitle) { echo $glpilisttitle; } else { _e('List'); } echo "</a></td>"; $name = $this->getTypeName(1); if (isset($this->fields['id']) && $this instanceof CommonDBTM) { $name = sprintf(__('%1$s - %2$s'), $name, sprintf(__('%1$s - ID %2$d'), $this->getName(), $this->fields['id'])); } if (isset($this->fields["entities_id"]) && Session::isMultiEntitiesMode() && $this->isEntityAssign()) { $entname = Dropdown::getDropdownName("glpi_entities", $this->fields["entities_id"]); if ($this->isRecursive()) { $entname = sprintf(__('%1$s + %2$s'), $entname, __('Child entities')); } $name = sprintf(__('%1$s (%2$s)'), $name, $entname); } echo "<td class='b big'>"; if (!self::isLayoutWithMain() || self::isLayoutExcludedPage()) { echo $name; } echo "</td>"; if ($current !== false) { echo "<td width='40px'>" . ($current + 1) . "/" . count($glpilistitems) . "</td>"; } if ($next >= 0) { echo "<td class='right' width='16px'><a href='{$cleantarget}?id={$next}{$extraparamhtml}' id='nextpage'>" . "<img src='" . $CFG_GLPI["root_doc"] . "/pics/right.png' alt=\"" . __s('Next') . "\" title=\"" . __s('Next') . "\" class='pointer'></a></td>"; $js = '$("body").keydown(function(e) { if ($("input, textarea").is(":focus") === false) { if(e.keyCode == 39 && e.ctrlKey) { window.location = $("#nextpage").attr("href"); } } });'; echo Html::scriptBlock($js); } else { echo "<td class='right' width='16px'><img src='" . $CFG_GLPI["root_doc"] . "/pics/right_off.png' alt=\"" . __s('Next') . "\" title=\"" . __s('Next') . "\"></td>"; } if ($last >= 0) { echo "<td class='right' width='16px'><a href='{$cleantarget}?id={$last}{$extraparamhtml}'>" . "<img src=\"" . $CFG_GLPI["root_doc"] . "/pics/last.png\" alt=\"" . __s('Last') . "\" title=\"" . __s('Last') . "\" class='pointer'></a></td>"; } else { echo "<td class='right' width='16px'><img src='" . $CFG_GLPI["root_doc"] . "/pics/last_off.png' alt=\"" . __s('Last') . "\" title=\"" . __s('Last') . "\"></td>"; } // echo "</ul></div>"; // End pager echo "</tr></table></div>"; // echo "<div class='sep'></div>"; } }
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 // we use REQUEST because method differ with layout (lefttab : GET, vsplit: POST) if (!isset($options['template_preview'])) { if (isset($_REQUEST)) { $values = Html::cleanPostForTextArea($_REQUEST); } } // 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() || $predeffield == 'requesttypes_id' && empty($saved)) { // 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 responsive_hidden'>"; 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><td colspan='2'></td></tr>"; // SLTs echo "<tr class='tab_bg_1'>"; echo "<th width='{$colsize1}%'>" . $tt->getBeginHiddenFieldText('time_to_own'); if (!$ID) { printf(__('%1$s%2$s'), __('Time to own'), $tt->getMandatoryMark('time_to_own')); } else { _e('Time to own'); } echo $tt->getEndHiddenFieldText('time_to_own'); echo "</th>"; echo "<td width='{$colsize2}%' class='nopadding'>"; $slt = new SLT(); $slt->showSltForTicket($this, SLT::TTO, $tt, $canupdate); echo "</td>"; echo "<th width='{$colsize3}%'>" . $tt->getBeginHiddenFieldText('due_date'); if (!$ID) { printf(__('%1$s%2$s'), __('Time to resolve'), $tt->getMandatoryMark('due_date')); } else { _e('Time to resolve'); } echo $tt->getEndHiddenFieldText('due_date'); echo "</th>"; echo "<td width='{$colsize4}%' class='nopadding'>"; $slt->showSltForTicket($this, SLT::TTR, $tt, $canupdate); echo "</td>"; echo "</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"], 'condition' => 'is_active = 1 AND is_ticketheader = 1')); } else { echo Dropdown::getDropdownName('glpi_requesttypes', $this->fields["requesttypes_id"]); echo Html::hidden('requesttypes_id', array('value' => $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 $tt->getBeginHiddenFieldValue('urgency'); echo parent::getUrgencyName($this->fields["urgency"]); echo $tt->getEndHiddenFieldValue('urgency', $this); } 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 (Session::haveRightsOr('ticketvalidation', TicketValidation::getCreateRights()) && $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 || !$ID) { 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>" . $tt->getBeginHiddenFieldText('priority'); printf(__('%1$s%2$s'), __('Priority'), $tt->getMandatoryMark('priority')); echo $tt->getEndHiddenFieldText('priority') . "</th>"; echo "<td>"; $idajax = 'change_priority_' . mt_rand(); if ($canpriority && !$tt->isHiddenField('priority')) { $idpriority = parent::dropdownPriority(array('value' => $this->fields["priority"], 'withmajor' => true)); $idpriority = 'dropdown_priority' . $idpriority; 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' => $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('items_id'); printf(__('%1$s%2$s'), _n('Associated element', 'Associated elements', Session::getPluralNumber()), $tt->getMandatoryMark('items_id')); 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('items_id'); echo "</th>"; if (!$ID) { echo "<td rowspan='2'>"; echo $tt->getBeginHiddenFieldValue('items_id'); $values['_canupdate'] = Session::haveRight('ticket', CREATE); if ($values['_canupdate']) { Item_Ticket::itemAddForm($this, $values); } echo $tt->getEndHiddenFieldValue('items_id', $this); echo "</td>"; } else { echo "<td>"; echo $tt->getBeginHiddenFieldValue('items_id'); $values['_canupdate'] = $canupdate || $canupdate_descr; Item_Ticket::itemAddForm($this, $values); echo $tt->getEndHiddenFieldValue('items_id', $this); 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 style='width:{$colsize1}%'>" . $tt->getBeginHiddenFieldText('name'); printf(__('%1$s%2$s'), __('Title'), $tt->getMandatoryMark('name')); echo $tt->getEndHiddenFieldText('name') . "</th>"; echo "<td colspan='3'>"; if (!$ID || $canupdate_descr) { echo $tt->getBeginHiddenFieldValue('name'); echo "<input type='text' style='width:98%' maxlength=250 name='name' " . " 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 style='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 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(); $rows = 6; $content_id = "content{$rand}"; if ($CFG_GLPI["use_rich_text"]) { $this->fields["content"] = $this->setRichTextContent($content_id, $this->fields["content"], $rand); $rows = 10; } else { $this->fields["content"] = $this->setSimpleTextContent($this->fields["content"]); } echo "<div id='content{$rand_text}'>"; echo "<textarea id='{$content_id}' name='content' style='width:100%' rows='{$rows}'>" . $this->fields["content"] . "</textarea></div>"; echo Html::scriptBlock("\$(document).ready(function() { \$('#{$content_id}').autogrow(); });"); 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 style='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 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 style='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'>"; // 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, DELETE, PURGE))) && !$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 ($this->canDeleteItem()) { 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 = 3; 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 "</tr>"; echo "<tr class='tab_bg_1'>"; echo "<td colspan='{$colspan}'>"; if (!isset($rand)) { $rand = mt_rand(); } if ($canupdate_descr) { echo Html::initImagePasteSystem($content_id, $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; }
/** form for Task * * @param $ID Integer : Id of the task * @param $options array * - parent Object : the object **/ function showForm($ID, $options = array()) { global $DB, $CFG_GLPI; $rand_template = mt_rand(); $rand_text = mt_rand(); $rand_type = mt_rand(); $rand_time = mt_rand(); if (isset($options['parent']) && !empty($options['parent'])) { $item = $options['parent']; } $fkfield = $item->getForeignKeyField(); if ($ID > 0) { $this->check($ID, READ); } else { // Create item $options[$fkfield] = $item->getField('id'); $this->check(-1, CREATE, $options); } $rand = mt_rand(); $this->showFormHeader($options); $canplan = !$item->isStatusExists(CommonITILObject::PLANNED) || $item->isAllowedStatus($item->fields['status'], CommonITILObject::PLANNED); $rowspan = 5; if ($this->maybePrivate()) { $rowspan++; } if (isset($this->fields["state"])) { $rowspan++; } echo "<tr class='tab_bg_1'>"; echo "<td rowspan='{$rowspan}' style='width:100px'>" . __('Description') . "</td>"; echo "<td rowspan='{$rowspan}' style='width:50%' id='content{$rand_text}'>" . "<textarea name='content' style='width: 95%; height: 160px' id='task{$rand_text}'>" . $this->fields["content"] . "</textarea>"; echo Html::scriptBlock("\$(document).ready(function() { \$('#content{$rand}').autogrow(); });"); echo "</td>"; echo "<input type='hidden' name='{$fkfield}' value='" . $this->fields[$fkfield] . "'>"; echo "</td></tr>\n"; echo "<tr class='tab_bg_1'>"; echo "<td style='width:100px'>" . _n('Task template', 'Task templates', 1) . "</td><td>"; TaskTemplate::dropdown(array('value' => 0, 'entity' => $this->getEntityID(), 'rand' => $rand_template, 'on_change' => 'tasktemplate_update(this.value)')); echo "</td>"; echo "</tr>"; echo Html::scriptBlock(' function tasktemplate_update(value) { jQuery.ajax({ url: "' . $CFG_GLPI["root_doc"] . '/ajax/task.php", type: "POST", data: { tasktemplates_id: value } }).done(function(datas) { datas.taskcategories_id = isNaN(parseInt(datas.taskcategories_id)) ? 0 : parseInt(datas.taskcategories_id); datas.actiontime = isNaN(parseInt(datas.actiontime)) ? 0 : parseInt(datas.actiontime); $("#task' . $rand_text . '").html(datas.content); $("#dropdown_taskcategories_id' . $rand_type . '").select2("val", parseInt(datas.taskcategories_id)); $("#dropdown_actiontime' . $rand_time . '").select2("val", parseInt(datas.actiontime)); }); } '); if ($ID > 0) { echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Date') . "</td>"; echo "<td>"; Html::showDateTimeField("date", array('value' => $this->fields["date"], 'timestep' => 1, 'maybeempty' => false)); echo "</tr>"; } else { echo "<tr class='tab_bg_1'>"; echo "<td colspan='2'> "; echo "</tr>"; } echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Category') . "</td><td>"; TaskCategory::dropdown(array('value' => $this->fields["taskcategories_id"], 'rand' => $rand_type, 'entity' => $item->fields["entities_id"], 'condition' => "`is_active` = '1'")); echo "</td></tr>\n"; if (isset($this->fields["state"])) { echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Status') . "</td><td>"; Planning::dropdownState("state", $this->fields["state"]); echo "</td></tr>\n"; } if ($this->maybePrivate()) { echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Private') . "</td>"; echo "<td>"; Dropdown::showYesNo('is_private', $this->fields["is_private"]); echo "</td>"; echo "</tr>"; } echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Duration') . "</td><td>"; $toadd = array(); for ($i = 9; $i <= 100; $i++) { $toadd[] = $i * HOUR_TIMESTAMP; } Dropdown::showTimeStamp("actiontime", array('min' => 0, 'max' => 8 * HOUR_TIMESTAMP, 'value' => $this->fields["actiontime"], 'rand' => $rand_time, 'addfirstminutes' => true, 'inhours' => true, 'toadd' => $toadd)); echo "</td></tr>\n"; if ($ID <= 0) { Document_Item::showSimpleAddForItem($item); } echo "<tr class='tab_bg_1'>"; echo "<td>" . __('By') . "</td>"; echo "<td colspan='2'>"; echo Html::image($CFG_GLPI['root_doc'] . "/pics/user.png") . " "; echo _n('User', 'Users', 1); $rand_user = mt_rand(); $params = array('name' => "users_id_tech", 'value' => $ID > -1 ? $this->fields["users_id_tech"] : Session::getLoginUserID(), 'right' => "own_ticket", 'rand' => $rand_user, 'entity' => $item->fields["entities_id"], 'width' => ''); $params['toupdate'] = array('value_fieldname' => 'users_id', 'to_update' => "user_available{$rand_user}", 'url' => $CFG_GLPI["root_doc"] . "/ajax/planningcheck.php"); User::dropdown($params); echo " <a href='#' onClick=\"" . Html::jsGetElementbyID('planningcheck' . $rand) . ".dialog('open');\">"; echo " <img src='" . $CFG_GLPI["root_doc"] . "/pics/reservation-3.png'\n title=\"" . __s('Availability') . "\" alt=\"" . __s('Availability') . "\"\n class='calendrier'>"; echo "</a>"; Ajax::createIframeModalWindow('planningcheck' . $rand, $CFG_GLPI["root_doc"] . "/front/planning.php?checkavailability=checkavailability" . "&itemtype=" . $item->getType() . "&{$fkfield}=" . $item->getID(), array('title' => __('Availability'))); echo "<br />"; echo Html::image($CFG_GLPI['root_doc'] . "/pics/group.png") . " "; echo _n('Group', 'Groups', 1) . " "; $rand_group = mt_rand(); $params = array('name' => "groups_id_tech", 'value' => $ID > -1 ? $this->fields["groups_id_tech"] : Dropdown::EMPTY_VALUE, 'condition' => "is_task", 'rand' => $rand_group, 'entity' => $item->fields["entities_id"]); $params['toupdate'] = array('value_fieldname' => 'users_id', 'to_update' => "group_available{$rand_group}", 'url' => $CFG_GLPI["root_doc"] . "/ajax/planningcheck.php"); Group::dropdown($params); echo "</td>\n"; echo "<td>"; if ($canplan) { echo __('Planning'); } if (!empty($this->fields["begin"])) { if (Session::haveRight('planning', Planning::READMY)) { echo "<script type='text/javascript' >\n"; echo "function showPlan" . $ID . $rand_text . "() {\n"; echo Html::jsHide("plan{$rand_text}"); $params = array('action' => 'add_event_classic_form', 'form' => 'followups', 'users_id' => $this->fields["users_id_tech"], 'groups_id' => $this->fields["groups_id_tech"], 'id' => $this->fields["id"], 'begin' => $this->fields["begin"], 'end' => $this->fields["end"], 'rand_user' => $rand_user, 'rand_group' => $rand_group, 'entity' => $item->fields["entities_id"], 'itemtype' => $this->getType(), 'items_id' => $this->getID()); Ajax::updateItemJsCode("viewplan{$rand_text}", $CFG_GLPI["root_doc"] . "/ajax/planning.php", $params); echo "}"; echo "</script>\n"; echo "<div id='plan{$rand_text}' onClick='showPlan" . $ID . $rand_text . "()'>\n"; echo "<span class='showplan'>"; } if (isset($this->fields["state"])) { echo Planning::getState($this->fields["state"]) . "<br>"; } printf(__('From %1$s to %2$s'), Html::convDateTime($this->fields["begin"]), Html::convDateTime($this->fields["end"])); if (isset($this->fields["users_id_tech"]) && $this->fields["users_id_tech"] > 0) { echo "<br>" . getUserName($this->fields["users_id_tech"]); } if (isset($this->fields["groups_id_tech"]) && $this->fields["groups_id_tech"] > 0) { echo "<br>" . Dropdown::getDropdownName('glpi_groups', $this->fields["groups_id_tech"]); } if (Session::haveRight('planning', Planning::READMY)) { echo "</span>"; echo "</div>\n"; echo "<div id='viewplan{$rand_text}'></div>\n"; } } else { if ($canplan) { echo "<script type='text/javascript' >\n"; echo "function showPlanUpdate{$rand_text}() {\n"; echo Html::jsHide("plan{$rand_text}"); $params = array('action' => 'add_event_classic_form', 'form' => 'followups', 'entity' => $item->fields['entities_id'], 'rand_user' => $rand_user, 'rand_group' => $rand_group, 'itemtype' => $this->getType(), 'items_id' => $this->getID()); Ajax::updateItemJsCode("viewplan{$rand_text}", $CFG_GLPI["root_doc"] . "/ajax/planning.php", $params); echo "};"; echo "</script>"; if ($canplan) { echo "<div id='plan{$rand_text}' onClick='showPlanUpdate{$rand_text}()'>\n"; echo "<span class='vsubmit'>" . __('Plan this task') . "</span>"; echo "</div>\n"; echo "<div id='viewplan{$rand_text}'></div>\n"; } } else { _e('None'); } } echo "</td></tr>"; if (!empty($this->fields["begin"]) && PlanningRecall::isAvailable()) { echo "<tr class='tab_bg_1'><td>" . _x('Planning', 'Reminder') . "</td><td class='center'>"; PlanningRecall::dropdown(array('itemtype' => $this->getType(), 'items_id' => $this->getID())); echo "</td><td colspan='2'></td></tr>"; } $this->showFormButtons($options); return true; }
Html::helpHeader(Ticket::getTypeName(Session::getPluralNumber()), '', $_SESSION["glpiname"]); } else { Html::header(Ticket::getTypeName(Session::getPluralNumber()), '', "helpdesk", "ticket"); } $available_options = array('load_kb_sol', '_openfollowup'); $options = array(); foreach ($available_options as $key) { if (isset($_GET[$key])) { $options[$key] = $_GET[$key]; } } $options['id'] = $_GET["id"]; $track->display($options); if (isset($_GET['_sol_to_kb'])) { Ajax::createIframeModalWindow('savetokb', $CFG_GLPI["root_doc"] . "/front/knowbaseitem.form.php?_in_modal=1&item_itemtype=Ticket&item_items_id=" . $_GET["id"], array('title' => __('Save solution to the knowledge base'), 'reloadonclose' => false)); echo Html::scriptBlock(Html::jsGetElementbyID('savetokb') . ".dialog('open');"); } } else { Html::header(__('New ticket'), '', "helpdesk", "ticket"); unset($_REQUEST['id']); // Add a ticket from item : format data if (isset($_REQUEST['_add_fromitem'])) { $_REQUEST['items_id'] = array($_REQUEST['itemtype'] => array($_REQUEST['items_id'])); } $track->display($_REQUEST); } if ($_SESSION["glpiactiveprofile"]["interface"] == "helpdesk") { Html::helpFooter(); } else { Html::footer(); }
function showForm($ID, $options = array()) { global $DB, $CFG_GLPI; $obj = $options['obj']; //Html::printCleanArray($obj); $itemtype = getItemTypeForTable($obj->getTable()); $list_ip = array(); $total_ip = 0; /*if ($itemtype == 'NetworkEquipment') { $query = "SELECT `ip` FROM `glpi_networkequipments` WHERE `id` = '".$obj->fields['id']."'"; $res = $DB->query($query); while ($row = $DB->fetch_array($res)) { if ($row['ip'] != '') { $list_ip[$row['ip']] = $row['ip']; } } } $tmp = array_values($list_ip); if (count($tmp) > 0 && $tmp[0] == '') { array_pop($list_ip); }*/ $query = "SELECT `glpi_networknames`.`name`, `glpi_ipaddresses`.`name` as ip, `glpi_networkports`.`items_id`\n FROM `glpi_networkports` \n LEFT JOIN `" . $obj->getTable() . "` ON (`glpi_networkports`.`items_id` = `" . $obj->getTable() . "`.`id`\n AND `glpi_networkports`.`itemtype` = '" . $itemtype . "')\n LEFT JOIN `glpi_networknames` ON (`glpi_networkports`.`id` = `glpi_networknames`.`items_id`)\n LEFT JOIN `glpi_ipaddresses` ON (`glpi_ipaddresses`.`items_id` = `glpi_networknames`.`id`)\n WHERE `" . $obj->getTable() . "`.`id` = '" . $obj->fields['id'] . "'"; $res = $DB->query($query); while ($row = $DB->fetch_array($res)) { if ($row['ip'] != '') { $port = $row['ip']; if ($row['name'] != '') { $port = $row['name'] . " ({$port})"; } $list_ip[$row['ip']] = $port; } } echo "<table class='tab_cadre_fixe'><tr class='tab_bg_2 left'>"; echo "<tr><th colspan='4'>" . __('IP ping', 'addressing') . "</th></tr>"; if (count($list_ip) > 0) { echo "<tr class='tab_bg_1'>"; echo "<td>" . __('IP') . " : </td>"; echo "<td colspan='3'>"; echo "<select id='ip'>"; echo "<option>" . Dropdown::EMPTY_VALUE . "</option>"; foreach ($list_ip as $ip => $name) { echo "<option value='{$ip}'>{$name}</option>"; } echo "</select>"; echo " <input class='submit' type='button' value='" . __s('Ping', 'addressing') . "' id='ping_ip'>"; echo "</td>"; echo "</tr>"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Result', 'addressing') . " : </td>"; echo "<td colspan='3'>"; echo "<div id='ping_response' class='plugin_addressing_ping_equipment'></div>"; echo "</td></tr>"; } echo "</table>"; echo Html::scriptBlock("\$(document).on('click', '#ping_ip', function(event) {\n \$('#ping_response').load('" . $CFG_GLPI["root_doc"] . "/plugins/addressing/ajax/ping.php', {\n 'ip': \$('#ip').val()\n })\n });"); if (count($list_ip) == 0) { echo __('No IP for this equipment', 'addressing'); } }
function showForm($ID, $options = array()) { $this->initForm($ID, $options); $options['formoptions'] = "onSubmit='return plugaddr_Check(\"" . __('Invalid data !!', 'addressing') . "\")'"; $this->showFormHeader($options); $PluginAddressingConfig = new PluginAddressingConfig(); $PluginAddressingConfig->getFromDB('1'); echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Name') . "</td>"; echo "<td>"; Html::autocompletionTextField($this, "name"); echo "</td>"; if ($PluginAddressingConfig->fields["alloted_ip"]) { echo "<td>" . __('Assigned IP', 'addressing') . "</td><td>"; Dropdown::showYesNo('alloted_ip', $this->fields["alloted_ip"]); echo "</td>"; } else { echo "<td>"; echo Html::hidden('alloted_ip', array('value' => 0)); //echo "<input type='hidden' name='alloted_ip' value='0'></td><td></td>"; echo "</td><td></td>"; } echo "</tr>"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Select the network', 'addressing') . "</td>"; echo "<td>"; Dropdown::show('Network', array('name' => "networks_id", 'value' => $this->fields["networks_id"])); echo "</td>"; if ($PluginAddressingConfig->fields["free_ip"]) { echo "<td>" . __('Free Ip', 'addressing') . "</td><td>"; Dropdown::showYesNo('free_ip', $this->fields["free_ip"]); echo "</td>"; } else { echo "<td>"; echo Html::hidden('free_ip', array('value' => 0)); echo "</td><td></td>"; //echo "<td><input type='hidden' name='free_ip' value='0'></td><td></td>"; } echo "</tr>"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Detected subnet list', 'addressing') . "</td>"; echo "<td>"; $this->dropdownSubnet($ID > 0 ? $this->fields["entities_id"] : $_SESSION["glpiactive_entity"]); echo "</td>"; if ($PluginAddressingConfig->fields["double_ip"]) { echo "<td>" . __('Same IP', 'addressing') . "</td><td>"; Dropdown::showYesNo('double_ip', $this->fields["double_ip"]); echo "</td>"; } else { //echo "<td><input type='hidden' name='double_ip' value='0'></td><td></td>"; echo "<td>"; echo Html::hidden('double_ip', array('value' => 0)); echo "</td><td></td>"; } echo "</tr>"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('First IP', 'addressing') . "</td>"; // Subnet echo "<td>"; echo "<input type='text' id='plugaddr_ipdeb0' value='' name='_ipdeb0' size='3' " . "onChange='plugaddr_ChangeNumber(\"" . __('Invalid data !!', 'addressing') . "\");'>."; echo "<input type='text' id='plugaddr_ipdeb1' value='' name='_ipdeb1' size='3' " . "onChange='plugaddr_ChangeNumber(\"" . __('Invalid data !!', 'addressing') . "\");'>."; echo "<input type='text' id='plugaddr_ipdeb2' value='' name='_ipdeb2' size='3' " . "onChange='plugaddr_ChangeNumber(\"" . __('Invalid data !!', 'addressing') . "\");'>."; echo "<input type='text' id='plugaddr_ipdeb3' value='' name='_ipdeb3' size='3' " . "onChange='plugaddr_ChangeNumber(\"" . __('Invalid data !!', 'addressing') . "\");'>"; echo "</td>"; if ($PluginAddressingConfig->fields["reserved_ip"]) { echo "<td>" . __('Reserved IP', 'addressing') . "</td><td>"; Dropdown::showYesNo('reserved_ip', $this->fields["reserved_ip"]); echo "</td>"; } else { echo "<td>"; echo Html::hidden('reserved_ip', array('value' => 0)); echo "</td><td></td>"; //echo "<td><input type='hidden' name='reserved_ip' value='0'></td><td></td>"; } echo "</tr>"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Last IP', 'addressing') . "</td>"; // Mask echo "<td>"; echo "<input type='text' id='plugaddr_ipfin0' value='' name='_ipfin0' size='3' " . "onChange='plugaddr_ChangeNumber(\"" . __('Invalid data !!', 'addressing') . "\");'>."; echo "<input type='text' id='plugaddr_ipfin1' value='' name='_ipfin1' size='3' " . "onChange='plugaddr_ChangeNumber(\"" . __('Invalid data !!', 'addressing') . "\");'>."; echo "<input type='text' id='plugaddr_ipfin2' value='' name='_ipfin2' size='3' " . "onChange='plugaddr_ChangeNumber(\"" . __('Invalid data !!', 'addressing') . "\");'>."; echo "<input type='text' id='plugaddr_ipfin3' value='' name='_ipfin3' size='3' " . "onChange='plugaddr_ChangeNumber(\"" . __('Invalid data !!', 'addressing') . "\");'>"; echo "</td>"; if ($PluginAddressingConfig->fields["use_ping"]) { echo "<td>" . __('Ping free Ip', 'addressing') . "</td><td>"; Dropdown::showYesNo('use_ping', $this->fields["use_ping"]); echo "</td>"; } else { echo "<td>"; echo Html::hidden('use_ping', array('value' => 0)); echo "</td><td></td>"; //echo "<td><input type='hidden' name='use_ping' value='0'></td><td></td>"; } echo "</tr>"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Report for the IP Range', 'addressing') . "</td>"; // Mask echo "<td>"; echo "<input type='hidden' id='plugaddr_ipdeb' value='" . $this->fields["begin_ip"] . "' name='begin_ip'>"; echo "<input type='hidden' id='plugaddr_ipfin' value='" . $this->fields["end_ip"] . "' name='end_ip'>"; echo "<div id='plugaddr_range'>-</div>"; if ($ID > 0) { $js = "plugaddr_Init(\"" . __('Invalid data !!', 'addressing') . "\");"; echo Html::scriptBlock($js); } echo "</td>"; echo "<td></td>"; echo "<td></td>"; echo "</tr>"; echo "<tr class='tab_bg_1'>"; echo "<td colspan = '4'>"; echo "<table cellpadding='2' cellspacing='2'><tr><td>"; echo __('Comments') . "</td></tr>"; echo "<tr><td class='center'>" . "<textarea cols='125' rows='3' name='comment'>" . $this->fields["comment"] . "</textarea>"; echo "</td></tr></table>"; echo "</td>"; $this->showFormButtons($options); return true; }
/** * Summary of displayLockMessage * Shows a short message top-left of screen * This message is permanent, and can't be closed * * @param $msg : message to be shown * @param $title : if $title is '' then title bar it is not shown (default '') **/ private function displayLockMessage($msg, $title = '') { $hideTitle = ''; if ($title == '') { $hideTitle = "\$('.ui-dialog-titlebar', ui.dialog | ui).hide();"; } echo "<div id='message_after_lock' title='{$title}'>"; echo $msg; echo "</div>"; echo Html::scriptBlock("\n \$(document).ready(function() {\n \$('#message_after_lock').dialog({\n dialogClass: 'message_after_redirect',\n minHeight: 10,\n width: 'auto',\n height: 'auto',\n position: {\n my: 'left top',\n at: 'left+20 top-30',\n of: \$('#page'),\n collision: 'none'\n },\n autoOpen: false,\n create: function(event, ui) {\n {$hideTitle}\n \$('.ui-dialog-titlebar-close', ui.dialog | ui).hide();\n },\n show: {\n effect: 'slide',\n direction: 'up',\n duration: 800\n },\n })\n .dialog('open');\n });\n "); }
public function ajaxModuleItemsDropdown($options) { $moduletype = $options['moduletype']; $itemtype = $options['itemtype']; if ($itemtype === "") { return; } switch ($options['moduletype']) { case 'actors': $title = __('Actor Item', 'fusioninventory'); break; case 'targets': $title = __('Target Item', 'fusioninventory'); break; } /** * get Itemtype choices dropdown */ $dropdown_rand = $this->showDropdownForItemtype($title, $itemtype, array('width' => "95%")); $item = getItemForItemtype($itemtype); $itemtype_name = $item->getTypeName(); $item_key_id = $item->getForeignKeyField(); $dropdown_rand_id = "dropdown_" . $item_key_id . $dropdown_rand; echo implode(array("\n", "<div class='center' id='add_fusinv_job_item_button'>", "<input type='button' class=submit", " value='" . __('Add') . " {$title}'", " onclick='javascript:void(0)'>", "</input>", "</div>")); echo Html::scriptBlock(implode("\n", array("\$('#add_fusinv_job_item_button').on('click', function() {", " taskjobs.add_item(", " \"{$moduletype}\", \"{$itemtype}\", \"{$itemtype_name}\", \"{$dropdown_rand_id}\"", " );", "});"))); }
public static function showSelectAccountsList($ID) { global $CFG_GLPI; $rand = mt_rand(); echo "<div align='center'>"; echo "<table class='tab_cadre_fixe' cellpadding='5'>"; echo "<tr><th colspan='2'>"; echo __('Linked accounts list', 'accounts') . "</th></tr>"; echo "<tr class='tab_bg_1'>"; echo "<td>"; echo __('Please fill the encryption key', 'accounts') . "</td>"; echo "<td class='center'>"; echo "<input type='password' autocomplete='off' name='key' id='key'> "; echo "<input type='submit' name='select' value=\"" . __s('Display report') . "\"\n class='submit' id='showAccountsList{$rand}'>"; echo "</td>"; echo "</tr>"; echo "</table></div>"; $url = $CFG_GLPI["root_doc"] . "/plugins/accounts/ajax/viewaccountslist.php"; echo "<div id='viewaccountslist{$rand}'></div>"; echo Html::scriptBlock("\$(document).on('click', '#showAccountsList{$rand}', function(){\n var key = \$('#key').val();\n if (key == '') {\n alert('" . __('Please fill the encryption key', 'accounts') . "');\n } else {\n \$('#viewaccountslist{$rand}').load('{$url}', {'id': {$ID}, 'key': key});\n }\n });"); }
/** * Print the computer form * * @param $ID integer ID of the item * @param $options array * - target for the Form * - withtemplate template or basic computer * *@return Nothing (display) **/ function showForm($ID, $options = array()) { global $CFG_GLPI, $DB; $this->initForm($ID, $options); $this->showFormHeader($options); echo "<tr class='tab_bg_1'>"; //TRANS: %1$s is a string, %2$s a second one without spaces between them : to change for RTL echo "<td>" . sprintf(__('%1$s%2$s'), __('Name'), isset($options['withtemplate']) && $options['withtemplate'] ? "*" : "") . "</td>"; echo "<td>"; $objectName = autoName($this->fields["name"], "name", isset($options['withtemplate']) && $options['withtemplate'] == 2, $this->getType(), $this->fields["entities_id"]); Html::autocompletionTextField($this, 'name', array('value' => $objectName)); echo "</td>"; echo "<td>" . __('Status') . "</td>"; echo "<td>"; State::dropdown(array('value' => $this->fields["states_id"], 'entity' => $this->fields["entities_id"], 'condition' => "`is_visible_computer`")); echo "</td></tr>\n"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Location') . "</td>"; echo "<td>"; Location::dropdown(array('value' => $this->fields["locations_id"], 'entity' => $this->fields["entities_id"])); echo "</td>"; echo "<td>" . __('Type') . "</td>"; echo "<td>"; ComputerType::dropdown(array('value' => $this->fields["computertypes_id"])); echo "</td></tr>\n"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Technician in charge of the hardware') . "</td>"; echo "<td>"; User::dropdown(array('name' => 'users_id_tech', 'value' => $this->fields["users_id_tech"], 'right' => 'own_ticket', 'entity' => $this->fields["entities_id"])); echo "</td>"; echo "<td>" . __('Manufacturer') . "</td>"; echo "<td>"; Manufacturer::dropdown(array('value' => $this->fields["manufacturers_id"])); echo "</td></tr>\n"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Group in charge of the hardware') . "</td>"; echo "<td>"; Group::dropdown(array('name' => 'groups_id_tech', 'value' => $this->fields['groups_id_tech'], 'entity' => $this->fields['entities_id'], 'condition' => '`is_assign`')); echo "</td>"; echo "<td>" . __('Model') . "</td>"; echo "<td>"; ComputerModel::dropdown(array('value' => $this->fields["computermodels_id"])); echo "</td></tr>\n"; echo "<tr class='tab_bg_1'>"; //TRANS: Number of the alternate username echo "<td>" . __('Alternate username number') . "</td>"; echo "<td >"; Html::autocompletionTextField($this, 'contact_num'); echo "</td>"; echo "<td>" . __('Serial number') . "</td>"; echo "<td >"; Html::autocompletionTextField($this, 'serial'); echo "</td></tr>\n"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Alternate username') . "</td>"; echo "<td>"; Html::autocompletionTextField($this, 'contact'); echo "</td>"; echo "<td>" . sprintf(__('%1$s%2$s'), __('Inventory number'), isset($options['withtemplate']) && $options['withtemplate'] ? "*" : "") . "</td>"; echo "<td>"; $objectName = autoName($this->fields["otherserial"], "otherserial", isset($options['withtemplate']) && $options['withtemplate'] == 2, $this->getType(), $this->fields["entities_id"]); Html::autocompletionTextField($this, 'otherserial', array('value' => $objectName)); echo "</td></tr>\n"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('User') . "</td>"; echo "<td>"; User::dropdown(array('value' => $this->fields["users_id"], 'entity' => $this->fields["entities_id"], 'right' => 'all')); echo "</td>"; echo "<td>" . __('Network') . "</td>"; echo "<td>"; Network::dropdown(array('value' => $this->fields["networks_id"])); echo "</td></tr>\n"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Group') . "</td>"; echo "<td>"; Group::dropdown(array('value' => $this->fields["groups_id"], 'entity' => $this->fields["entities_id"], 'condition' => '`is_itemgroup`')); echo "</td>"; // Display auto inventory informations $rowspan = 7; $inventory_show = false; if (!empty($ID) && Plugin::haveImport() && $this->fields["is_dynamic"]) { $inventory_show = true; $rowspan -= 5; } echo "<td rowspan='{$rowspan}'>" . __('Comments') . "</td>"; echo "<td rowspan='{$rowspan}' class='middle'>"; echo "<textarea cols='45' rows='" . ($rowspan + 3) . "' name='comment' >" . $this->fields["comment"]; echo "</textarea></td></tr>"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Domain') . "</td>"; echo "<td >"; Domain::dropdown(array('value' => $this->fields["domains_id"], 'entity' => $this->fields["entities_id"])); echo "</td></tr>"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Operating system') . "</td>"; echo "<td>"; OperatingSystem::dropdown(array('value' => $this->fields["operatingsystems_id"])); echo "<br /><a href='#' id='toggle_os_information'>" . __("More information") . "</a>"; echo "</td>"; if ($inventory_show) { echo "<td rowspan='4' colspan='2'>"; Plugin::doHook("autoinventory_information", $this); echo "</td>"; } echo "</tr>"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Version of the operating system') . "</td>"; echo "<td >"; OperatingSystemVersion::dropdown(array('value' => $this->fields["operatingsystemversions_id"])); echo "</td>"; echo "</tr>"; echo "<tr class='tab_bg_1'><td colspan='2'>"; echo Html::scriptBlock("\n \$(document).ready(function(){\n \$('#os_information').hide();\n\n \$('#toggle_os_information').on('click',function() {\n \$('#os_information').dialog({\n width:'auto',\n resizable: false,\n appendTo: '#os_information_parent',\n position: {\n my : 'left top',\n at : 'left bottom',\n of: \$('#toggle_os_information')\n }\n })\n })\n });"); // group os advanced information in a single bloc (who can be toggled) echo "<div id='os_information_parent'>"; echo "<div id='os_information' title=\"" . __('Operating system') . "\">"; echo "<table>"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Service pack') . "</td>"; echo "<td >"; OperatingSystemServicePack::dropdown(array('value' => $this->fields["operatingsystemservicepacks_id"])); echo "</td></tr>"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Operating system architecture') . "</td>"; echo "<td >"; OperatingSystemArchitecture::dropdown(array('value' => $this->fields["operatingsystemarchitectures_id"])); echo "</td></tr>"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Kernel version of the operating system') . "</td>"; echo "<td >"; Html::autocompletionTextField($this, 'os_kernel_version'); echo "</td></tr>"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Product ID of the operating system') . "</td>"; echo "<td >"; Html::autocompletionTextField($this, 'os_licenseid'); echo "</td></tr>"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Serial of the operating system') . "</td>"; echo "<td >"; Html::autocompletionTextField($this, 'os_license_number'); echo "</td>"; echo "</table>"; echo "</div>"; echo "</div>"; echo "</td>"; echo "</tr>"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('UUID') . "</td>"; echo "<td >"; Html::autocompletionTextField($this, 'uuid'); echo "</td>"; echo "</tr>\n"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Update Source') . "</td>"; echo "<td >"; AutoUpdateSystem::dropdown(array('value' => $this->fields["autoupdatesystems_id"])); echo "</td></tr>"; $this->showFormButtons($options); return true; }
$addclass = ''; if ($_POST["num"] == 0) { $addclass = ' headerRow'; } echo "<tr class='normalcriteria{$addclass}' id='{$rowid}'><td class='left' width='45%'>"; // First line display add / delete images for normal and meta search items if ($_POST["num"] == 0) { $linked = Search::getMetaItemtypeAvailable($_POST["itemtype"]); echo "<img class='pointer' src=\"" . $CFG_GLPI["root_doc"] . "/pics/plus.png\" alt='+' title=\"" . __s('Add a search criterion') . "\" id='addsearchcriteria{$randrow}'>"; $js = Html::jsGetElementbyID("addsearchcriteria{$randrow}") . ".on('click', function(e) {\n \$.post( '" . $CFG_GLPI['root_doc'] . "/ajax/searchrow.php',\n { itemtype: '" . $_POST["itemtype"] . "', num: {$nbsearchcountvar} })\n .done(function( data ) {\n \$('#" . $searchcriteriatableid . " .normalcriteria:last').after(data);\n });\n {$nbsearchcountvar} = {$nbsearchcountvar} +1;});"; echo Html::scriptBlock($js); echo " "; if (is_array($linked) && count($linked) > 0) { echo "<img class='pointer' src=\"" . $CFG_GLPI["root_doc"] . "/pics/meta_plus.png\" \n alt='+' title=\"" . __s('Add a global search criterion') . "\" id='addmetasearchcriteria{$randrow}'>"; $js = Html::jsGetElementbyID("addmetasearchcriteria{$randrow}") . ".on('click', function(e) {\n \$.post( '" . $CFG_GLPI['root_doc'] . "/ajax/searchmetarow.php',\n { itemtype: '" . $_POST["itemtype"] . "', num: {$nbmetasearchcountvar} })\n .done(function( data ) {\n \$('#" . $searchcriteriatableid . "').append(data);\n });\n {$nbmetasearchcountvar} = {$nbmetasearchcountvar} +1;});"; echo Html::scriptBlock($js); echo " "; } // Instanciate an object to access method $item = NULL; if ($_POST["itemtype"] != 'AllAssets') { $item = getItemForItemtype($_POST["itemtype"]); } if ($item && $item->maybeDeleted()) { echo "<input type='hidden' id='is_deleted' name='is_deleted' value='" . $p['is_deleted'] . "'>"; } } else { echo "<img class='pointer' src=\"" . $CFG_GLPI["root_doc"] . "/pics/moins.png\" alt='-' title=\"" . __s('Delete a search criterion') . "\" onclick=\"" . Html::jsGetElementbyID($rowid) . ".remove();\"> "; } $criteria = array(); if (isset($_SESSION['glpisearch'][$_POST["itemtype"]]['criteria'][$_POST["num"]]) && is_array($_SESSION['glpisearch'][$_POST["itemtype"]]['criteria'][$_POST["num"]])) {
/** * Show SLT for ticket * * @param $ticket Ticket item * @param $type * @param $tt * @param $canupdate **/ function showSltForTicket(Ticket $ticket, $type, $tt, $canupdate) { global $CFG_GLPI; list($dateField, $sltField) = self::getSltFieldNames($type); echo "<table width='100%'>"; echo "<tr class='tab_bg_1'>"; if (!isset($ticket->fields[$dateField]) || $ticket->fields[$dateField] == 'NULL') { $ticket->fields[$dateField] = ''; } if ($ticket->fields['id']) { if ($this->getSltDataForTicket($ticket->fields['id'], $type)) { echo "<td>"; echo Html::convDateTime($ticket->fields[$dateField]); echo "</td>"; echo "<th>" . __('SLT') . "</th>"; echo "<td>"; echo Dropdown::getDropdownName('glpi_slts', $ticket->fields[$sltField]) . " "; $commentsla = ""; $slalevel = new SlaLevel(); $nextaction = new SlaLevel_Ticket(); if ($nextaction->getFromDBForTicket($ticket->fields["id"], $type)) { $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('sla', READ)) { $slaoptions['link'] = Toolbox::getItemTypeFormURL('SLT') . "?id=" . $this->fields["id"]; } Html::showToolTip($commentsla, $slaoptions); if ($canupdate) { $fields = array('slt_delete' => 'slt_delete', 'id' => $ticket->getID(), 'type' => $type, '_glpi_csrf_token' => Session::getNewCSRFToken(), '_glpi_simple_form' => 1); $JS = " function delete_date{$type}(){\n if (nativeConfirm('" . addslashes(__('Also delete date ?')) . "')) {\n submitGetLink('" . $ticket->getFormURL() . "',\n " . json_encode(array_merge($fields, array('delete_date' => 1))) . ");\n } else {\n submitGetLink('" . $ticket->getFormURL() . "',\n " . json_encode(array_merge($fields, array('delete_date' => 0))) . ");\n }\n }"; echo Html::scriptBlock($JS); echo "<a class='pointer' onclick='delete_date{$type}();return false;'>"; echo "<img src='" . $CFG_GLPI['root_doc'] . "/pics/delete.png' title='" . _x('button', 'Delete permanently') . "' " . "alt='" . _x('button', 'Delete permanently') . "' class='pointer'>"; echo "</a>"; } echo "</td>"; } else { echo "<td width='200px'>"; echo $tt->getBeginHiddenFieldValue($dateField); if ($canupdate) { Html::showDateTimeField($dateField, array('value' => $ticket->fields[$dateField], 'timestep' => 1, 'maybeempty' => true)); } else { echo Html::convDateTime($ticket->fields[$dateField]); } echo $tt->getEndHiddenFieldValue($dateField, $ticket); echo "</td>"; $slt_data = $this->getSltData("`type` = '{$type}'\n AND `entities_id` = '" . $ticket->fields['entities_id'] . "'"); if ($canupdate && !empty($slt_data)) { echo "<td>"; echo $tt->getBeginHiddenFieldText($sltField); echo "<span id='slt_action{$type}'>"; echo "<a " . Html::addConfirmationOnAction(array(__('The assignment of a SLT to a ticket causes the recalculation of the date.'), __("Escalations defined in the SLT will be triggered under this new date.")), "cleanhide('slt_action{$type}');cleandisplay('slt_choice{$type}');") . "><img src='" . $CFG_GLPI['root_doc'] . "/pics/clock.png' title='" . __('SLT') . "' alt='" . __('SLT') . "' class='pointer'></a>"; echo "</span>"; echo "<div id='slt_choice{$type}' style='display:none'>"; echo "<span class='b'>" . __('SLT') . "</span> "; Slt::dropdown(array('name' => $sltField, 'entity' => $ticket->fields["entities_id"], 'condition' => "`type` = '" . $type . "'")); echo "</div>"; echo $tt->getEndHiddenFieldText($sltField); echo "</td>"; } } } else { // New Ticket echo "<td>"; echo $tt->getBeginHiddenFieldValue($dateField); Html::showDateTimeField($dateField, array('value' => $ticket->fields[$dateField], 'timestep' => 1, 'maybeempty' => false, 'canedit' => $canupdate)); echo $tt->getEndHiddenFieldValue($dateField, $ticket); echo "</td>"; $slt_data = $this->getSltData("`type` = '{$type}'\n AND `entities_id` = '" . $ticket->fields['entities_id'] . "'"); if ($canupdate && !empty($slt_data)) { echo "<th>" . $tt->getBeginHiddenFieldText($sltField); printf(__('%1$s%2$s'), __('SLT'), $tt->getMandatoryMark($sltField)); echo $tt->getEndHiddenFieldText('slas_id') . "</th>"; echo "<td class='nopadding'>" . $tt->getBeginHiddenFieldValue($sltField); Slt::dropdown(array('name' => $sltField, 'entity' => $ticket->fields["entities_id"], 'value' => isset($ticket->fields[$sltField]) ? $ticket->fields[$sltField] : 0, 'condition' => "`type` = '" . $type . "'")); echo $tt->getEndHiddenFieldValue($sltField, $ticket); echo "</td>"; } } echo "</tr>"; echo "</table>"; }
/** show GANTT diagram for a project or for all * * @param $ID ID of the project or -1 for all projects */ static function showGantt($ID) { global $DB; if ($ID > 0) { $project = new Project(); if ($project->getFromDB($ID) && $project->canView()) { $todisplay = static::getDataToDisplayOnGantt($ID); } else { return false; } } else { $todisplay = array(); // Get all root projects $query = "SELECT *\n FROM `glpi_projects`\n WHERE `projects_id` = '0'\n AND `show_on_global_gantt` = '1'\n " . getEntitiesRestrictRequest("AND", 'glpi_projects', "", '', true); foreach ($DB->request($query) as $data) { $todisplay += static::getDataToDisplayOnGantt($data['id'], false); } ksort($todisplay); } $data = array(); $invalid = array(); if (count($todisplay)) { // Prepare for display foreach ($todisplay as $key => $val) { if (!empty($val['from']) && !empty($val['to'])) { $temp = array(); $color = 'ganttRed'; if ($val['percent'] > 50) { $color = 'ganttOrange'; } if ($val['percent'] == 100) { $color = 'ganttGreen'; } switch ($val['type']) { case 'project': $temp = array('name' => $val['link'], 'desc' => '', 'values' => array(array('from' => "/Date(" . strtotime($val['from']) . "000)/", 'to' => "/Date(" . strtotime($val['to']) . "000)/", 'desc' => $val['desc'], 'label' => $val['percent'] . "%", 'customClass' => $color))); break; case 'task': if (isset($val['is_milestone']) && $val['is_milestone']) { $color = 'ganttMilestone'; } $temp = array('name' => ' ', 'desc' => str_repeat('-', $val['parents']) . $val['link'], 'values' => array(array('from' => "/Date(" . strtotime($val['from']) . "000)/", 'to' => "/Date(" . strtotime($val['to']) . "000)/", 'desc' => $val['desc'], 'label' => strlen($val['percent'] == 0) ? '' : $val['percent'] . "%", 'customClass' => $color))); break; } $data[] = $temp; } else { $invalid[] = $val['link']; } } // Html::printCleanArray($data); } if (count($invalid)) { echo sprintf(__('Invalid items (no start or end date): %s'), implode(',', $invalid)); echo "<br><br>"; } if (count($data)) { $months = array(__('January'), __('February'), __('March'), __('April'), __('May'), __('June'), __('July'), __('August'), __('September'), __('October'), __('November'), __('December')); $dow = array(Toolbox::substr(__('Sunday'), 0, 1), Toolbox::substr(__('Monday'), 0, 1), Toolbox::substr(__('Tuesday'), 0, 1), Toolbox::substr(__('Wednesday'), 0, 1), Toolbox::substr(__('Thursday'), 0, 1), Toolbox::substr(__('Friday'), 0, 1), Toolbox::substr(__('Saturday'), 0, 1)); echo "<div class='gantt'></div>"; $js = "\n \$('.gantt').gantt({\n source: " . json_encode($data) . ",\n navigate: 'scroll',\n maxScale: 'months',\n itemsPerPage: 20,\n months: " . json_encode($months) . ",\n dow: " . json_encode($dow) . ",\n onItemClick: function(data) {\n // alert('Item clicked - show some details');\n },\n onAddClick: function(dt, rowId) {\n // alert('Empty space clicked - add an item!');\n },\n });"; echo Html::scriptBlock($js); } else { _e('No item to display'); } }
/** form for Task * * @param $ID Integer : Id of the task * @param $options array * - parent Object : the object **/ function showForm($ID, $options = array()) { global $DB, $CFG_GLPI; if (isset($options['parent']) && !empty($options['parent'])) { $item = $options['parent']; } $fkfield = $item->getForeignKeyField(); if ($ID > 0) { $this->check($ID, READ); } else { // Create item $options[$fkfield] = $item->getField('id'); $this->check(-1, CREATE, $options); } $rand = mt_rand(); $this->showFormHeader($options); $canplan = !$item->isStatusExists(CommonITILObject::PLANNED) || $item->isAllowedStatus($item->fields['status'], CommonITILObject::PLANNED); $rowspan = 3; if ($this->maybePrivate()) { $rowspan++; } if (isset($this->fields["state"])) { $rowspan++; } echo "<tr class='tab_bg_1'>"; echo "<td rowspan='{$rowspan}' class='middle'>" . __('Description') . "</td>"; echo "<td class='center middle' rowspan='{$rowspan}'>" . "<textarea id ='content{$rand}' name='content' cols='50' rows='{$rowspan}'>" . $this->fields["content"] . "</textarea>"; echo Html::scriptBlock("\$(document).ready(function() { \$('#content{$rand}').autogrow(); });"); echo "</td>"; if ($ID > 0) { echo "<td>" . __('Date') . "</td>"; echo "<td>"; Html::showDateTimeField("date", array('value' => $this->fields["date"], 'timestep' => 1, 'maybeempty' => false)); } else { echo "<td colspan='2'> "; } echo "<input type='hidden' name='{$fkfield}' value='" . $this->fields[$fkfield] . "'>"; echo "</td></tr>\n"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Category') . "</td><td>"; TaskCategory::dropdown(array('value' => $this->fields["taskcategories_id"], 'entity' => $item->fields["entities_id"])); echo "</td></tr>\n"; if (isset($this->fields["state"])) { echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Status') . "</td><td>"; Planning::dropdownState("state", $this->fields["state"]); echo "</td></tr>\n"; } if ($this->maybePrivate()) { echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Private') . "</td>"; echo "<td>"; Dropdown::showYesNo('is_private', $this->fields["is_private"]); echo "</td>"; echo "</tr>"; } echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Duration') . "</td><td>"; $toadd = array(); for ($i = 9; $i <= 100; $i++) { $toadd[] = $i * HOUR_TIMESTAMP; } Dropdown::showTimeStamp("actiontime", array('min' => 0, 'max' => 8 * HOUR_TIMESTAMP, 'value' => $this->fields["actiontime"], 'addfirstminutes' => true, 'inhours' => true, 'toadd' => $toadd)); echo "</td></tr>\n"; Document_Item::showSimpleAddForItem($item); echo "<tr class='tab_bg_1'>"; echo "<td>" . __('By'); echo " <a href='#' onClick=\"" . Html::jsGetElementbyID('planningcheck' . $rand) . ".dialog('open');\">"; echo "<img src='" . $CFG_GLPI["root_doc"] . "/pics/reservation-3.png'\n title=\"" . __s('Availability') . "\" alt=\"" . __s('Availability') . "\"\n class='calendrier'>"; echo "</a>"; Ajax::createIframeModalWindow('planningcheck' . $rand, $CFG_GLPI["root_doc"] . "/front/planning.php?checkavailability=checkavailability" . "&itemtype=" . $item->getType() . "&{$fkfield}=" . $item->getID(), array('title' => __('Availability'))); echo "</td>"; echo "<td class='center'>"; $rand_user = mt_rand(); $params = array('name' => "users_id_tech", 'value' => $this->fields["users_id_tech"] ? $this->fields["users_id_tech"] : Session::getLoginUserID(), 'right' => "own_ticket", 'rand' => $rand_user, 'entity' => $item->fields["entities_id"]); $params['toupdate'] = array('value_fieldname' => 'users_id', 'to_update' => "user_available{$rand_user}", 'url' => $CFG_GLPI["root_doc"] . "/ajax/planningcheck.php"); User::dropdown($params); echo "</td>\n"; if ($canplan) { echo "<td>" . __('Planning') . "</td>"; } echo "<td>"; if (!empty($this->fields["begin"])) { if (Session::haveRight('planning', Planning::READMY)) { echo "<script type='text/javascript' >\n"; echo "function showPlan" . $ID . "() {\n"; echo Html::jsHide('plan'); $params = array('form' => 'followups', 'users_id' => $this->fields["users_id_tech"], 'id' => $this->fields["id"], 'begin' => $this->fields["begin"], 'end' => $this->fields["end"], 'rand_user' => $rand_user, 'entity' => $item->fields["entities_id"], 'itemtype' => $this->getType(), 'items_id' => $this->getID()); Ajax::updateItemJsCode('viewplan', $CFG_GLPI["root_doc"] . "/ajax/planning.php", $params); echo "}"; echo "</script>\n"; echo "<div id='plan' onClick='showPlan" . $ID . "()'>\n"; echo "<span class='showplan'>"; } if (isset($this->fields["state"])) { echo Planning::getState($this->fields["state"]) . "<br>"; } printf(__('From %1$s to %2$s'), Html::convDateTime($this->fields["begin"]), Html::convDateTime($this->fields["end"])); echo "<br>" . getUserName($this->fields["users_id_tech"]); if (Session::haveRight('planning', Planning::READMY)) { echo "</span>"; echo "</div>\n"; echo "<div id='viewplan'></div>\n"; } } else { if ($canplan) { echo "<script type='text/javascript' >\n"; echo "function showPlanUpdate() {\n"; echo Html::jsHide('plan'); $params = array('form' => 'followups', 'entity' => $_SESSION["glpiactive_entity"], 'rand_user' => $rand_user, 'itemtype' => $this->getType(), 'items_id' => $this->getID()); Ajax::updateItemJsCode('viewplan', $CFG_GLPI["root_doc"] . "/ajax/planning.php", $params); echo "};"; echo "</script>"; if ($canplan) { echo "<div id='plan' onClick='showPlanUpdate()'>\n"; echo "<span class='vsubmit'>" . __('Plan this task') . "</span>"; echo "</div>\n"; echo "<div id='viewplan'></div>\n"; } } else { _e('None'); } } echo "</td></tr>"; if (!empty($this->fields["begin"]) && PlanningRecall::isAvailable()) { echo "<tr class='tab_bg_1'><td>" . _x('Planning', 'Reminder') . "</td><td class='center'>"; PlanningRecall::dropdown(array('itemtype' => $this->getType(), 'items_id' => $this->getID())); echo "</td></tr>"; } $this->showFormButtons($options); return true; }
static function showLockIcon($itemtype) { global $PLUGIN_HOOKS; if (isset($_GET['id']) && $_GET['id'] > 0) { $pfLock = new self(); $a_locks = $pfLock->getLockFields(getTableForItemType($itemtype), $_GET['id']); foreach ($a_locks as $field) { $js = '$("input[name=' . $field . ']").closest("td").prev().toggleClass("lockfield", true);'; echo Html::scriptBlock($js); } } }
/** * Create Ajax Tabs apply to 'tabspanel' div. Content is displayed in 'tabcontent' * * @param $tabdiv_id ID of the div containing the tabs (default 'tabspanel') * @param $tabdivcontent_id ID of the div containing the content loaded by tabs * (default 'tabcontent') * @param $tabs array of tabs to create : * tabs is array('key' => array('title'=> 'x', * url => 'url_toload', * params => 'url_params')... * @param $type itemtype for active tab * @param $ID ID of element for active tab (default 0) * @param $orientation orientation of tabs (default vertical may also be horizontal) * * @return nothing **/ static function createTabs($tabdiv_id = 'tabspanel', $tabdivcontent_id = 'tabcontent', $tabs = array(), $type, $ID = 0, $orientation = 'vertical') { global $CFG_GLPI; /// TODO need to clean params !! $active_tabs = Session::getActiveTab($type); $rand = mt_rand(); if (count($tabs) > 0) { echo "<div id='tabs{$rand}' class='center {$orientation}'>"; if (in_array($_SESSION['glpilayout'], array('classic', 'vsplit'))) { $orientation = 'horizontal'; } echo "<ul>"; $current = 0; $selected_tab = 0; foreach ($tabs as $key => $val) { if ($key == $active_tabs) { $selected_tab = $current; } echo "<li><a title=\"" . str_replace(array("<sup class='tab_nb'>", '</sup>'), '', $val['title']) . "\" "; echo " href='" . $val['url'] . (isset($val['params']) ? '?' . $val['params'] : '') . "'>"; // extract sup information // $title = ''; // $limit = 16; // No title strip for horizontal menu // if ($orientation == 'vertical') { // if (preg_match('/(.*)(<sup>.*<\/sup>)/',$val['title'], $regs)) { // $title = Html::resume_text(trim($regs[1]),$limit-2).$regs[2]; // } else { // $title = Html::resume_text(trim($val['title']),$limit); // } // } else { $title = $val['title']; // } echo $title . "</a></li>"; $current++; } echo "</ul>"; echo "</div>"; echo "<div id='loadingtabs{$rand}' class='invisible'>" . "<div class='loadingindicator'>" . __s('Loading...') . "</div></div>"; $js = "\$('#tabs{$rand}').tabs({ active: {$selected_tab},\n // Loading indicator\n beforeLoad: function (event, ui) {\n ui.panel.html(\$('#loadingtabs{$rand}').html());\n },\n ajaxOptions: {type: 'POST'},\n\n activate : function( event, ui ){\n // Get future value\n var newIndex = ui.newTab.parent().children().index(ui.newTab);\n \$.get('" . $CFG_GLPI['root_doc'] . "/ajax/updatecurrenttab.php',\n { itemtype: '{$type}', id: '{$ID}', tab: newIndex });\n }});"; if ($orientation == 'vertical') { $js .= "\$('#tabs{$rand}').tabs().addClass( 'ui-tabs-vertical ui-helper-clearfix' );"; } if (in_array($_SESSION['glpilayout'], array('classic', 'vsplit'))) { $js .= "\$('#tabs{$rand}').scrollabletabs();"; } else { $js .= "\$('#tabs{$rand}').removeClass( 'ui-corner-top' ).addClass( 'ui-corner-left' );"; } $js .= "// force reload\n function reloadTab(add) {\n\n var current_index = \$('#tabs{$rand}').tabs('option','active');\n // Save tab\n currenthref = \$('#tabs{$rand} ul>li a').eq(current_index).attr('href');\n \$('#tabs{$rand} ul>li a').eq(current_index).attr('href',currenthref+'&'+add);\n \$('#tabs{$rand}').tabs( 'load' , current_index);\n // Restore tab\n \$('#tabs{$rand} ul>li a').eq(current_index).attr('href',currenthref);\n };"; echo Html::scriptBlock($js); } }
/** * Print the HTML ajax associated item add * * @param $ticket Ticket object * @param $options array of possible options: * - id : ID of the ticket * - _users_id_requester : ID of the requester user * - items_id : array of elements (itemtype => array(id1, id2, id3, ...)) * * @return Nothing (display) **/ static function itemAddForm(Ticket $ticket, $options = array()) { global $CFG_GLPI; $params = array('id' => isset($ticket->fields['id']) && $ticket->fields['id'] != '' ? $ticket->fields['id'] : 0, '_users_id_requester' => 0, 'items_id' => array(), 'itemtype' => ''); $opt = array(); foreach ($options as $key => $val) { if (!empty($val)) { $params[$key] = $val; } } if (!$ticket->can($params['id'], READ)) { return false; } $canedit = $ticket->can($params['id'], UPDATE); // Ticket update case if ($params['id'] > 0) { // Get requester $class = new $ticket->userlinkclass(); $tickets_user = $class->getActors($params['id']); if (isset($tickets_user[CommonITILActor::REQUESTER]) && count($tickets_user[CommonITILActor::REQUESTER]) == 1) { foreach ($tickets_user[CommonITILActor::REQUESTER] as $user_id_single) { $params['_users_id_requester'] = $user_id_single['users_id']; } } // Get associated elements for ticket $used = self::getUsedItems($params['id']); foreach ($used as $itemtype => $items) { foreach ($items as $items_id) { if (!isset($params['items_id'][$itemtype]) || !in_array($items_id, $params['items_id'][$itemtype])) { $params['items_id'][$itemtype][] = $items_id; } } } } // Get ticket template $tt = new TicketTemplate(); if (isset($options['_tickettemplate'])) { $tt = $options['_tickettemplate']; if (isset($tt->fields['id'])) { $opt['templates_id'] = $tt->fields['id']; } } else { if (isset($options['templates_id'])) { $tt->getFromDBWithDatas($options['templates_id']); if (isset($tt->fields['id'])) { $opt['templates_id'] = $tt->fields['id']; } } } $rand = mt_rand(); $count = 0; echo "<div id='itemAddForm{$rand}'>"; // Show associated item dropdowns if ($canedit) { echo "<div style='float:left'>"; $p = array('used' => $params['items_id'], 'rand' => $rand, 'tickets_id' => $params['id']); // My items if ($params['_users_id_requester'] > 0) { Item_Ticket::dropdownMyDevices($params['_users_id_requester'], $ticket->fields["entities_id"], $params['itemtype'], 0, $p); } // Global search Item_Ticket::dropdownAllDevices("itemtype", $params['itemtype'], 0, 1, $params['_users_id_requester'], $ticket->fields["entities_id"], $p); echo "<span id='item_ticket_selection_information'></span>"; echo "</div>"; // Add button echo "<a href='javascript:itemAction{$rand}(\"add\");' class='vsubmit' style='float:left'>" . _sx('button', 'Add') . "</a>"; } // Display list echo "<div style='clear:both;'>"; if (!empty($params['items_id'])) { // No delete if mandatory and only one item $delete = true; $cpt = 0; foreach ($params['items_id'] as $itemtype => $items) { foreach ($items as $items_id) { $cpt++; } } if ($cpt == 1 && isset($tt->mandatory['items_id'])) { $delete = false; } foreach ($params['items_id'] as $itemtype => $items) { foreach ($items as $items_id) { if ($count < 5 && $params['id'] || $params['id'] == 0) { echo Item_Ticket::showItemToAdd($params['id'], $itemtype, $items_id, array('rand' => $rand, 'delete' => $delete)); } $count++; } } } if ($count == 0) { echo "<input type='hidden' value='0' name='items_id'>"; } if ($params['id'] > 0 && $count > 5) { echo "<i><a href='" . $ticket->getFormURL() . "?id=" . $params['id'] . "&forcetab=Item_Ticket\$1'>" . __('Display all items') . " (" . $count . ")</a></i>"; } echo "</div>"; foreach (array('id', '_users_id_requester', 'items_id', 'itemtype') as $key) { $opt[$key] = $params[$key]; } $js = " function itemAction{$rand}(action, itemtype, items_id) {"; $js .= " \$.ajax({\n url: '" . $CFG_GLPI['root_doc'] . "/ajax/itemTicket.php',\n dataType: 'html',\n data: {'action' : action,\n 'rand' : {$rand},\n 'params' : " . json_encode($opt) . ",\n 'my_items' : \$('#dropdown_my_items{$rand}').val(),\n 'itemtype' : (itemtype === undefined) ? \$('#dropdown_itemtype{$rand}').val() : itemtype,\n 'items_id' : (items_id === undefined) ? \$('#dropdown_add_items_id{$rand}').val() : items_id},\n success: function(response) {"; $js .= " \$(\"#itemAddForm{$rand}\").html(response);"; $js .= " }"; $js .= " });"; $js .= " }"; echo Html::scriptBlock($js); echo "</div>"; }
/** * Print the config form for default user prefs * * @param $data array containing datas * (CFG_GLPI for global config / glpi_users fields for user prefs) * * @return Nothing (display) **/ function showFormUserPrefs($data = array()) { global $DB, $CFG_GLPI; $oncentral = $_SESSION["glpiactiveprofile"]["interface"] == "central"; $userpref = false; $url = Toolbox::getItemTypeFormURL(__CLASS__); if (array_key_exists('last_login', $data)) { $userpref = true; if ($data["id"] === Session::getLoginUserID()) { $url = $CFG_GLPI['root_doc'] . "/front/preference.php"; } else { $url = $CFG_GLPI['root_doc'] . "/front/user.form.php"; } } echo "<form name='form' action='{$url}' method='post'>"; // Only set id for user prefs if ($userpref) { echo "<input type='hidden' name='id' value='" . $data['id'] . "'>"; } echo "<div class='center' id='tabsbody'>"; echo "<table class='tab_cadre_fixe'>"; echo "<tr><th colspan='4'>" . __('Personalization') . "</th></tr>"; echo "<tr class='tab_bg_2'>"; echo "<td width='30%'>" . ($userpref ? __('Language') : __('Default language')) . "</td>"; echo "<td width='20%'>"; if (Config::canUpdate() || !GLPI_DEMO_MODE) { Dropdown::showLanguages("language", array('value' => $data["language"])); } else { echo " "; } echo "<td width='30%'>" . __('Date format') . "</td>"; echo "<td width='20%'>"; $date_formats = array(0 => __('YYYY-MM-DD'), 1 => __('DD-MM-YYYY'), 2 => __('MM-DD-YYYY')); Dropdown::showFromArray('date_format', $date_formats, array('value' => $data["date_format"])); echo "</td></tr>"; echo "<tr class='tab_bg_2'>"; echo "<td>" . __('Results to display by page') . "</td><td>"; // Limit using global config $value = $data['list_limit'] < $CFG_GLPI['list_limit_max'] ? $data['list_limit'] : $CFG_GLPI['list_limit_max']; Dropdown::showNumber('list_limit', array('value' => $value, 'min' => 5, 'max' => $CFG_GLPI['list_limit_max'], 'step' => 5)); echo "</td>"; echo "<td>" . __('Number format') . "</td>"; $values = array(0 => '1 234.56', 1 => '1,234.56', 2 => '1 234,56', 3 => '1234.56', 4 => '1234,56'); echo "<td>"; Dropdown::showFromArray('number_format', $values, array('value' => $data["number_format"])); echo "</td></tr>"; echo "<tr class='tab_bg_2'>"; echo "<td>" . __('Display order of surnames firstnames') . "</td><td>"; $values = array(User::REALNAME_BEFORE => __('Surname, First name'), User::FIRSTNAME_BEFORE => __('First name, Surname')); Dropdown::showFromArray('names_format', $values, array('value' => $data["names_format"])); echo "</td>"; echo "<td>" . __("Color palette") . "</td><td>"; $themes_files = scandir(GLPI_ROOT . "/css/palettes/"); echo "<select name='palette' id='theme-selector'>"; foreach ($themes_files as $key => $file) { if (strpos($file, ".css") !== false) { $name = substr($file, 0, -4); $selected = ""; if ($data["palette"] == $name) { $selected = "selected='selected'"; } echo "<option value='{$name}' {$selected}>" . ucfirst($name) . "</option>"; } } echo Html::scriptBlock("\n function formatThemes(theme) {\n return \" <img src='../css/palettes/previews/\" + theme.text.toLowerCase() + \".png'/>\"\n + \" \" + theme.text;\n }\n \$(\"#theme-selector\").select2({\n formatResult: formatThemes,\n formatSelection: formatThemes,\n width: '100%',\n escapeMarkup: function(m) { return m; }\n });\n "); echo "</select>"; echo "</td></tr>"; echo "<tr class='tab_bg_2'>"; if ($oncentral) { echo "<td>" . __('Display the complete name in tree dropdowns') . "</td><td>"; Dropdown::showYesNo('use_flat_dropdowntree', $data["use_flat_dropdowntree"]); echo "</td>"; } else { echo "<td colspan='2'> </td>"; } if (!$userpref || $CFG_GLPI['show_count_on_tabs'] != -1) { echo "<td>" . __('Display counts in tabs') . "</td><td>"; $values = array(0 => __('No'), 1 => __('Yes')); if (!$userpref) { $values[-1] = __('Never'); } Dropdown::showFromArray('show_count_on_tabs', $values, array('value' => $data["show_count_on_tabs"])); echo "</td>"; } else { echo "<td colspan='2'> </td>"; } echo "</tr>"; echo "<tr class='tab_bg_2'>"; if ($oncentral) { echo "<td>" . __('Show GLPI ID') . "</td><td>"; Dropdown::showYesNo("is_ids_visible", $data["is_ids_visible"]); echo "</td>"; } else { echo "<td colspan='2'></td>"; } echo "<td>" . __('CSV delimiter') . "</td><td>"; $values = array(';' => ';', ',' => ','); Dropdown::showFromArray('csv_delimiter', $values, array('value' => $data["csv_delimiter"])); echo "</td></tr>"; echo "<tr class='tab_bg_2'>"; echo "<td>" . __('Notifications for my changes') . "</td><td>"; Dropdown::showYesNo("notification_to_myself", $data["notification_to_myself"]); echo "</td>"; if ($oncentral) { echo "<td>" . __('Results to display on home page') . "</td><td>"; Dropdown::showNumber('display_count_on_home', array('value' => $data['display_count_on_home'], 'min' => 0, 'max' => 30)); echo "</td>"; } else { echo "<td colspan='2'> </td>"; } echo "</tr>"; echo "<tr class='tab_bg_2'>"; echo "<td>" . __('PDF export font') . "</td><td>"; Dropdown::showFromArray("pdffont", GLPIPDF::getFontList(), array('value' => $data["pdffont"], 'width' => 200)); echo "</td>"; echo "<td>" . __('Keep devices when purging an item') . "</td><td>"; Dropdown::showYesNo('keep_devices_when_purging_item', $data['keep_devices_when_purging_item']); echo "</td></tr>"; echo "<tr class='tab_bg_2'><td>" . __('Go to created item after creation') . "</td>"; echo "<td>"; Dropdown::showYesNo("backcreated", $data["backcreated"]); echo "</td>"; echo "<td>" . __('Layout') . "</td><td>"; $layout_options = array('lefttab' => __("Tabs on left"), 'classic' => __("Classic view"), 'vsplit' => __("Vertical split")); echo "<select name='layout' id='layout-selector'>"; foreach ($layout_options as $key => $name) { $selected = ""; if ($data["layout"] == $key) { $selected = "selected='selected'"; } echo "<option value='{$key}' {$selected}>" . ucfirst($name) . "</option>"; } echo Html::scriptBlock("\n function formatLayout(layout) {\n return \" <img src='../pics/layout_\" + layout.id.toLowerCase() + \".png'/>\"\n + \" \" + layout.text;\n }\n \$(\"#layout-selector\").select2({\n formatResult: formatLayout,\n formatSelection: formatLayout,\n escapeMarkup: function(m) { return m; }\n });\n "); echo "</select>"; echo "</td>"; echo "</tr>"; echo "<tr class='tab_bg_2'><td>" . __('Enable ticket timeline') . "</td>"; echo "<td>"; Dropdown::showYesNo('ticket_timeline', $data['ticket_timeline']); echo "</td>"; echo "<td>" . __('Keep tabs replaced by the ticket timeline') . "</td><td>"; Dropdown::showYesNo('ticket_timeline_keep_replaced_tabs', $data['ticket_timeline_keep_replaced_tabs']); echo "</td></tr>"; if ($oncentral) { echo "<tr class='tab_bg_1'><th colspan='4'>" . __('Assistance') . "</th></tr>"; echo "<tr class='tab_bg_2'>"; echo "<td>" . __('Private followups by default') . "</td><td>"; Dropdown::showYesNo("followup_private", $data["followup_private"]); echo "</td><td>" . __('Show new tickets on the home page') . "</td><td>"; if (Session::haveRightsOr("ticket", array(Ticket::READMY, Ticket::READALL, Ticket::READASSIGN))) { Dropdown::showYesNo("show_jobs_at_login", $data["show_jobs_at_login"]); } else { echo Dropdown::getYesNo(0); } echo " </td></tr>"; echo "<tr class='tab_bg_2'><td>" . __('Private tasks by default') . "</td><td>"; Dropdown::showYesNo("task_private", $data["task_private"]); echo "</td><td> " . __('Request sources by default') . "</td><td>"; RequestType::dropdown(array('value' => $data["default_requesttypes_id"], 'name' => "default_requesttypes_id")); echo "</td></tr>"; echo "<tr class='tab_bg_2'><td>" . __('Tasks state by default') . "</td><td>"; Planning::dropdownState("task_state", $data["task_state"]); echo "</td><td colspan='2'> </td></tr>"; echo "<tr class='tab_bg_2'><td>" . __('Pre-select me as a technician when creating a ticket') . "</td><td>"; if (!$userpref || Session::haveRight('ticket', Ticket::OWN)) { Dropdown::showYesNo("set_default_tech", $data["set_default_tech"]); } else { echo Dropdown::getYesNo(0); } echo "</td><td>" . __('Automatically refresh the list of tickets (minutes)') . "</td><td>"; Dropdown::showNumber('refresh_ticket_list', array('value' => $data["refresh_ticket_list"], 'min' => 1, 'max' => 30, 'step' => 1, 'toadd' => array(0 => __('Never')))); echo "</td>"; echo "</tr>"; echo "<tr class='tab_bg_2'>"; echo "<td>" . __('Priority colors') . "</td>"; echo "<td colspan='3'>"; echo "<table><tr>"; echo "<td>1 "; Html::showColorField('priority_1', array('value' => $data["priority_1"])); echo "</td>"; echo "<td>2 "; Html::showColorField('priority_2', array('value' => $data["priority_2"])); echo "</td>"; echo "<td>3 "; Html::showColorField('priority_3', array('value' => $data["priority_3"])); echo "</td>"; echo "<td>4 "; Html::showColorField('priority_4', array('value' => $data["priority_4"])); echo "</td>"; echo "<td>5 "; Html::showColorField('priority_5', array('value' => $data["priority_5"])); echo "</td>"; echo "<td>6 "; Html::showColorField('priority_6', array('value' => $data["priority_6"])); echo "</td>"; echo "</tr></table>"; echo "</td></tr>"; } // Only for user if (array_key_exists('personal_token', $data)) { echo "<tr class='tab_bg_1'><th colspan='4'>" . __('Remote access key') . "</th></tr>"; echo "<tr class='tab_bg_1'><td>" . __('Remote access key'); if (!empty($data["personal_token"])) { //TRANS: %s is the generation date echo "<br>" . sprintf(__('generated on %s'), Html::convDateTime($data["personal_token_date"])); } echo "</td><td colspan='3'>"; echo "<input type='checkbox' name='_reset_personal_token'> " . __('Regenerate'); echo "</td></tr>"; } echo "<tr><th colspan='4'>" . __('Due date progression') . "</th></tr>"; echo "<tr class='tab_bg_1'>" . "<td>" . __('OK state color') . "</td>"; echo "<td>"; Html::showColorField('duedateok_color', array('value' => $data["duedateok_color"])); echo "</td><td colspan='2'> </td></tr>"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Warning state color') . "</td>"; echo "<td>"; Html::showColorField('duedatewarning_color', array('value' => $data["duedatewarning_color"])); echo "</td>"; echo "<td>" . __('Warning state threshold') . "</td>"; echo "<td>"; Dropdown::showNumber("duedatewarning_less", array('value' => $data['duedatewarning_less'])); $elements = array('%' => '%', 'hours' => _n('Hour', 'Hours', Session::getPluralNumber()), 'days' => _n('Day', 'Days', Session::getPluralNumber())); echo " "; Dropdown::showFromArray("duedatewarning_unit", $elements, array('value' => $data['duedatewarning_unit'])); echo "</td></tr>"; echo "<tr class='tab_bg_1'>" . "<td>" . __('Critical state color') . "</td>"; echo "<td>"; Html::showColorField('duedatecritical_color', array('value' => $data["duedatecritical_color"])); echo "</td>"; echo "<td>" . __('Critical state threshold') . "</td>"; echo "<td>"; Dropdown::showNumber("duedatecritical_less", array('value' => $data['duedatecritical_less'])); echo " "; $elements = array('%' => '%', 'hours' => _n('Hour', 'Hours', Session::getPluralNumber()), 'days' => _n('Day', 'Days', Session::getPluralNumber())); Dropdown::showFromArray("duedatecritical_unit", $elements, array('value' => $data['duedatecritical_unit'])); echo "</td></tr>"; echo "<tr class='tab_bg_2'>"; echo "<td colspan='4' class='center'>"; echo "<input type='submit' name='update' class='submit' value=\"" . _sx('button', 'Save') . "\">"; echo "</td></tr>"; echo "</table></div>"; Html::closeForm(); }
/** * Display types of used accounts * * @param $target target for type change action * * @return nothing */ public static function showSelector($target) { global $CFG_GLPI; $rand = mt_rand(); Plugin::loadLang('accounts'); echo "<div class='center' ><span class='b'>" . __('Select the wanted account type', 'accounts') . "</span><br>"; echo "<a style='font-size:14px;' href='" . $target . "?reset=reset' title=\"" . __s('Show all') . "\">" . str_replace(" ", " ", __('Show all')) . "</a></div>"; $js = "\$('#tree_projectcategory{$rand}').jstree({\n 'plugins' : ['themes', 'json_data', 'search'],\n 'core' : {'load_open': true,\n 'html_titles': true,\n 'animation' : 0},\n 'themes' : {\n 'theme' : 'classic',\n 'url' : '" . $CFG_GLPI["root_doc"] . "/css/jstree/style.css'\n },\n 'search' : {\n 'case_insensitive' : true,\n 'show_only_matches' : true,\n 'ajax' : {\n 'type': 'POST',\n 'url' : '" . $CFG_GLPI["root_doc"] . "/plugins/accounts/ajax/accounttreetypes.php'\n }\n },\n 'json_data' : {\n 'ajax' : {\n 'type': 'POST',\n 'url': function (node) {\n var nodeId = '';\n var url = '';\n if (node == -1) {\n url = '" . $CFG_GLPI["root_doc"] . "/plugins/accounts/ajax/accounttreetypes.php?node=-1';\n } else {\n nodeId = node.attr('id');\n url = '" . $CFG_GLPI["root_doc"] . "/plugins/accounts/ajax/accounttreetypes.php?node='+nodeId;\n }\n return url;\n },\n 'success': function (new_data) {\n return new_data;\n },\n 'progressive_render' : true\n }\n }\n });"; echo Html::scriptBlock($js); echo "<div class='left' style='width:100%'>"; echo "<div id='tree_projectcategory{$rand}'></div>"; echo "</div>"; }
/** * This function provides a mecanism to send html form by ajax * * @since version 9.1 **/ static function ajaxForm($selector, $success = "console.log(html);") { echo Html::scriptBlock("\n \$(document).ready(function() {\n var lastClicked = null;\n \$('input[type=submit]').click(function(e) {\n e = e || event;\n lastClicked = e.target || e.srcElement;\n });\n\n \$('{$selector}').on('submit', function(e) {\n e.preventDefault();\n var form = \$(this);\n var formData = form.closest('form').serializeArray();\n //push submit button\n formData.push({\n name: \$(lastClicked).attr('name'),\n value: \$(lastClicked).val()\n });\n\n \$.ajax({\n url: form.attr('action'),\n type: form.attr('method'),\n data: formData,\n success: function(html) {\n {$success}\n }\n });\n });\n });\n "); }
/** * Dropdown of values in an array * * @param $name select name * @param $elements array of elements to display * @param $options array of possible options: * - value : integer / preselected value (default 0) * - used : array / Already used items ID: not to display in dropdown (default empty) * - readonly : boolean / used as a readonly item (default false) * - on_change : string / value to transmit to "onChange" * - multiple : boolean / can select several values (default false) * - size : integer / number of rows for the select (default = 1) * - display : boolean / display or return string * - other : boolean or string if not false, then we can use an "other" value * if it is a string, then the default value will be this string * - rand : specific rand if needed (default is generated one) * - width : specific width needed (default not set) * - emptylabel : empty label if empty displayed (default self::EMPTY_VALUE) * - display_emptychoice : display empty choice (default false) * - tooltip : string / message to add as tooltip on the dropdown (default '') * - option_tooltips : array / message to add as tooltip on the dropdown options. Use the same keys as for the $elements parameter, but none is mandotary. Missing keys will just be ignored and no tooltip will be added. To add a tooltip on an option group, is the '__optgroup_label' key inside the array describing option tooltips : 'optgroupname1' => array('__optgroup_label' => 'tooltip for option group') (default empty) * * Permit to use optgroup defining items in arrays * array('optgroupname' => array('key1' => 'val1', * 'key2' => 'val2'), * 'optgroupname2' => array('key3' => 'val3', * 'key4' => 'val4')) **/ static function showFromArray($name, array $elements, $options = array()) { $param['value'] = ''; $param['values'] = array(''); $param['tooltip'] = ''; $param['option_tooltips'] = array(); $param['used'] = array(); $param['readonly'] = false; $param['on_change'] = ''; $param['width'] = ''; $param['multiple'] = false; $param['size'] = 1; $param['display'] = true; $param['other'] = false; $param['rand'] = mt_rand(); $param['emptylabel'] = self::EMPTY_VALUE; $param['display_emptychoice'] = false; if (is_array($options) && count($options)) { if (isset($options['value']) && strlen($options['value'])) { $options['values'] = array($options['value']); unset($options['value']); } foreach ($options as $key => $val) { $param[$key] = $val; } } if ($param['other'] !== false) { $other_select_option = $name . '_other_value'; $param['on_change'] .= "displayOtherSelectOptions(this, \"{$other_select_option}\");"; // If $param['other'] is a string, then we must highlight "other" option if (is_string($param['other'])) { if (!$param["multiple"]) { $param['values'] = array($other_select_option); } else { $param['values'][] = $other_select_option; } } } $param['option_tooltips'] = Html::entities_deep($param['option_tooltips']); if ($param["display_emptychoice"]) { $elements = array(0 => $param['emptylabel']) + $elements; } if ($param["multiple"]) { $field_name = $name . "[]"; } else { $field_name = $name; } $output = ''; // readonly mode $field_id = Html::cleanId("dropdown_" . $name . $param['rand']); if ($param['readonly']) { $to_display = array(); foreach ($param['values'] as $value) { $output .= "<input type='hidden' name='{$field_name}' value='{$value}'>"; if (isset($elements[$value])) { $to_display[] = $elements[$value]; } } $output .= implode('<br>', $to_display); } else { $output .= "<select name='{$field_name}' id='{$field_id}'"; if ($param['tooltip']) { $output .= ' title="' . Html::entities_deep($param['tooltip']) . '"'; } if (!empty($param["on_change"])) { $output .= " onChange='" . $param["on_change"] . "'"; } if (is_int($param["size"]) && $param["size"] > 0) { $output .= " size='" . $param["size"] . "'"; } if ($param["multiple"]) { $output .= " multiple"; } $output .= '>'; $max_option_size = 0; foreach ($elements as $key => $val) { // optgroup management if (is_array($val)) { $opt_goup = Html::entities_deep($key); if ($max_option_size < strlen($opt_goup)) { $max_option_size = strlen($opt_goup); } $output .= "<optgroup label=\"{$opt_goup}\""; $optgroup_tooltips = false; if (isset($param['option_tooltips'][$key])) { if (is_array($param['option_tooltips'][$key])) { if (isset($param['option_tooltips'][$key]['__optgroup_label'])) { $output .= ' title="' . $param['option_tooltips'][$key]['__optgroup_label'] . '"'; } $optgroup_tooltips = $param['option_tooltips'][$key]; } else { $output .= ' title="' . $param['option_tooltips'][$key] . '"'; } } $output .= ">"; foreach ($val as $key2 => $val2) { if (!isset($param['used'][$key2])) { $output .= "<option value='" . $key2 . "'"; // Do not use in_array : trouble with 0 and empty value foreach ($param['values'] as $value) { if (strcmp($key2, $value) === 0) { $output .= " selected"; break; } } if ($optgroup_tooltips && isset($optgroup_tooltips[$key2])) { $output .= ' title="' . $optgroup_tooltips[$key2] . '"'; } $output .= ">" . $val2 . "</option>"; if ($max_option_size < strlen($val2)) { $max_option_size = strlen($val2); } } } $output .= "</optgroup>"; } else { if (!isset($param['used'][$key])) { $output .= "<option value='" . $key . "'"; // Do not use in_array : trouble with 0 and empty value foreach ($param['values'] as $value) { if (strcmp($key, $value) === 0) { $output .= " selected"; break; } } if (isset($param['option_tooltips'][$key])) { $output .= ' title="' . $param['option_tooltips'][$key] . '"'; } $output .= ">" . $val . "</option>"; if ($max_option_size < strlen($val)) { $max_option_size = strlen($val); } } } } if ($param['other'] !== false) { $output .= "<option value='{$other_select_option}'"; if (is_string($param['other'])) { $output .= " selected"; } $output .= ">" . __('Other...') . "</option>"; } $output .= "</select>"; if ($param['other'] !== false) { $output .= "<input name='{$other_select_option}' id='{$other_select_option}' type='text'"; if (is_string($param['other'])) { $output .= " value=\"" . $param['other'] . "\""; } else { $output .= " style=\"display: none\""; } $output .= ">"; } } // Width set on select $output .= Html::jsAdaptDropdown($field_id, array('width' => $param["width"])); if ($param["multiple"]) { // Hack for All / None because select2 does not provide it $select = __('All'); $deselect = __('None'); $output .= "<div class='invisible' id='selectallbuttons_{$field_id}'>"; $output .= "<div class='select2-actionable-menu'>"; $output .= "<a class='vsubmit floatleft' " . "onclick=\"selectAll('{$field_id}');\$('#{$field_id}').select2('close');\">{$select}" . "</a> "; $output .= "<a class='vsubmit floatright' onclick=\"deselectAll('{$field_id}');\">{$deselect}" . "</a>"; $output .= "</div></div>"; $js = "\n var multichecksappend{$field_id} = false;\n \$('#{$field_id}').on('select2-open', function() {\n if (!multichecksappend{$field_id}) {\n \$('#select2-drop').append(\$('#selectallbuttons_{$field_id}').html());\n multichecksappend{$field_id} = true;\n }\n });"; $output .= Html::scriptBlock($js); } $output .= Ajax::commonDropdownUpdateItem($param, false); if ($param['display']) { echo $output; return $param['rand']; } return $output; }
public function showForm($ID, $options = array()) { global $CFG_GLPI; $this->initForm($ID, $options); $this->showFormHeader($options); echo '<table class="tab_cadre_fixe">'; echo "<tr class='line0 tab_bg_2'><td><label for='name'>" . __('Name') . " <span class='red'>*</span></label></td>"; echo "<td>"; echo '<input type="text" id="name" name="name" value="' . $this->fields['name'] . '" size="40" required>'; echo "</td>"; echo "</tr>"; echo "<tr class='line1 tab_bg_2'><td><label for='comment'>" . __('Description') . "</label></td>"; echo "<td>"; echo "<textarea name='comment' id ='comment' cols='45' rows='2'>" . $this->fields['comment'] . "</textarea>"; echo "</td>"; echo "</tr>"; echo "<tr class='line1 tab_bg_2'><td><label>" . __('HTML color', 'tag') . "</label></td>"; echo "<td>"; //Note : create some bugs Html::showColorField('color', array('value' => $this->fields['color'])); echo "</td>"; echo "</tr>"; echo "<tr class='line0 tab_bg_2'>"; echo "<td colspan='2'>"; echo "<table class='tab_cadre_fixe'>"; echo "<tr class='line1 tab_bg_2'>"; echo "<th>" . _n('Associated item type', 'Associated item types', 2) . "</th>"; echo "</tr>"; echo "<tr class='line1 tab_bg_2'>"; echo "<td class='center'>"; echo _n('Tag type', 'Tag types', 1, 'tag') . " "; $values = array(0 => Dropdown::EMPTY_VALUE); $menus = Html::getMenuInfos(); foreach ($menus as $key => $value) { if ($key != 'plugins' && $key != 'preference') { $values[$key] = $menus[$key]['title']; } } $rand = Dropdown::showFromArray("type_menu", $values, array('value' => $this->fields['type_menu'], 'width' => '50%', 'on_change' => 'pluginTagSubType();')); echo "<div id='plugin_tag_itemtype'></div><br>"; $JS = 'function pluginTagSubType(){'; $JS .= Ajax::updateItemJsCode('plugin_tag_itemtype', $CFG_GLPI['root_doc'] . "/plugins/tag/ajax/tag.php", array('action' => 'add_subtypes', 'type_menu' => '__VALUE__', 'rand' => $rand), "dropdown_type_menu{$rand}", false); $JS .= '}'; $JS .= 'pluginTagSubType();'; echo Html::scriptBlock($JS); // Sub type choice $itemtypes = array(); $selected = array(); if (!empty($this->fields['type_menu'])) { foreach (json_decode($this->fields['type_menu'], true) as $itemtype) { $item = getItemForItemtype($itemtype); $itemtypes[$itemtype] = $item->getTypeName(); $selected[] = $itemtype; } } Dropdown::showFromArray("subtypes", $itemtypes, array('values' => $selected, 'multiple' => true, 'rand' => $rand, 'width' => '100%')); echo "</td>"; echo "</tr>"; echo "</table>"; echo "</td>"; echo "</tr>"; $this->showFormButtons($options); return true; }
function showSummary($container) { global $DB, $CFG_GLPI; $cID = $container->fields['id']; // Display existing Fields $tmp = array('plugin_fields_containers_id' => $cID); $canadd = $this->can(-1, CREATE, $tmp); $query = "SELECT `id`, `label`\n FROM `" . $this->getTable() . "`\n WHERE `plugin_fields_containers_id` = '{$cID}'\n ORDER BY `ranking` ASC"; $result = $DB->query($query); $rand = mt_rand(); echo "<div id='viewField" . $cID . "{$rand}'></div>\n"; echo "<script type='text/javascript' >\n"; echo "function viewAddField" . $cID . "{$rand}() {\n"; $params = array('type' => __CLASS__, 'parenttype' => 'PluginFieldsContainer', 'plugin_fields_containers_id' => $cID, 'id' => -1); Ajax::updateItemJsCode("viewField" . $cID . "{$rand}", $CFG_GLPI["root_doc"] . "/ajax/viewsubitem.php", $params); echo "};"; echo "</script>\n"; echo "<div class='center'>" . "<a href='javascript:viewAddField" . $container->fields['id'] . "{$rand}();'>"; echo __("Add a new field", "fields") . "</a></div><br>\n"; if ($DB->numrows($result) == 0) { echo "<table class='tab_cadre_fixe'><tr class='tab_bg_2'>"; echo "<th class='b'>" . __("No field for this bloc", "fields") . "</th></tr></table>"; } else { echo '<div id="drag">'; echo '<input type="hidden" name="_plugin_fields_containers_id" id="plugin_fields_containers_id" value="' . $cID . '" />'; echo "<table class='tab_cadre_fixehov'>"; echo "<tr>"; echo "<th>" . __("Label") . "</th>"; echo "<th>" . __("Type") . "</th>"; echo "<th>" . __("Default values") . "</th>"; echo "<th>" . __("Mandatory field") . "</th>"; echo "<th>" . __("Active") . "</th>"; echo "<th>" . __("Read only", "fields") . "</th>"; echo "<th width='16'> </th>"; echo "</tr>\n"; $fields_type = self::getTypes(); while ($data = $DB->fetch_array($result)) { if ($this->getFromDB($data['id'])) { echo "<tr class='tab_bg_2' style='cursor:pointer' onClick=\"viewEditField{$cID}" . $this->fields['id'] . "{$rand}();\">"; echo "<td>"; echo "\n<script type='text/javascript' >\n"; echo "function viewEditField" . $cID . $this->fields["id"] . "{$rand}() {\n"; $params = array('type' => __CLASS__, 'parenttype' => 'PluginFieldsContainer', 'plugin_fields_containers_id' => $cID, 'id' => $this->fields["id"]); Ajax::updateItemJsCode("viewField" . $cID . "{$rand}", $CFG_GLPI["root_doc"] . "/ajax/viewsubitem.php", $params); echo "};"; echo "</script>\n"; echo $this->fields['label'] . "</td>"; echo "<td>" . $fields_type[$this->fields['type']] . "</td>"; echo "<td>" . $this->fields['default_value'] . "</td>"; echo "<td align='center'>" . Dropdown::getYesNo($this->fields["mandatory"]) . "</td>"; echo "<td align='center'>"; echo $this->fields['is_active'] == 1 ? __('Yes') : '<b class="red">' . __('No') . '</b>'; echo "</td>"; echo "<td>"; echo Dropdown::getYesNo($this->fields["is_readonly"]); echo "</td>"; echo '<td class="rowhandler control center">'; echo '<div class="drag row" style="cursor:move;border:none !important;">'; echo '<img src="../pics/drag.png" alt="#" title="Déplacer" width="16" height="16" />'; echo '</div>'; echo '</td>'; echo "</tr>\n"; } } } echo '</table>'; echo '</div>'; echo Html::scriptBlock('redipsInit()'); }
protected static final function showFormStatic($type, $type_id) { global $CFG_GLPI; if (!self::canItemStatic($type, $type_id, READ)) { return false; } $can_write = self::canItemStatic($type, $type_id, UPDATE); // lecture des données à afficher $current_rules = self::getFromDBStatic($type, $type_id); // racine de tous les identifiants du formulaire (doit être unique même dans le cas où plusieurs jeux de règles sont rassemblés sur la même page) $rootid = 'configmanager' . mt_rand(); // Entêtes du formulaire if ($can_write) { $form_id = $rootid . '_form'; echo '<form id="' . $form_id . '" action="' . PluginConfigmanagerRule::getFormURL() . '" method="post">'; } echo '<table class="tab_cadre_fixe">'; if (isset(self::getConfigParams()['_header']['text'])) { echo self::getConfigParams()['_header']['text']; } // Ligne de titres echo '<tr class="headerRow">'; foreach (self::getConfigParams() as $param => $desc) { if ($param[0] != '_') { $tooltip = isset($desc['tooltip']) ? ' title="' . $desc['tooltip'] . '"' : ''; echo '<th' . $tooltip . '>' . $desc['text'] . '</th>'; } } echo '<th>' . __('Actions', 'configmanager') . '</th>'; echo '</tr>'; /* * Affichage des règles * $beforezero est un marqueur servant à suivre si on doit encore afficher les règles héritées. On l'initialise à vrai ssi il est possible qu'il y ait des règles à hériter, puis si on s'apperçoit qu'on est en train d'afficher des règles d'ordre >0 alors qu'on doit encore afficher les règles héritées, ça veut dire qu'il n'y en a pas. On glisse donc le message indiquant que les règles seraient là. Idem à la fin, pour le cas où toutes les règles ont un order<0 */ $table_id = $rootid . '_tbody'; echo '<tbody id="' . $table_id . '">'; $beforezero = isset(static::$inherit_order[array_search($type, static::$inherit_order) + 1]); foreach ($current_rules as $rule) { $can_write2 = $can_write && $rule['config__type'] == $type && $rule['config__type_id'] == $type_id; if ($rule['config__order'] > 0 && $beforezero && $rule['config__type'] == $type) { // afficher une ligne bidon pour indiquer l'emplacement des règles héritées s'il n'y a rien d'hérité $beforezero = false; echo self::makeFakeInheritRow(); } else { if ($rule['config__type'] != $type) { $beforezero = false; } } echo self::makeRuleTablerow($rule, $rootid, $can_write2); } if ($beforezero) { echo self::makeFakeInheritRow(); } echo '</tbody>'; if (isset(self::getConfigParams()['_pre_save']['text'])) { echo self::getConfigParams()['_pre_save']['text']; } // Affichage du 'bas de formulaire' (champs cachés et boutons) if ($can_write) { echo '<tr>'; echo '<td class="center"><a class="pointer" onclick="' . $rootid . '.addlast()"><img src="/pics/menu_add.png" title=""></a></td>'; echo '<td class="center" colspan="' . count(self::getConfigParams()) . '">'; echo '<input type="hidden" name="config__object_name" value="' . get_called_class() . '">'; echo '<input type="submit" name="update" value="' . _sx('button', 'Save') . '" class="submit">'; echo '</td></tr>'; } if (isset(self::getConfigParams()['_footer']['text'])) { echo self::getConfigParams()['_footer']['text']; } echo '</table>'; Html::closeForm(); // Préparation de données 'vides' pour une création $newidtag = self::NEW_ID_TAG; $newordertag = self::NEW_ORDER_TAG; $empty_rule = self::makeEmptyRule($type, $type_id); $empty_rule_html = self::makeRuleTablerow($empty_rule, $rootid, true); $empty_rule_html = preg_replace("@[\n\r]@", " ", $empty_rule_html); $empty_rule_html = preg_replace("@<script.*?</script>@", "", $empty_rule_html); $empty_rule_html = addslashes($empty_rule_html); // Préparation des données pour la suppression d'une règle $delete_rule_html = addslashes('<input type="hidden" name="delete_rules[]" value="' . $newidtag . '">'); echo Html::scriptBlock(<<<JS var {$rootid} = {}; \$(function() { var tableNode = document.getElementById('{$table_id}'); var formNode = document.getElementById('{$form_id}'); var rules = {}; //id=> order, dom (ne contient pas les 0) {$rootid} = { moveup : moveup, movedown : movedown, add : add, addlast : addlast, remove : remove, }; initialize(); /** * Initialisation du script : les règles sont 'scannées' pour pouvoir être manipulées facilement par la suite */ function initialize() { rows = tableNode.children; for (var i in rows) { var row = rows[i]; if(row.nodeType) { if(!row.id.match(/{$rootid}_rule_(\\d)/)) continue; id = row.id.match(/{$rootid}_rule_(\\d)/)[1]; orderDom = row.querySelector('[name\$="rules['+id+'][config__order]"]'); // orderDom.length == null ssi c'est une règle héritée if(orderDom) { rules[id] = { id : id, dom : row, order : parseInt(orderDom.value), }; } } } } /** * Déplace une règle vers le haut */ function moveup(id) { var current = rules[id]; var prev = null; //On recherche la règle précédente Object.keys(rules).forEach(function(rule_id) { rule = rules[rule_id]; if(rule.id === id) return; if(rules[rule_id].order < current.order && (prev === null || rules[rule_id].order > prev.order)) { prev = rule; } }); if(prev===null && current.order < 0) { // cas où il n'y a pas de précédent et qu'on est déjà avant les règles héritées return; } else if((prev===null || prev.order<0) && current.order>0) { // cas où on doit croiser les règles héritées Object.keys(rules).forEach(function(rule_id) { setOrder(rules[rule_id], rules[rule_id].order-1); }); setOrder(current, -1); if(prev) { tableNode.insertBefore(current.dom, prev.dom.nextSibling); } else { tableNode.insertBefore(current.dom, tableNode.firstElementChild); } } else { // cas où on ne croise qu'un règle var tmp = current.order setOrder(current, prev.order); setOrder(prev, tmp); tableNode.insertBefore(current.dom, prev.dom); } } /** * Déplace une règle vers le bas */ function movedown(id) { var current = rules[id]; var next = null; //On recherche la règle suivante Object.keys(rules).forEach(function(rule_id) { rule = rules[rule_id]; if(rule.id === id) return; if(rules[rule_id].order > current.order && (next === null || rules[rule_id].order < next.order)) { next = rule; } }); if(next===null && current.order > 0) { // cas où il n'y a pas de précédent et qu'on est déjà avant les règles héritées return; } else if((next===null || next.order>0) && current.order<0) { // cas où on doit croiser les règles héritées Object.keys(rules).forEach(function(rule_id) { setOrder(rules[rule_id], rules[rule_id].order+1); }); setOrder(current, 1); if(next) { tableNode.insertBefore(current.dom, next.dom); } else { tableNode.appendChild(current.dom); } } else { // cas où on ne croise qu'un règle var tmp = current.order setOrder(current, next.order); setOrder(next, tmp); tableNode.insertBefore(next.dom, current.dom); } } addcnt = 1; /** * Ajoute une règle juste après celle dont l'id est donné en argument */ function add(id) { var current = rules[id]; var template = '{$empty_rule_html}'; var newOrder = current.order<0?current.order:current.order+1; var newID = '{$newidtag}'+addcnt++; // Adaptation du modèle de ligne à notre cas particulier template = template.replace(/{$newidtag}/g, newID); template = template.replace(/{$newordertag}/g, newOrder); // Décalage des objets pour faire de la place au nouveau Object.keys(rules).forEach(function(rule_id) { rule = rules[rule_id]; if(newOrder>0 && rule.order>=newOrder) setOrder(rule, rule.order+1); if(newOrder<0 && rule.order<=newOrder) setOrder(rule, rule.order-1); }); // création du DOM du nouvel objet var tbody = document.createElement('tbody'); tbody.innerHTML = template; newRule = { id : newID, order : newOrder, dom : tbody.firstElementChild, }; rules[newID] = newRule; // Ajout de la nouvelle ligne juste après celle à partir de laquelle on a cliqué if(current.dom.nextSibling) { tableNode.insertBefore(newRule.dom, current.dom.nextSibling); } else { tableNode.appendChild(newRule.dom); } prettyDropdown(newRule.dom); } /** * Ajoute une règle en dernière position */ function addlast() { var newID = '{$newidtag}'+addcnt++; var newOrder = null; Object.keys(rules).forEach(function(rule_id) { rule = rules[rule_id]; if(newOrder === null || newOrder<rule.order) newOrder = rule.order; }); if(newOrder === null) newOrder = 1; else newOrder++; // Adaptation du modèle de ligne à notre cas particulier var template = '{$empty_rule_html}'; template = template.replace(/{$newidtag}/g, newID); template = template.replace(/{$newordertag}/g, newOrder); // création du DOM du nouvel objet var tbody = document.createElement('tbody'); tbody.innerHTML = template; newRule = { id : newID, order : newOrder, dom : tbody.firstElementChild, }; rules[newID] = newRule; tableNode.appendChild(newRule.dom); prettyDropdown(newRule.dom); } /** * Retire la règle dont l'id est donné en argument */ function remove(id) { var current = rules[id]; tableNode.removeChild(current.dom); // Ajout de l'input signalant la suppression d'une règle (seulement si règle existante côté serveur) if(!/<?php echo self::NEW_ID_TAG;?>\\d*/.test(id)) { var template = '{$delete_rule_html}'; template = template.replace(/{$newidtag}/g, id); var div = document.createElement('div'); div.innerHTML = template; formNode.appendChild(div.firstElementChild); } // Décalage des objets pour boucher le trou Object.keys(rules).forEach(function(rule_id) { rule = rules[rule_id]; if(current.order>0 && rule.order>current.order) setOrder(rule, rule.order-1); if(current.order<0 && rule.order<current.order) setOrder(rule, rule.order+1); }); delete rules[id]; } function setOrder(rule, order) { rule.order = order; tableNode.querySelector('[name\$="rules['+rule.id+'][config__order]"]').value = order; } /** * Transforms a simple dropdown into a jQuery select * Adapted from Html::jsAdaptDropdown & Dropdown::show (end of function) */ function prettyDropdown(dom) { console.log('coucou'); console.log(dom); \$('#'+dom.id+' select').each(function(test, toto) { console.log(test, toto); }); \$('#'+dom.id+' select').select2({ width: '100%', closeOnSelect: false, dropdownAutoWidth: true, quietMillis: 100, minimumResultsForSearch: '{$CFG_GLPI['ajax_limit_count']}', formatSelection: function(object, container) { text = object.text; if (object.element[0].parentElement.nodeName == 'OPTGROUP') { text = object.element[0].parentElement.getAttribute('label') + ' - ' + text; } return text; }, formatResult: function (result, container) { return \$('<div>', {title: result.title}).text(result.text); } }); \$('#'+dom.id+' select').each(function(i, el) { var multichecksappend = false; \$('#'+el.id).on('select2-open', function() { if (!multichecksappend) { \$('#select2-drop').append(\$('#selectallbuttons_'+el.id).html()); multichecksappend = true; } }); }); } }); JS ); }
static function showAddEventForm($params = array()) { global $CFG_GLPI; if (count($CFG_GLPI['planning_add_types']) == 1) { $params['itemtype'] = $CFG_GLPI['planning_add_types'][0]; self::showAddEventSubForm($params); } else { $rand = mt_rand(); $select_options = array(); foreach ($CFG_GLPI['planning_add_types'] as $add_types) { $select_options[$add_types] = $add_types::getTypeName(1); } echo __("Event type") . " : <br>"; Dropdown::showFromArray('itemtype', $select_options, array('display_emptychoice' => true, 'rand' => $rand)); echo Html::scriptBlock("\n \$(document).ready(function() {\n \$('#dropdown_itemtype{$rand}').on('change', function() {\n var current_itemtype = \$(this).val();\n \$('#add_planning_subform{$rand}').load('" . $CFG_GLPI['root_doc'] . "/ajax/planning.php',\n {action: 'add_event_sub_form',\n itemtype: current_itemtype,\n begin: '" . $params['begin'] . "',\n end: '" . $params['end'] . "'});\n });\n });"); echo "<br><br>"; echo "<div id='add_planning_subform{$rand}'></div>"; } }
/** * Show the current ticketfollowup summary * * @param $ticket Ticket object **/ function showSummary($ticket) { global $DB, $CFG_GLPI; if (!Session::haveRightsOr(self::$rightname, array(self::SEEPUBLIC, self::SEEPRIVATE))) { return false; } $tID = $ticket->fields['id']; // Display existing Followups $showprivate = Session::haveRight(self::$rightname, self::SEEPRIVATE); $caneditall = Session::haveRight(self::$rightname, self::UPDATEALL); $tmp = array('tickets_id' => $tID); $canadd = $this->can(-1, CREATE, $tmp); $showuserlink = 0; if (User::canView()) { $showuserlink = 1; } $techs = $ticket->getAllUsers(CommonITILActor::ASSIGN); $reopen_case = false; if (in_array($ticket->fields["status"], $ticket->getClosedStatusArray()) && $ticket->isAllowedStatus($ticket->fields['status'], Ticket::INCOMING)) { $reopen_case = true; } $tech = Session::haveRight(self::$rightname, self::ADDALLTICKET) || $ticket->isUser(CommonITILActor::ASSIGN, Session::getLoginUserID()) || isset($_SESSION["glpigroups"]) && $ticket->haveAGroup(CommonITILActor::ASSIGN, $_SESSION['glpigroups']); $RESTRICT = ""; if (!$showprivate) { $RESTRICT = " AND (`is_private` = '0'\n OR `users_id` ='" . Session::getLoginUserID() . "') "; } $query = "SELECT `glpi_ticketfollowups`.*, `glpi_users`.`picture`\n FROM `glpi_ticketfollowups`\n LEFT JOIN `glpi_users` ON (`glpi_ticketfollowups`.`users_id` = `glpi_users`.`id`)\n WHERE `tickets_id` = '{$tID}'\n {$RESTRICT}\n ORDER BY `date` DESC"; $result = $DB->query($query); $rand = mt_rand(); if ($caneditall || $canadd) { echo "<div id='viewfollowup" . $tID . "{$rand}'></div>\n"; } if ($canadd) { echo "<script type='text/javascript' >\n"; echo "function viewAddFollowup" . $ticket->fields['id'] . "{$rand}() {\n"; $params = array('type' => __CLASS__, 'parenttype' => 'Ticket', 'tickets_id' => $ticket->fields['id'], 'id' => -1); Ajax::updateItemJsCode("viewfollowup" . $ticket->fields['id'] . "{$rand}", $CFG_GLPI["root_doc"] . "/ajax/viewsubitem.php", $params); echo Html::jsHide('addbutton' . $ticket->fields['id'] . "{$rand}"); echo "};"; echo "</script>\n"; // Not closed ticket or closed if (!in_array($ticket->fields["status"], array_merge($ticket->getSolvedStatusArray(), $ticket->getClosedStatusArray())) || $reopen_case) { if (isset($_GET['_openfollowup']) && $_GET['_openfollowup']) { echo Html::scriptBlock("viewAddFollowup" . $ticket->fields['id'] . "{$rand}()"); } else { echo "<div id='addbutton" . $ticket->fields['id'] . "{$rand}' class='center firstbloc'>" . "<a class='vsubmit' href='javascript:viewAddFollowup" . $ticket->fields['id'] . "{$rand}();'>"; if ($reopen_case) { _e('Reopen the ticket'); } else { _e('Add a new followup'); } echo "</a></div>\n"; } } } if ($DB->numrows($result) == 0) { echo "<table class='tab_cadre_fixe'><tr class='tab_bg_2'>"; echo "<th class='b'>" . __('No followup for this ticket.') . "</th></tr></table>"; } else { $today = strtotime('today'); $lastmonday = strtotime('last monday'); $lastlastmonday = strtotime('last monday', strtotime('last monday')); // Case of monday if ($today - $lastmonday == 7 * DAY_TIMESTAMP) { $lastlastmonday = $lastmonday; $lastmonday = $today; } $steps = array(0 => array('end' => $today, 'name' => __('Today')), 1 => array('end' => $lastmonday, 'name' => __('This week')), 2 => array('end' => $lastlastmonday, 'name' => __('Last week')), 3 => array('end' => strtotime('midnight first day of'), 'name' => __('This month')), 4 => array('end' => strtotime('midnight first day of last month'), 'name' => __('Last month')), 5 => array('end' => 0, 'name' => __('Before the last month'))); $currentpos = -1; while ($data = $DB->fetch_assoc($result)) { $this->getFromDB($data['id']); $candelete = $this->canPurge() && $this->canPurgeItem(); $canedit = $this->canUpdate() && $this->canUpdateItem(); $time = strtotime($data['date']); if (!isset($steps[$currentpos]) || $steps[$currentpos]['end'] > $time) { $currentpos++; while ($steps[$currentpos]['end'] > $time && isset($steps[$currentpos + 1])) { $currentpos++; } if (isset($steps[$currentpos])) { echo "<h3>" . $steps[$currentpos]['name'] . "</h3>"; } } $id = 'followup' . $data['id'] . $rand; $color = 'byuser'; if (isset($techs[$data['users_id']])) { $color = 'bytech'; } $classtoadd = ''; if ($canedit) { $classtoadd = " pointer"; } echo "<div class='boxnote {$color}' id='view{$id}'"; echo ">"; echo "<div class='boxnoteleft'>"; echo "<img class='user_picture_verysmall' alt=\"" . __s('Picture') . "\" src='" . User::getThumbnailURLForPicture($data['picture']) . "'>"; echo "</div>"; // boxnoteleft echo "<div class='boxnotecontent'"; echo ">"; echo "<div class='boxnotefloatleft'>"; $username = NOT_AVAILABLE; if ($data['users_id']) { $username = getUserName($data['users_id'], $showuserlink); } $name = sprintf(__('Create by %1$s on %2$s'), $username, Html::convDateTime($data['date'])); if ($data['requesttypes_id']) { $name = sprintf(__('%1$s - %2$s'), $name, Dropdown::getDropdownName('glpi_requesttypes', $data['requesttypes_id'])); } if ($showprivate && $data["is_private"]) { $name = sprintf(__('%1$s - %2$s'), $name, __('Private')); } echo $name; echo "</div>"; // floatright echo "<div class='boxnotetext {$classtoadd}'"; if ($canedit) { echo " onClick=\"viewEditFollowup" . $ticket->fields['id'] . $data['id'] . "{$rand}(); " . Html::jsHide("view{$id}") . " " . Html::jsShow("viewfollowup" . $ticket->fields['id'] . $data["id"] . "{$rand}") . "\" "; } echo ">"; $content = nl2br($data['content']); if (empty($content)) { $content = NOT_AVAILABLE; } echo $content . '</div>'; // boxnotetext echo "</div>"; // boxnotecontent echo "<div class='boxnoteright'>"; if ($candelete) { Html::showSimpleForm(Toolbox::getItemTypeFormURL('TicketFollowup'), array('purge' => 'purge'), _x('button', 'Delete permanently'), array('id' => $data['id']), $CFG_GLPI["root_doc"] . "/pics/delete.png", '', __('Confirm the final deletion?')); } echo "</div>"; // boxnoteright echo "</div>"; // boxnote if ($canedit) { echo "<div id='viewfollowup" . $ticket->fields['id'] . $data["id"] . "{$rand}' class='starthidden'></div>\n"; echo "\n<script type='text/javascript' >\n"; echo "function viewEditFollowup" . $ticket->fields['id'] . $data["id"] . "{$rand}() {\n"; $params = array('type' => __CLASS__, 'parenttype' => 'Ticket', 'tickets_id' => $data["tickets_id"], 'id' => $data["id"]); Ajax::updateItemJsCode("viewfollowup" . $ticket->fields['id'] . $data["id"] . "{$rand}", $CFG_GLPI["root_doc"] . "/ajax/viewsubitem.php", $params); echo "};"; echo "</script>\n"; } } } }
/** * Show accounts associated to an item * * @since version 0.84 * * @param $item CommonDBTM object for which associated accounts 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 (!Session::haveRight("plugin_accounts", READ)) { return false; } if (!$item->can($item->fields['id'], READ)) { return false; } if (empty($withtemplate)) { $withtemplate = 0; } $canedit = $item->canadditem('PluginAccountsAccount'); $rand = mt_rand(); $is_recursive = $item->isRecursive(); $who = Session::getLoginUserID(); if (count($_SESSION["glpigroups"]) && Session::haveRight("plugin_accounts_my_groups", 1)) { $first_groups = true; $groups = ""; foreach ($_SESSION['glpigroups'] as $val) { if (!$first_groups) { $groups .= ","; } else { $first_groups = false; } $groups .= "'" . $val . "'"; } $ASSIGN = "( `groups_id` IN ({$groups}) OR `users_id` = '{$who}') "; } else { // Only personal ones $ASSIGN = " `users_id` = '{$who}' "; } $query = "SELECT `glpi_plugin_accounts_accounts_items`.`id` AS assocID,\n `glpi_entities`.`id` AS entity,\n `glpi_plugin_accounts_accounts`.`name` AS assocName,\n `glpi_plugin_accounts_accounts`.*\n FROM `glpi_plugin_accounts_accounts_items`\n LEFT JOIN `glpi_plugin_accounts_accounts`\n ON (`glpi_plugin_accounts_accounts_items`.`plugin_accounts_accounts_id`=`glpi_plugin_accounts_accounts`.`id`)\n LEFT JOIN `glpi_entities` ON (`glpi_plugin_accounts_accounts`.`entities_id`=`glpi_entities`.`id`)\n WHERE `glpi_plugin_accounts_accounts_items`.`items_id` = '{$ID}'\n AND `glpi_plugin_accounts_accounts_items`.`itemtype` = '" . $item->getType() . "' "; $query .= getEntitiesRestrictRequest(" AND", "glpi_plugin_accounts_accounts", '', '', true); if (!Session::haveRight("plugin_accounts_see_all_users", 1)) { $query .= " AND {$ASSIGN} "; } $query .= " ORDER BY `assocName`"; $result = $DB->query($query); $number = $DB->numrows($result); $i = 0; $accounts = array(); $account = new PluginAccountsAccount(); $used = array(); if ($numrows = $DB->numrows($result)) { while ($data = $DB->fetch_assoc($result)) { $accounts[$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_plugin_accounts_accounts", '', $entities, true); $q = "SELECT COUNT(*)\n FROM `glpi_plugin_accounts_accounts`\n WHERE `is_deleted` = '0'\n {$limit}"; $result = $DB->query($q); $nb = $DB->result($result, 0, 0); echo "<div class='firstbloc'>"; if (Session::haveRight('plugin_accounts', READ) && $nb > count($used)) { echo "<form name='account_form{$rand}' id='account_form{$rand}' method='post'\n action='" . Toolbox::getItemTypeFormURL('PluginAccountsAccount') . "'>"; 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}'>"; } PluginAccountsAccount::dropdownAccount(array('entity' => $entities, 'used' => $used)); echo "</td><td class='center' width='20%'>"; echo "<input type='submit' name='additem' value=\"" . _sx('button', 'Associate a account', 'accounts') . "\" 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($massiveactionparams); } echo "<table class='tab_cadre_fixe'>"; if (Session::isMultiEntitiesMode()) { $colsup = 1; } else { $colsup = 0; } //hash $hashclass = new PluginAccountsHash(); $hash = 0; $restrict = getEntitiesRestrictRequest(" ", "glpi_plugin_accounts_hashes", '', $item->getEntityID(), $hashclass->maybeRecursive()); $hashes = getAllDatasFromTable("glpi_plugin_accounts_hashes", $restrict); if (!empty($hashes)) { foreach ($hashes as $hashe) { $hash = $hashe["hash"]; $hash_id = $hashe["id"]; } $alert = ''; } else { $alert = __('There is no encryption key for this entity', 'accounts'); } $aeskey = new PluginAccountsAesKey(); echo "<tr><th colspan='" . (8 + $colsup) . "'>"; if ($hash) { if (!$aeskey->getFromDBByHash($hash_id) || !$aeskey->fields["name"]) { _e('Encryption key', 'accounts'); echo "<input type='password' name='aeskey' id='aeskey' autocomplete='off'>"; } else { echo Html::hidden('aeskey', array('value' => $aeskey->fields["name"], 'id' => 'aeskey', 'autocomplete' => 'off')); } } else { echo __('Encryption key', 'accounts'); echo "<div class='red'>"; echo $alert; echo "</div>"; } echo "<tr>"; if ($canedit && $number && $withtemplate < 2) { echo "<th width='10'>" . Html::getCheckAllAsCheckbox('mass' . __CLASS__ . $rand) . "</th>"; } echo "<th>" . __('Name') . "</th>"; if (Session::isMultiEntitiesMode()) { echo "<th>" . __('Entity') . "</th>"; } echo "<th>" . __('Login') . "</th>"; echo "<th>" . __('Password') . "</th>"; echo "<th>" . __('Affected User', 'accounts') . "</th>"; echo "<th>" . __('Type') . "</th>"; echo "<th>" . __('Creation date') . "</th>"; echo "<th>" . __('Expiration date') . "</th>"; echo "</tr>"; $used = array(); if ($number) { Session::initNavigateListItems('PluginAccountsAccount', sprintf(__('%1$s = %2$s'), $item->getTypeName(1), $item->getName())); foreach ($accounts as $data) { $accountID = $data["id"]; $link = NOT_AVAILABLE; if ($account->getFromDB($accountID)) { $link = $account->getLink(); } Session::addToNavigateListItems('PluginAccountsAccount', $accountID); $used[$accountID] = $accountID; $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>"; if (Session::isMultiEntitiesMode()) { echo "<td class='center'>" . Dropdown::getDropdownName("glpi_entities", $data['entities_id']) . "</td>"; } echo "<td class='center'>" . $data["login"] . "</td>"; echo "<td class='center'>"; //hash if (isset($hash_id) && $aeskey->getFromDBByHash($hash_id) && $aeskey->fields["name"]) { echo Html::hidden("encrypted_password{$accountID}", array('value' => $data["encrypted_password"], 'id' => "encrypted_password{$accountID}", 'autocomplete' => 'off')); echo "<input type='text' id='hidden_password{$accountID}' value='' size='30' >"; echo Html::scriptBlock("\n if (!check_hash()) {\n \$('#hidden_password{$accountID}')\n .after('" . __('Wrong encryption key', 'accounts') . "')\n .remove();\n } else {\n decrypt_password('{$accountID}');\n }\n "); } else { $url = $CFG_GLPI["root_doc"] . "/plugins/accounts/front/account.form.php"; echo " <input type='button' id='decrypt_link{$accountID}' name='decrypte' value='" . __s('Uncrypt', 'accounts') . "'\n class='submit'>"; echo Html::hidden("encrypted_password{$accountID}", array('value' => $data["encrypted_password"], 'id' => "encrypted_password{$accountID}", 'autocomplete' => 'off')); echo Html::scriptBlock("\$(document).on('click', '#decrypt_link{$accountID}', function(event) {\n if (!check_hash()) {\n alert('" . __('Wrong encryption key', 'accounts') . "');\n } else {\n var decrypted_password = decrypt_password('{$accountID}');\n \$('#decrypt_link{$accountID}')\n .after(decrypted_password)\n .remove();\n }\n });"); } echo "</td>"; echo "<td class='center'>"; echo getUsername($data["users_id"]); echo "</td>"; echo "<td class='center'>"; echo Dropdown::getDropdownName("glpi_plugin_accounts_accounttypes", $data["plugin_accounts_accounttypes_id"]); echo "</td>"; echo "<td class='center'>" . Html::convdate($data["date_creation"]) . "</td>"; if ($data["date_expiration"] <= date('Y-m-d') && !empty($data["date_expiration"])) { echo "<td class='center'>"; echo "<div class='deleted'>" . Html::convdate($data["date_expiration"]) . "</div>"; echo "</td>"; } else { if (empty($data["date_expiration"])) { echo "<td class='center'>" . __('Don\'t expire', 'accounts') . "</td>"; } else { echo "<td class='center'>" . Html::convdate($data["date_expiration"]) . "</td>"; } } echo "</tr>"; $i++; } } echo "</table>"; echo Html::hidden('good_hash', array('value' => $hash, 'id' => 'good_hash')); if ($canedit && $number && $withtemplate < 2) { $massiveactionparams['ontop'] = false; Html::showMassiveActions($massiveactionparams); Html::closeForm(); } echo "</div>"; }