Invert fonction from clean_cross_side_scripting_deep
static public unclean_cross_side_scripting_deep ( $value ) : unclean | ||
$value | array or string item to unclean from clean_cross_side_scripting_deep | |
return | unclean | item |
static function pdfMain(PluginPdfSimplePDF $pdf, KnowbaseItem $item) { global $DB; $ID = $item->getField('id'); if (!Session::haveRight('knowbase', 'r') || !Session::haveRight('faq', 'r')) { return false; } $knowbaseitemcategories_id = $item->getField('knowbaseitemcategories_id'); $fullcategoryname = Html::clean(getTreeValueCompleteName("glpi_knowbaseitemcategories", $knowbaseitemcategories_id)); $question = Html::clean(Toolbox::unclean_cross_side_scripting_deep(html_entity_decode($item->getField('name'), ENT_QUOTES, "UTF-8"))); $answer = Html::clean(Toolbox::unclean_cross_side_scripting_deep(html_entity_decode($item->getField('answer'), ENT_QUOTES, "UTF-8"))); $pdf->setColumnsSize(100); if (Toolbox::strlen($fullcategoryname) > 0) { $pdf->displayTitle('<b>' . __('Category name') . '</b>'); $pdf->displayLine($fullcategoryname); } if (Toolbox::strlen($question) > 0) { $pdf->displayTitle('<b>' . __('Subject') . '</b>'); $pdf->displayText('', $question, 5); } else { $pdf->displayTitle('<b>' . __('No question found', 'pdf') . '</b>'); } if (Toolbox::strlen($answer) > 0) { $pdf->displayTitle('<b>' . __('Content') . '</b>'); $pdf->displayText('', $answer, 5); } else { $pdf->displayTitle('<b>' . __('No answer found') . '</b>'); } $pdf->setColumnsSize(50, 15, 15, 10, 10); $pdf->displayTitle(__('Writer'), __('Creation date'), __('Last update'), __('FAQ'), _n('View', 'Views', 2)); $pdf->displayLine(getUserName($item->fields["users_id"]), Html::convDateTime($item->fields["date"]), Html::convDateTime($item->fields["date_mod"]), Dropdown::getYesNo($item->fields["is_faq"]), $item->fields["view"]); $pdf->displaySpace(); }
// Original Author of file: // Purpose of file: // ---------------------------------------------------------------------- //define('GLPI_ROOT', '../..'); //include (GLPI_ROOT . "/inc/includes.php"); include "../../inc/includes.php"; $common = new PluginMobileCommon(); define("MOBILE_EXTRANET_ROOT", "../../plugins/mobile"); $_POST = array_map('stripslashes', $_POST); //Do login and checks //$user_present = 1; if (!isset($_POST['login_name'])) { $_POST['login_name'] = ''; } if (isset($_POST['login_password'])) { $_POST['login_password'] = Toolbox::unclean_cross_side_scripting_deep($_POST['login_password']); } else { $_POST['login_password'] = ''; } // Redirect management $REDIRECT = ""; if (isset($_POST['redirect']) && strlen($_POST['redirect']) > 0) { $REDIRECT = "?redirect=" . $_POST['redirect']; } else { if (isset($_GET['redirect']) && strlen($_GET['redirect']) > 0) { $REDIRECT = "?redirect=" . $_GET['redirect']; } } $auth = new Auth(); // now we can continue with the process... if ($auth->Login($_POST['login_name'], $_POST['login_password'], isset($_REQUEST["noAUTO"]) ? $_REQUEST["noAUTO"] : false)) {
/** * Form to add a solution to an ITIL object * * @param $knowbase_id_toload integer load a kb article as solution (0 = no load by default) * (default 0) **/ function showSolutionForm($knowbase_id_toload = 0) { global $CFG_GLPI; $this->check($this->getField('id'), READ); $canedit = $this->canSolve(); $options = array(); if ($knowbase_id_toload > 0) { $kb = new KnowbaseItem(); if ($kb->getFromDB($knowbase_id_toload)) { $this->fields['solution'] = $kb->getField('answer'); } } // Alert if validation waiting $validationtype = $this->getType() . 'Validation'; if (method_exists($validationtype, 'alertValidation')) { $validationtype::alertValidation($this, 'solution'); } $this->showFormHeader($options); $show_template = $canedit; // && $this->getField('solutiontypes_id') == 0 // && empty($this->fields['solution']); $rand_template = mt_rand(); $rand_text = $rand_type = 0; if ($canedit) { $rand_text = mt_rand(); $rand_type = mt_rand(); } if ($show_template) { echo "<tr class='tab_bg_2'>"; echo "<td>" . _n('Solution template', 'Solution templates', 1) . "</td><td>"; SolutionTemplate::dropdown(array('value' => 0, 'entity' => $this->getEntityID(), 'rand' => $rand_template, 'toupdate' => array('value_fieldname' => 'value', 'to_update' => 'solution' . $rand_text, 'url' => $CFG_GLPI["root_doc"] . "/ajax/solution.php", 'moreparams' => array('type_id' => 'dropdown_solutiontypes_id' . $rand_type)))); echo "</td><td colspan='2'>"; if (Session::haveRightsOr('knowbase', array(READ, KnowbaseItem::READFAQ))) { echo "<a class='vsubmit' title=\"" . __s('Search a solution') . "\"\n href='" . $CFG_GLPI['root_doc'] . "/front/knowbaseitem.php?item_itemtype=" . $this->getType() . "&item_items_id=" . $this->getField('id') . "&forcetab=Knowbase\$1'>" . __('Search a solution') . "</a>"; } echo "</td></tr>"; } echo "<tr class='tab_bg_2'>"; echo "<td>" . __('Solution type') . "</td><td>"; $current = $this->fields['status']; // Settings a solution will set status to solved if ($canedit) { SolutionType::dropdown(array('value' => $this->getField('solutiontypes_id'), 'rand' => $rand_type, 'entity' => $this->getEntityID())); } else { echo Dropdown::getDropdownName('glpi_solutiontypes', $this->getField('solutiontypes_id')); } echo "</td><td colspan='2'> </td></tr>"; if ($canedit && Session::haveRight('knowbase', UPDATE)) { echo "<tr class='tab_bg_2'><td>" . __('Save and add to the knowledge base') . "</td><td>"; Dropdown::showYesNo('_sol_to_kb', false); echo "</td><td colspan='2'> </td></tr>"; } echo "<tr class='tab_bg_2'>"; echo "<td>" . __('Description') . "</td><td colspan='3'>"; if ($canedit) { $rand = mt_rand(); Html::initEditorSystem("solution{$rand}"); echo "<div id='solution{$rand_text}'>"; echo "<textarea id='solution{$rand}' name='solution' rows='12' cols='80' class='form-control'>" . $this->getField('solution') . "</textarea></div>"; } else { echo Toolbox::unclean_cross_side_scripting_deep($this->getField('solution')); } echo "</td></tr>"; $options['candel'] = false; $options['canedit'] = $canedit; $this->showFormButtons($options); }
/** * Execute the actions as defined in the rule * * @see Rule::executeActions() * * @param $output the result of the actions * @param $params the parameters * * @return the fields modified **/ function executeActions($output, $params) { global $CFG_GLPI; $entity = ''; $right = ''; $is_recursive = 0; $continue = true; $output_src = $output; if (count($this->actions)) { $entity = array(); foreach ($this->actions as $action) { switch ($action->fields["action_type"]) { case "assign": switch ($action->fields["field"]) { case "entities_id": $entity[] = $action->fields["value"]; break; case "profiles_id": $right = $action->fields["value"]; break; case "is_recursive": $is_recursive = $action->fields["value"]; break; case "is_active": $output["is_active"] = $action->fields["value"]; break; case "_ignore_user_import": $continue = false; $output_src["_stop_import"] = true; break; } // switch (field) break; case "regex_result": switch ($action->fields["field"]) { case "_affect_entity_by_dn": case "_affect_entity_by_tag": case "_affect_entity_by_domain": case "_affect_entity_by_completename": foreach ($this->regex_results as $regex_result) { $res = RuleAction::getRegexResultById($action->fields["value"], $regex_result); if ($res != null) { switch ($action->fields["field"]) { case "_affect_entity_by_dn": $entity_found = Entity::getEntityIDByDN(addslashes($res)); break; case "_affect_entity_by_tag": $entity_found = Entity::getEntityIDByTag(addslashes($res)); break; case "_affect_entity_by_domain": $entity_found = Entity::getEntityIDByDomain(addslashes($res)); break; case "_affect_entity_by_completename": $res = Toolbox::unclean_cross_side_scripting_deep($res); $entity_found = Entity::getEntityIDByCompletename(addslashes($res)); break; default: $entity_found = -1; break; } //If an entity was found if ($entity_found > -1) { $entity[] = $entity_found; } } } if (!count($entity)) { //Not entity assigned : action processing must be stopped for this rule $continue = false; } break; } // switch (field) break; } // switch (action_type) } // foreach (action) } // count (actions) if ($continue) { //Nothing to be returned by the function : //Store in session the entity and/or right if (count($entity)) { if ($right != '') { foreach ($entity as $entID) { $output["_ldap_rules"]["rules_entities_rights"][] = array($entID, $right, $is_recursive); } } else { foreach ($entity as $entID) { $output["_ldap_rules"]["rules_entities"][] = array($entID, $is_recursive); } } } else { if ($right != '') { $output["_ldap_rules"]["rules_rights"][] = $right; } } return $output; } return $output_src; }
/** * Populate the planning with planned reminder * * @param $options array of possible options: * - who ID of the user (0 = undefined) * - who_group ID of the group of users (0 = undefined) * - begin Date * - end Date * * @return array of planning item **/ static function populatePlanning($options = array()) { global $DB, $CFG_GLPI; $interv = array(); if (!isset($options['begin']) || $options['begin'] == 'NULL' || !isset($options['end']) || $options['end'] == 'NULL') { return $interv; } $who = $options['who']; $who_group = $options['who_group']; $begin = $options['begin']; $end = $options['end']; $readpub = $readpriv = ""; $joinstoadd = self::addVisibilityJoins(true); // See public reminder ? if ($who === Session::getLoginUserID() && Session::haveRight("reminder_public", "r")) { $readpub = self::addVisibilityRestrict(); } // See my private reminder ? if ($who_group === "mine" || $who === Session::getLoginUserID()) { $readpriv = "(`glpi_reminders`.`users_id` = '" . Session::getLoginUserID() . "')"; } else { if ($who > 0) { $readpriv = "`glpi_reminders`.`users_id` = '{$who}'"; } if ($who_group > 0) { if (!empty($readpriv)) { $readpriv .= " OR "; } $readpriv .= " `glpi_groups_reminders`.`groups_id` = '{$who_group}'"; } if (!empty($readpriv)) { $readpriv = '(' . $readpriv . ')'; } } $ASSIGN = ''; if (!empty($readpub) && !empty($readpriv)) { $ASSIGN = "({$readpub} OR {$readpriv})"; } else { if ($readpub) { $ASSIGN = $readpub; } else { $ASSIGN = $readpriv; } } if ($ASSIGN) { $query2 = "SELECT DISTINCT `glpi_reminders`.*\n FROM `glpi_reminders`\n {$joinstoadd}\n WHERE `glpi_reminders`.`is_planned` = '1'\n AND {$ASSIGN}\n AND `begin` < '{$end}'\n AND `end` > '{$begin}'\n ORDER BY `begin`"; $result2 = $DB->query($query2); if ($DB->numrows($result2) > 0) { for ($i = 0; $data = $DB->fetch_assoc($result2); $i++) { $key = $data["begin"] . "\$\$" . $i; $interv[$key]["itemtype"] = 'Reminder'; $interv[$key]["reminders_id"] = $data["id"]; $interv[$key]["id"] = $data["id"]; if (strcmp($begin, $data["begin"]) > 0) { $interv[$key]["begin"] = $begin; } else { $interv[$key]["begin"] = $data["begin"]; } if (strcmp($end, $data["end"]) < 0) { $interv[$key]["end"] = $end; } else { $interv[$key]["end"] = $data["end"]; } $interv[$key]["name"] = Html::resume_text($data["name"], $CFG_GLPI["cut"]); $interv[$key]["text"] = Html::resume_text(Html::clean(Toolbox::unclean_cross_side_scripting_deep($data["text"])), $CFG_GLPI["cut"]); $interv[$key]["users_id"] = $data["users_id"]; $interv[$key]["state"] = $data["state"]; $interv[$key]["state"] = $data["state"]; } } } return $interv; }
/** * Get dn for a user * * @param $ds LDAP link * @param $options array of possible options: * - basedn : base dn used to search * - login_field : attribute to store login * - search_parameters array of search parameters * - user_params array of parameters : method (IDENTIFIER_LOGIN or IDENTIFIER_EMAIL) + value * - condition : ldap condition used * * @return dn of the user, else false **/ static function searchUserDn($ds, $options = array()) { $values['basedn'] = ''; $values['login_field'] = ''; $values['search_parameters'] = array(); $values['user_params'] = ''; $values['condition'] = ''; $values['user_dn'] = false; foreach ($options as $key => $value) { $values[$key] = $value; } //By default authentify users by login //$authentification_value = ''; $login_attr = $values['search_parameters']['fields'][self::IDENTIFIER_LOGIN]; $ldap_parameters = array("dn"); foreach ($values['search_parameters']['fields'] as $parameter) { $ldap_parameters[] = $parameter; } //First : if a user dn is provided, look for it in the directory //Before trying to find the user using his login_field if ($values['user_dn']) { $info = self::getUserByDn($ds, $values['user_dn'], $ldap_parameters); if ($info) { return array('dn' => $values['user_dn'], $login_attr => $info[$login_attr][0]); } } //$authentification_value = $values['user_params']['value']; // Tenter une recherche pour essayer de retrouver le DN $filter = "(" . $values['login_field'] . "=" . $values['user_params']['value'] . ")"; if (!empty($values['condition'])) { $filter = "(& {$filter} " . $values['condition'] . ")"; } $filter = Toolbox::unclean_cross_side_scripting_deep($filter); if ($result = @ldap_search($ds, $values['basedn'], $filter, $ldap_parameters)) { $info = self::get_entries_clean($ds, $result); if (is_array($info) && $info['count'] == 1) { return array('dn' => $info[0]['dn'], $login_attr => $info[0][$login_attr][0]); } } return false; }
/** * @param $input array */ static function cleanContentHtml(array $input) { $txt = Html::clean(Toolbox::unclean_cross_side_scripting_deep($input['content_html'])); $txt = trim(html_entity_decode($txt, 0, 'UTF-8')); if (!$txt) { // No HTML (nothing to display) $input['content_html'] = ''; } else { if (!$input['content_text']) { // Use cleaned HTML $input['content_text'] = $txt; } } return $input; }
/** * Print out list kb item * * @param $options $_GET * @param $type string search type : browse / search (default search) **/ static function showList($options, $type = 'search') { global $DB, $CFG_GLPI; // Default values of parameters $params['faq'] = !Session::haveRight(self::$rightname, READ); $params["start"] = "0"; $params["knowbaseitemcategories_id"] = "0"; $params["contains"] = ""; $params["target"] = $_SERVER['PHP_SELF']; if (is_array($options) && count($options)) { foreach ($options as $key => $val) { $params[$key] = $val; } } $ki = new self(); switch ($type) { case 'myunpublished': if (!Session::haveRightsOr(self::$rightname, array(UPDATE, self::PUBLISHFAQ))) { return false; } break; case 'allunpublished': if (!Session::haveRight(self::$rightname, self::KNOWBASEADMIN)) { return false; } break; default: break; } if (!$params["start"]) { $params["start"] = 0; } $query = self::getListRequest($params, $type); // Get it from database if ($result = $DB->query($query)) { $KbCategory = new KnowbaseItemCategory(); $title = ""; if ($KbCategory->getFromDB($params["knowbaseitemcategories_id"])) { $title = empty($KbCategory->fields['name']) ? "(" . $params['knowbaseitemcategories_id'] . ")" : $KbCategory->fields['name']; $title = sprintf(__('%1$s: %2$s'), __('Category'), $title); } Session::initNavigateListItems('KnowbaseItem', $title); $numrows = $DB->numrows($result); $list_limit = $_SESSION['glpilist_limit']; $showwriter = in_array($type, array('myunpublished', 'allunpublished', 'allmy')); // Limit the result, if no limit applies, use prior result if ($numrows > $list_limit && !isset($_GET['export_all'])) { $query_limit = $query . " LIMIT " . intval($params["start"]) . ", " . intval($list_limit) . " "; $result_limit = $DB->query($query_limit); $numrows_limit = $DB->numrows($result_limit); } else { $numrows_limit = $numrows; $result_limit = $result; } if ($numrows_limit > 0) { // Set display type for export if define $output_type = Search::HTML_OUTPUT; if (isset($_GET["display_type"])) { $output_type = $_GET["display_type"]; } // Pager $parameters = "start=" . $params["start"] . "&knowbaseitemcategories_id=" . $params['knowbaseitemcategories_id'] . "&contains=" . $params["contains"] . "&is_faq=" . $params['faq']; if (isset($options['item_itemtype']) && isset($options['item_items_id'])) { $parameters .= "&item_items_id=" . $options['item_items_id'] . "&item_itemtype=" . $options['item_itemtype']; } if ($output_type == Search::HTML_OUTPUT) { Html::printPager($params['start'], $numrows, Toolbox::getItemTypeSearchURL('KnowbaseItem'), $parameters, 'KnowbaseItem'); } $nbcols = 1; // Display List Header echo Search::showHeader($output_type, $numrows_limit + 1, $nbcols); echo Search::showNewLine($output_type); $header_num = 1; echo Search::showHeaderItem($output_type, __('Subject'), $header_num); if ($output_type != Search::HTML_OUTPUT) { echo Search::showHeaderItem($output_type, __('Content'), $header_num); } if ($showwriter) { echo Search::showHeaderItem($output_type, __('Writer'), $header_num); } echo Search::showHeaderItem($output_type, __('Category'), $header_num); if (isset($options['item_itemtype']) && isset($options['item_items_id']) && $output_type == Search::HTML_OUTPUT) { echo Search::showHeaderItem($output_type, ' ', $header_num); } // Num of the row (1=header_line) $row_num = 1; for ($i = 0; $i < $numrows_limit; $i++) { $data = $DB->fetch_assoc($result_limit); Session::addToNavigateListItems('KnowbaseItem', $data["id"]); // Column num $item_num = 1; $row_num++; echo Search::showNewLine($output_type, $i % 2); $item = new self(); $item->getFromDB($data["id"]); $name = $data["name"]; $answer = $data["answer"]; // Manage translations if (isset($data['transname']) && !empty($data['transname'])) { $name = $data["transname"]; } if (isset($data['transanswer']) && !empty($data['transanswer'])) { $answer = $data["transanswer"]; } if ($output_type == Search::HTML_OUTPUT) { $toadd = ''; if (isset($options['item_itemtype']) && isset($options['item_items_id'])) { $href = " href='#' onClick=\"" . Html::jsGetElementbyID('kbshow' . $data["id"]) . ".dialog('open');\""; $toadd = Ajax::createIframeModalWindow('kbshow' . $data["id"], $CFG_GLPI["root_doc"] . "/front/knowbaseitem.form.php?id=" . $data["id"], array('display' => false)); } else { $href = " href=\"" . $CFG_GLPI['root_doc'] . "/front/knowbaseitem.form.php?id=" . $data["id"] . "\" "; } echo Search::showItem($output_type, "<div class='kb'>{$toadd}<a " . ($data['is_faq'] ? " class='pubfaq' title='" . __("This item is part of the FAQ") . "' " : " class='knowbase' ") . " {$href}>" . Html::resume_text($name, 80) . "</a></div>\n <div class='kb_resume'>" . Html::resume_text(Html::clean(Toolbox::unclean_cross_side_scripting_deep($answer)), 600) . "</div>", $item_num, $row_num); } else { echo Search::showItem($output_type, $name, $item_num, $row_num); echo Search::showItem($output_type, Html::clean(Toolbox::unclean_cross_side_scripting_deep(html_entity_decode($answer, ENT_QUOTES, "UTF-8"))), $item_num, $row_num); } $showuserlink = 0; if (Session::haveRight('user', READ)) { $showuserlink = 1; } if ($showwriter) { echo Search::showItem($output_type, getUserName($data["users_id"], $showuserlink), $item_num, $row_num); } $categ = $data["category"]; if ($output_type == Search::HTML_OUTPUT) { $cathref = $ki->getSearchURL() . "?knowbaseitemcategories_id=" . $data["knowbaseitemcategories_id"] . '&forcetab=Knowbase$2'; $categ = "<a href='{$cathref}'>" . $categ . '</a>'; } echo Search::showItem($output_type, $categ, $item_num, $row_num); if (isset($options['item_itemtype']) && isset($options['item_items_id']) && $output_type == Search::HTML_OUTPUT) { $forcetab = $options['item_itemtype']; if (!$_SESSION['glpiticket_timeline'] || $_SESSION['glpiticket_timeline_keep_replaced_tabs']) { $forcetab .= '$2'; //Solution tab } else { $forcetab .= '$1'; //Timeline tab } $content = "<a href='" . Toolbox::getItemTypeFormURL($options['item_itemtype']) . "?load_kb_sol=" . $data['id'] . "&id=" . $options['item_items_id'] . "&forcetab=" . $forcetab . "'>" . __('Use as a solution') . "</a>"; echo Search::showItem($output_type, $content, $item_num, $row_num); } // End Line echo Search::showEndLine($output_type); } // Display footer if ($output_type == Search::PDF_OUTPUT_LANDSCAPE || $output_type == Search::PDF_OUTPUT_PORTRAIT) { echo Search::showFooter($output_type, Dropdown::getDropdownName("glpi_knowbaseitemcategories", $params['knowbaseitemcategories_id'])); } else { echo Search::showFooter($output_type); } echo "<br>"; if ($output_type == Search::HTML_OUTPUT) { Html::printPager($params['start'], $numrows, Toolbox::getItemTypeSearchURL('KnowbaseItem'), $parameters, 'KnowbaseItem'); } } else { echo "<div class='center b'>" . __('No item found') . "</div>"; } } }
function prepareInputForUpdate($input) { global $CFG_GLPI; if (isset($input["password2"])) { // Empty : do not update if (empty($input["password"])) { unset($input["password"]); } else { if ($input["password"] == $input["password2"]) { // Check right : my password of user with lesser rights if (isset($input['id']) && Config::validatePassword($input["password"]) && ($input['id'] == Session::getLoginUserID() || $this->currentUserHaveMoreRightThan($input['id']) || $input['password_forget_token'] == $this->fields['password_forget_token'] && abs(strtotime($_SESSION["glpi_currenttime"]) - strtotime($this->fields['password_forget_token_date'])) < DAY_TIMESTAMP && $this->isEmail($input['email']))) { $input["password"] = sha1(Toolbox::unclean_cross_side_scripting_deep(stripslashes($input["password"]))); } else { unset($input["password"]); } unset($input["password2"]); } else { Session::addMessageAfterRedirect(__('Error: the two passwords do not match'), false, ERROR); return false; } } } else { if (isset($input["password"])) { // From login unset($input["password"]); } } // Update User in the database if (!isset($input["id"]) && isset($input["name"])) { if ($this->getFromDBbyName($input["name"])) { $input["id"] = $this->fields["id"]; } } if (isset($input["entities_id"]) && Session::getLoginUserID() === $input['id']) { $_SESSION["glpidefault_entity"] = $input["entities_id"]; } // Security on default profile update if (isset($input['profiles_id'])) { if (!in_array($input['profiles_id'], Profile_User::getUserProfiles($input['id']))) { unset($input['profiles_id']); } } // Security on default entity update if (isset($input['entities_id'])) { if (!in_array($input['entities_id'], Profile_User::getUserEntities($input['id']))) { unset($input['entities_id']); } } if (isset($input['_reset_personal_token'])) { $input['personal_token'] = self::getUniquePersonalToken(); $input['personal_token_date'] = $_SESSION['glpi_currenttime']; } // Manage preferences fields if (Session::getLoginUserID() === $input['id']) { if (isset($input['use_mode']) && $_SESSION['glpi_use_mode'] != $input['use_mode']) { $_SESSION['glpi_use_mode'] = $input['use_mode']; //Session::loadLanguage(); } } foreach ($CFG_GLPI['user_pref_field'] as $f) { if (isset($input[$f])) { if (Session::getLoginUserID() === $input['id']) { if ($_SESSION["glpi{$f}"] != $input[$f]) { $_SESSION["glpi{$f}"] = $input[$f]; } } if ($input[$f] == $CFG_GLPI[$f]) { $input[$f] = "NULL"; } } } return $input; }
/** * Populate the planning with planned reminder * * @param $options array of possible options: * - who ID of the user (0 = undefined) * - who_group ID of the group of users (0 = undefined) * - begin Date * - end Date * - color * - event_type_color * - check_avaibility (boolean) * * @return array of planning item **/ static function populatePlanning($options = array()) { global $DB, $CFG_GLPI; $default_options = array('color' => '', 'event_type_color' => '', 'check_planned' => false); $options = array_merge($default_options, $options); $interv = array(); $reminder = new self(); if (!isset($options['begin']) || $options['begin'] == 'NULL' || !isset($options['end']) || $options['end'] == 'NULL') { return $interv; } $who = $options['who']; $who_group = $options['who_group']; $begin = $options['begin']; $end = $options['end']; $readpub = $readpriv = ""; $joinstoadd = self::addVisibilityJoins(true); // See public reminder ? if ($who === Session::getLoginUserID() && self::canView()) { $readpub = self::addVisibilityRestrict(); } // See my private reminder ? if ($who_group === "mine" || $who === Session::getLoginUserID()) { $readpriv = "(`glpi_reminders`.`users_id` = '" . Session::getLoginUserID() . "')"; } else { if ($who > 0) { $readpriv = "`glpi_reminders`.`users_id` = '{$who}'"; } if ($who_group > 0) { if (!empty($readpriv)) { $readpriv .= " OR "; } $readpriv .= " `glpi_groups_reminders`.`groups_id` = '{$who_group}'"; } if (!empty($readpriv)) { $readpriv = '(' . $readpriv . ')'; } } $ASSIGN = ''; if (!empty($readpub) && !empty($readpriv)) { $ASSIGN = "({$readpub} OR {$readpriv})"; } else { if ($readpub) { $ASSIGN = $readpub; } else { $ASSIGN = $readpriv; } } $PLANNED = ''; if ($options['check_planned']) { $PLANNED = "AND state != " . Planning::INFO; } if ($ASSIGN) { $query2 = "SELECT DISTINCT `glpi_reminders`.*\n FROM `glpi_reminders`\n {$joinstoadd}\n WHERE `glpi_reminders`.`is_planned` = '1'\n AND {$ASSIGN}\n {$PLANNED}\n AND `begin` < '{$end}'\n AND `end` > '{$begin}'\n ORDER BY `begin`"; $result2 = $DB->query($query2); if ($DB->numrows($result2) > 0) { for ($i = 0; $data = $DB->fetch_assoc($result2); $i++) { $key = $data["begin"] . "\$\$" . "Reminder" . "\$\$" . $data["id"]; $interv[$key]['color'] = $options['color']; $interv[$key]['event_type_color'] = $options['event_type_color']; $interv[$key]["itemtype"] = 'Reminder'; $interv[$key]["reminders_id"] = $data["id"]; $interv[$key]["id"] = $data["id"]; if (strcmp($begin, $data["begin"]) > 0) { $interv[$key]["begin"] = $begin; } else { $interv[$key]["begin"] = $data["begin"]; } if (strcmp($end, $data["end"]) < 0) { $interv[$key]["end"] = $end; } else { $interv[$key]["end"] = $data["end"]; } $interv[$key]["name"] = Html::resume_text($data["name"], $CFG_GLPI["cut"]); $interv[$key]["text"] = Html::resume_text(Html::clean(Toolbox::unclean_cross_side_scripting_deep($data["text"])), $CFG_GLPI["cut"]); $interv[$key]["users_id"] = $data["users_id"]; $interv[$key]["state"] = $data["state"]; $interv[$key]["state"] = $data["state"]; $interv[$key]["url"] = $CFG_GLPI["root_doc"] . "/front/reminder.form.php?id=" . $data['id']; $interv[$key]["ajaxurl"] = $CFG_GLPI["root_doc"] . "/ajax/planning.php" . "?action=edit_event_form" . "&itemtype=Reminder" . "&id=" . $data['id'] . "&url=" . $interv[$key]["url"]; $reminder->getFromDB($data["id"]); $interv[$key]["editable"] = $reminder->canUpdateItem(); } } } return $interv; }
/** * Print out an HTML "<select>" for a dropdown with preselected value * * @param $itemtype itemtype used for create dropdown * @param $options array of possible options: * - name : string / name of the select (default is depending itemtype) * - value : integer / preselected value (default -1) * - comments : boolean / is the comments displayed near the dropdown (default true) * - toadd : array / array of specific values to add at the begining * - entity : integer or array / restrict to a defined entity or array of entities * (default -1 : no restriction) * - entity_sons : boolean / if entity restrict specified auto select its sons * only available if entity is a single value not an array * (default false) * - toupdate : array / Update a specific item on select change on dropdown * (need value_fieldname, to_update, * url (see Ajax::updateItemOnSelectEvent for information) * and may have moreparams) * - used : array / Already used items ID: not to display in dropdown * (default empty) * - on_change : string / value to transmit to "onChange" * - rand : integer / already computed rand value * - condition : string / aditional SQL condition to limit display * - displaywith : array / array of field to display with request * - emptylabel : Empty choice's label (default self::EMPTY_VALUE) * - display_emptychoice : Display emptychoice ? (default true) * - display : boolean / display or get string (default true) * - width : specific width needed (default auto adaptive) * - permit_select_parent : boolean / for tree dropdown permit to see parent items * not available by default (default false) * - specific_tags : array of HTML5 tags to add the the field * - url : url of the ajax php code which should return the json data to show in * the dropdown * * @return boolean : false if error and random id if OK **/ static function show($itemtype, $options = array()) { global $DB, $CFG_GLPI; if ($itemtype && !($item = getItemForItemtype($itemtype))) { return false; } $table = $item->getTable(); $params['name'] = $item->getForeignKeyField(); $params['value'] = $itemtype == 'Entity' ? $_SESSION['glpiactive_entity'] : ''; $params['comments'] = true; $params['entity'] = -1; $params['entity_sons'] = false; $params['toupdate'] = ''; $params['width'] = ''; $params['used'] = array(); $params['toadd'] = array(); $params['on_change'] = ''; $params['condition'] = ''; $params['rand'] = mt_rand(); $params['displaywith'] = array(); //Parameters about choice 0 //Empty choice's label $params['emptylabel'] = self::EMPTY_VALUE; //Display emptychoice ? $params['display_emptychoice'] = $itemtype != 'Entity'; $params['display'] = true; $params['permit_select_parent'] = false; $params['addicon'] = true; $params['specific_tags'] = array(); $params['url'] = $CFG_GLPI['root_doc'] . "/ajax/getDropdownValue.php"; if (is_array($options) && count($options)) { foreach ($options as $key => $val) { $params[$key] = $val; } } $output = ''; $name = $params['emptylabel']; $comment = ""; // Check default value for dropdown : need to be a numeric if (strlen($params['value']) == 0 || !is_numeric($params['value']) && $params['value'] != 'mygroups') { $params['value'] = 0; } if (isset($params['toadd'][$params['value']])) { $name = $params['toadd'][$params['value']]; } else { if ($params['value'] > 0 || $itemtype == "Entity" && $params['value'] >= 0) { $tmpname = self::getDropdownName($table, $params['value'], 1); if ($tmpname["name"] != " ") { $name = $tmpname["name"]; $comment = $tmpname["comment"]; } } } // Manage entity_sons if (!($params['entity'] < 0) && $params['entity_sons']) { if (is_array($params['entity'])) { // translation not needed - only for debug $output .= "entity_sons options is not available with entity option as array"; } else { $params['entity'] = getSonsOf('glpi_entities', $params['entity']); } } $field_id = Html::cleanId("dropdown_" . $params['name'] . $params['rand']); // Manage condition if (!empty($params['condition'])) { $params['condition'] = static::addNewCondition($params['condition']); } if (!$item instanceof CommonTreeDropdown) { $name = Toolbox::unclean_cross_side_scripting_deep($name); } $p = array('value' => $params['value'], 'valuename' => $name, 'width' => $params['width'], 'itemtype' => $itemtype, 'display_emptychoice' => $params['display_emptychoice'], 'displaywith' => $params['displaywith'], 'emptylabel' => $params['emptylabel'], 'condition' => $params['condition'], 'used' => $params['used'], 'toadd' => $params['toadd'], 'entity_restrict' => is_array($params['entity']) ? json_encode(array_values($params['entity'])) : $params['entity'], 'on_change' => $params['on_change'], 'permit_select_parent' => $params['permit_select_parent'], 'specific_tags' => $params['specific_tags']); $output = "<span class='no-wrap'>"; $output .= Html::jsAjaxDropdown($params['name'], $field_id, $params['url'], $p); // Display comment if ($params['comments']) { $comment_id = Html::cleanId("comment_" . $params['name'] . $params['rand']); $link_id = Html::cleanId("comment_link_" . $params['name'] . $params['rand']); $options_tooltip = array('contentid' => $comment_id, 'linkid' => $link_id, 'display' => false); if ($item->canView()) { if ($params['value'] && $item->getFromDB($params['value']) && $item->canViewItem()) { $options_tooltip['link'] = $item->getLinkURL(); } else { $options_tooltip['link'] = $item->getSearchURL(); } $options_tooltip['linktarget'] = '_blank'; } $output .= " " . Html::showToolTip($comment, $options_tooltip); if ($item instanceof CommonDropdown && $item->canCreate() && !isset($_REQUEST['_in_modal']) && $params['addicon']) { $output .= "<img alt='' title=\"" . __s('Add') . "\" src='" . $CFG_GLPI["root_doc"] . "/pics/add_dropdown.png' style='cursor:pointer; margin-left:2px;'\n onClick=\"" . Html::jsGetElementbyID('add_dropdown' . $params['rand']) . ".dialog('open');\">"; $output .= Ajax::createIframeModalWindow('add_dropdown' . $params['rand'], $item->getFormURL(), array('display' => false)); } // Display specific Links if ($itemtype == "Supplier") { if ($item->getFromDB($params['value'])) { $output .= $item->getLinks(); } } if ($itemtype == 'ITILCategory' && Session::haveRight('knowbase', READ)) { if ($params['value'] && $item->getFromDB($params['value'])) { $output .= ' ' . $item->getLinks(); } } $paramscomment = array('value' => '__VALUE__', 'table' => $table); if ($item->canView()) { $paramscomment['withlink'] = $link_id; } $output .= Ajax::updateItemOnSelectEvent($field_id, $comment_id, $CFG_GLPI["root_doc"] . "/ajax/comments.php", $paramscomment, false); } $output .= Ajax::commonDropdownUpdateItem($params, false); if ($params['display']) { echo $output; return $params['rand']; } $output .= "</span>"; return $output; }
/** * List the tickets for an authenticated user * * @param $params array of options (author, group, category, status, startdate, enddate, itemtype) * @param $protocol the communication protocol used * * @return array of hashtable **/ static function methodListTickets($params, $protocol) { global $DB, $CFG_GLPI; if (isset($params['help'])) { return array('count' => 'bool,optional', 'start' => 'integer,optional', 'limit' => 'integer,optional', 'user' => 'integer,optional', 'recipient' => 'integer,optional', 'mine' => 'bool,optional', 'group' => 'integer,optional', 'mygroups' => 'bool,optional', 'category' => 'integer,optional', 'status' => 'integer,optional', 'startdate' => 'datetime,optional', 'enddate' => 'datetime,optional', 'itemtype' => 'string,optional', 'item' => 'integer,optional', 'entity' => 'integer,optional', 'satisfaction' => 'integer,optional', 'approval' => 'text,optional', 'approver' => 'integer,optional', 'id2name' => 'bool,optional', 'order' => 'array,optional', 'help' => 'bool,optional'); } if (!Session::getLoginUserID()) { return self::Error($protocol, WEBSERVICES_ERROR_NOTAUTHENTICATED); } $resp = array(); $start = 0; if (isset($params['start']) && is_numeric($params['start'])) { $start = $params['start']; } $limit = $_SESSION['glpilist_limit']; if (isset($params['limit']) && is_numeric($params['limit'])) { $limit = $params['limit']; } $where = $join = ''; // User (victim) if (isset($params['user'])) { if (!is_numeric($params['user']) || $params['user'] < 0) { return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', 'user'); } if (Session::haveRight('show_all_ticket', '1') || Session::haveRight('show_group_ticket', '1') || $params['user'] == Session::getLoginUserID()) { // restrict to author parameter $where = " AND `glpi_tickets_users_request`.`users_id` = '" . $params['user'] . "'"; } else { return self::Error($protocol, WEBSERVICES_ERROR_NOTALLOWED); } } else { if (Session::haveRight('show_all_ticket', '1') || Session::haveRight('show_group_ticket', '1')) { $where = ''; // Restrict will come from group (if needed) } else { // Only connected user's tickets' $where = " AND `glpi_tickets_users_request`.`users_id`\n = '" . Session::getLoginUserID() . "'"; } } // Group if (isset($params['group'])) { if (!is_numeric($params['group']) || $params['group'] < 0) { return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', 'group'); } if (Session::haveRight('show_all_ticket', '1') || Session::haveRight('show_group_ticket', '1') && in_array($params['group'], $_SESSION['glpigroups'])) { // restrict to group parameter $where = " AND `glpi_groups_tickets_request`.`groups_id` = '" . $params['group'] . "'"; } else { return self::Error($protocol, WEBSERVICES_ERROR_NOTALLOWED); } } else { if (Session::haveRight('show_group_ticket', '1') && !Session::haveRight('show_all_ticket', '1')) { // Connected user's group' if (count($_SESSION['glpigroups']) > 0) { $where = " AND `glpi_groups_tickets_request`.`groups_id`\n IN (" . implode(',', $_SESSION['glpigroups']) . ")"; } else { $where = " AND `glpi_tickets_users_request`.`users_id`\n = '" . Session::getLoginUserID() . "'"; } } } // Security if (empty($where) && !Session::haveRight('show_all_ticket', '1')) { return self::Error($protocol, WEBSERVICES_ERROR_NOTALLOWED, '', 'profil'); } // Recipient (person creating the ticket) if (isset($params['recipient'])) { if (!is_numeric($params['recipient']) || $params['recipient'] < 0) { return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', 'recipient'); } // restrict to recipient parameter $where = " AND `users_id_recipient`='" . $params['recipient'] . "'"; } // Mine (user or recipient for the ticket) if (isset($params['mine'])) { $where = " AND (`glpi_tickets_users_request`.`users_id` = '" . Session::getLoginUserID() . "'\n OR `users_id_recipient` = '" . Session::getLoginUserID() . "')"; } // Mygroups if (isset($param['mygroups'])) { $where = " AND `glpi_groups_tickets`.`groups_id`\n IN (" . implode(',', $_SESSION['glpigroups']) . ")"; } // Entity if (isset($params['entity'])) { if (!Session::haveAccessToEntity($params['entity'])) { return self::Error($protocol, WEBSERVICES_ERROR_NOTALLOWED, '', 'entity'); } $where = getEntitiesRestrictRequest("WHERE", "glpi_tickets", '', $params['entity']) . $where; } else { $where = getEntitiesRestrictRequest("WHERE", "glpi_tickets") . $where; } // Category if (isset($params['category'])) { if (!is_numeric($params['category']) || $params['category'] <= 0) { return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', 'category'); } $where .= " AND " . getRealQueryForTreeItem("glpi_itilcategories", $params['category'], "glpi_tickets.itilcategories_id"); } if (isset($params['approval']) || isset($params['approver'])) { $join .= "INNER JOIN `glpi_ticketvalidations`\n ON (`glpi_tickets`.`id` = `glpi_ticketvalidations`.`tickets_id` ) "; if (isset($params['approver']) && is_numeric($params['approver'])) { $where .= " AND `glpi_ticketvalidations`.`users_id_validate`=" . $params['approver']; } $tabstatus = TicketValidation::getAllStatusArray(); if (isset($params['approval']) && isset($tabstatus[$params['approval']])) { $where .= " AND `glpi_ticketvalidations`.`status`='" . $params['approval'] . "'"; } } if (isset($params['satisfaction'])) { $join .= "INNER JOIN `glpi_ticketsatisfactions`\n ON (`glpi_tickets`.`id` = `glpi_ticketsatisfactions`.`tickets_id` ) "; switch ($params['satisfaction']) { case 1: $where .= " AND `glpi_ticketsatisfactions`.`date_answered` IS NULL"; break; case 2: $where .= " AND `glpi_ticketsatisfactions`.`date_answered` IS NOT NULL"; break; default: // survey exists (by Inner Join) } $params['status'] = Ticket::CLOSED; } // Status if (isset($params['status'])) { if (!in_array($params['status'], Ticket::getAllowedStatusArray(true))) { return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', 'status'); } switch ($params['status']) { case 'all': // No restriction break; case 'notclosed': $status = Ticket::getAllStatusArray(); unset($status[CLOSED]); $where .= " AND `glpi_tickets`.`status` IN ('" . implode("','", $status) . "') "; break; case 'notold': $status = Ticket::getAllStatusArray(); unset($status[SOLVED], $status[CLOSED]); $where .= " AND `glpi_tickets`.`status` IN ('" . implode("','", $status) . "') "; break; case 'old': $status = array_merge(Ticket::getSolvedStatusArray(), Ticket::getClosedStatusArray()); $where .= " AND `glpi_tickets`.`status` IN ('" . implode("','", $status) . "') "; break; case 'process': $status = Ticket::getProcessStatusArray(); $where .= " AND `glpi_tickets`.`status` IN ('" . implode("','", $status) . "') "; break; default: $where .= " AND `glpi_tickets`.`status` = '" . $params['status'] . "' "; } } // Dates if (isset($params["startdate"])) { if (preg_match(WEBSERVICES_REGEX_DATETIME, $params["startdate"]) || preg_match(WEBSERVICES_REGEX_DATE, $params["startdate"])) { $where .= " AND `glpi_tickets`.`date` >= '" . $params['startdate'] . "' "; } else { return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', 'date'); } } if (isset($params["enddate"])) { if (preg_match(WEBSERVICES_REGEX_DATETIME, $params["enddate"]) || preg_match(WEBSERVICES_REGEX_DATE, $params["enddate"])) { $where .= " AND `glpi_tickets`.`date` <= '" . $params['enddate'] . "' "; } else { return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', 'date'); } } if (isset($params['itemtype'])) { if (!empty($params['itemtype']) && !class_exists($params['itemtype'])) { return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', 'itemtype'); } $where .= " AND `glpi_tickets`.`itemtype`='" . $params['itemtype'] . "'"; } if (isset($params['item'])) { if (!isset($params['itemtype'])) { return self::Error($protocol, WEBSERVICES_ERROR_MISSINGPARAMETER, '', 'itemtype'); } if (!is_numeric($params['item']) || $params['item'] <= 0) { return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', 'item'); } $where .= " AND `glpi_tickets`.`items_id`='" . $params['item'] . "'"; } $orders = array(); if (isset($params['order'])) { if (is_array($params['order'])) { $tab = $params['order']; } else { $tab = array($params['order'] => 'DESC'); } foreach ($tab as $key => $val) { if ($val != 'ASC') { $val = 'DESC'; } $sqlkey = array('id' => '`glpi_tickets`.`id`', 'date' => '`glpi_tickets`.`date`', 'closedate' => '`glpi_tickets`.`closedate`', 'date_mod' => '`glpi_tickets`.`date_mod`', 'status' => '`glpi_tickets`.`status`', 'entities_id' => '`glpi_tickets`.`entities_id`', 'priority' => '`glpi_tickets`.`priority`'); if (isset($sqlkey[$key])) { $orders[] = $sqlkey[$key] . " {$val}"; } else { return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', 'order=$key'); } } } if (count($orders)) { $order = implode(',', $orders); } else { $order = "`glpi_tickets`.`date_mod` DESC"; } $resp = array(); if (isset($params['count'])) { $query = "SELECT COUNT(DISTINCT `glpi_tickets`.`id`) AS count\n FROM `glpi_tickets`\n {$join}\n LEFT JOIN `glpi_tickets_users` AS glpi_tickets_users_request\n ON (`glpi_tickets`.`id` = `glpi_tickets_users_request`.`tickets_id`\n AND `glpi_tickets_users_request`.`type` = 1)\n LEFT JOIN `glpi_groups_tickets` AS glpi_groups_tickets_request\n ON (`glpi_tickets`.`id` = `glpi_groups_tickets_request`.`tickets_id`\n AND `glpi_groups_tickets_request`.`type` = 1 )\n {$where}"; $resp = $DB->request($query)->next(); //debug $resp['query'] = $query; } else { $query = "SELECT `glpi_tickets`.*,\n GROUP_CONCAT(DISTINCT `glpi_tickets_users_request`.`users_id` SEPARATOR ',')\n AS users_id_request,\n GROUP_CONCAT(DISTINCT `glpi_tickets_users_observer`.`users_id` SEPARATOR ',')\n AS users_id_observer,\n GROUP_CONCAT(DISTINCT `glpi_tickets_users_assign`.`users_id` SEPARATOR ',')\n AS users_id_assign,\n GROUP_CONCAT(DISTINCT `glpi_groups_tickets_request`.`groups_id` SEPARATOR ',')\n AS groups_id_request,\n GROUP_CONCAT(DISTINCT `glpi_groups_tickets_observer`.`groups_id` SEPARATOR ',')\n AS groups_id_observer,\n GROUP_CONCAT(DISTINCT `glpi_groups_tickets_assign`.`groups_id` SEPARATOR ',')\n AS groups_id_assign\n FROM `glpi_tickets`\n {$join}\n LEFT JOIN `glpi_tickets_users` AS glpi_tickets_users_request\n ON (`glpi_tickets`.`id` = `glpi_tickets_users_request`.`tickets_id`\n AND `glpi_tickets_users_request`.`type` = 1)\n LEFT JOIN `glpi_tickets_users` AS glpi_tickets_users_assign\n ON (`glpi_tickets`.`id` = `glpi_tickets_users_assign`.`tickets_id`\n AND `glpi_tickets_users_assign`.`type` = 2)\n LEFT JOIN `glpi_tickets_users` AS glpi_tickets_users_observer\n ON (`glpi_tickets`.`id` = `glpi_tickets_users_observer`.`tickets_id`\n AND `glpi_tickets_users_observer`.`type` = 3)\n LEFT JOIN `glpi_groups_tickets` AS glpi_groups_tickets_request\n ON (`glpi_tickets`.`id` = `glpi_groups_tickets_request`.`tickets_id`\n AND `glpi_groups_tickets_request`.`type` = 1)\n LEFT JOIN `glpi_groups_tickets` AS glpi_groups_tickets_assign\n ON (`glpi_tickets`.`id` = `glpi_groups_tickets_assign`.`tickets_id`\n AND `glpi_groups_tickets_assign`.`type` = 2)\n LEFT JOIN `glpi_groups_tickets` AS glpi_groups_tickets_observer\n ON (`glpi_tickets`.`id` = `glpi_groups_tickets_observer`.`tickets_id`\n AND `glpi_groups_tickets_observer`.`type` = 3)\n {$where}\n GROUP BY `glpi_tickets`.`id`\n ORDER BY {$order}\n LIMIT {$start},{$limit}"; foreach ($DB->request($query) as $data) { $tmp = explode(',', $data['users_id_request']); $data['users']['requester'] = array(); foreach ($tmp as $id) { $data['users']['requester'][]['id'] = $id; } $tmp = explode(',', $data['users_id_observer']); $data['users']['observer'] = array(); foreach ($tmp as $id) { $data['users']['observer'][]['id'] = $id; } $tmp = explode(',', $data['users_id_assign']); $data['users']['assign'] = array(); foreach ($tmp as $id) { $data['users']['assign'][]['id'] = $id; } $tmp = explode(',', $data['groups_id_request']); $data['groups']['requester'] = array(); foreach ($tmp as $id) { $data['groups']['requester'][]['id'] = $id; } $tmp = explode(',', $data['groups_id_observer']); $data['groups']['observer'] = array(); foreach ($tmp as $id) { $data['groups']['observer'][]['id'] = $id; } $tmp = explode(',', $data['groups_id_assign']); $data['groups']['assign'] = array(); foreach ($tmp as $id) { $data['groups']['assign'][]['id'] = $id; } unset($data['groups_id_request'], $data['groups_id_observer'], $data['groups_id_assign'], $data['users_id_request'], $data['users_id_observer'], $data['users_id_assign']); $data['solution'] = Html::clean(Toolbox::unclean_cross_side_scripting_deep($data['solution'])); if (isset($params['id2name'])) { if ($data['itemtype'] && ($item = getItemForItemtype($data['itemtype']))) { $data['itemtype_name'] = Html::clean($item->getTypeName()); if ($item->getFromDB($data['items_id'])) { $data['items_name'] = Html::clean($item->getNameID()); } else { $data['items_name'] = NOT_AVAILABLE; } } foreach ($data['groups'] as $type => $tab) { foreach ($tab as $key => $grp) { $data['groups'][$type][$key]['name'] = Html::clean(Dropdown::getDropdownName('glpi_groups', $grp['id'])); } } foreach ($data['users'] as $type => $tab) { foreach ($tab as $key => $usr) { $data['users'][$type][$key]['name'] = Html::clean(getUserName($usr['id'])); } } $data['status_name'] = Html::clean(Ticket::getStatus($data['status'])); $data['urgency_name'] = Ticket::getUrgencyName($data['urgency']); $data['impact_name'] = Ticket::getImpactName($data['impact']); $data['priority_name'] = Ticket::getPriorityName($data['priority']); $data['users_name_recipient'] = Html::clean(getUserName($data['users_id_recipient'])); $data['entities_name'] = Html::clean(Dropdown::getDropdownName('glpi_entities', $data['entities_id'])); $data['suppliers_name_assign'] = Html::clean(Dropdown::getDropdownName('glpi_suppliers', $data['suppliers_id_assign'])); $data['ticketcategories_name'] = Html::clean(Dropdown::getDropdownName('glpi_itilcategories', $data['itilcategories_id'])); $data['requesttypes_name'] = Html::clean(Dropdown::getDropdownName('glpi_requesttypes', $data['requesttypes_id'])); $data['solutiontypes_name'] = Html::clean(Dropdown::getDropdownName('glpi_solutiontypes', $data['solutiontypes_id'])); $data['slas_name'] = Html::clean(Dropdown::getDropdownName('glpi_slas', $data['slas_id'])); $data['slalevels_name'] = Html::clean(Dropdown::getDropdownName('glpi_slalevels', $data['slalevels_id'])); } $resp[] = $data; } } return $resp; }
/** * @param $ID * @param $forcetab string name of the tab to force at the display (default '') **/ static function showVeryShort($ID, $forcetab = '') { global $CFG_GLPI; // Prints a job in short form // Should be called in a <table>-segment // Print links or not in case of user view // Make new job object and fill it from database, if success, print it $showprivate = false; if (Session::haveRight('followup', TicketFollowup::SEEPRIVATE)) { $showprivate = true; } $job = new self(); $rand = mt_rand(); if ($job->getFromDBwithData($ID, 0)) { $bgcolor = $_SESSION["glpipriority_" . $job->fields["priority"]]; // $rand = mt_rand(); echo "<tr class='tab_bg_2'>"; echo "<td class='center' bgcolor='{$bgcolor}'>" . sprintf(__('%1$s: %2$s'), __('ID'), $job->fields["id"]) . "</td>"; echo "<td class='center'>"; if (isset($job->users[CommonITILActor::REQUESTER]) && count($job->users[CommonITILActor::REQUESTER])) { foreach ($job->users[CommonITILActor::REQUESTER] as $d) { if ($d["users_id"] > 0) { $userdata = getUserName($d["users_id"], 2); $name = "<span class='b'>" . $userdata['name'] . "</span>"; $name = sprintf(__('%1$s %2$s'), $name, Html::showToolTip($userdata["comment"], array('link' => $userdata["link"], 'display' => false))); echo $name; } else { echo $d['alternative_email'] . " "; } echo "<br>"; } } if (isset($job->groups[CommonITILActor::REQUESTER]) && count($job->groups[CommonITILActor::REQUESTER])) { foreach ($job->groups[CommonITILActor::REQUESTER] as $d) { echo Dropdown::getDropdownName("glpi_groups", $d["groups_id"]); echo "<br>"; } } echo "</td>"; echo "<td class='center'>"; if (!empty($job->hardwaredatas)) { foreach ($job->hardwaredatas as $hardwaredatas) { if ($hardwaredatas->canView()) { echo $hardwaredatas->getTypeName() . " - "; echo "<span class='b'>" . $hardwaredatas->getLink() . "</span><br/>"; } else { if ($hardwaredatas) { echo $hardwaredatas->getTypeName() . " - "; echo "<span class='b'>" . $hardwaredatas->getNameID() . "</span><br/>"; } } } } else { echo __('General'); } echo "<td>"; $link = "<a id='ticket" . $job->fields["id"] . $rand . "' href='" . $CFG_GLPI["root_doc"] . "/front/ticket.form.php?id=" . $job->fields["id"]; if ($forcetab != '') { $link .= "&forcetab=" . $forcetab; } $link .= "'>"; $link .= "<span class='b'>" . $job->getNameID() . "</span></a>"; $link = sprintf(__('%1$s (%2$s)'), $link, sprintf(__('%1$s - %2$s'), $job->numberOfFollowups($showprivate), $job->numberOfTasks($showprivate))); $content = Toolbox::unclean_cross_side_scripting_deep(html_entity_decode($job->fields['content'], ENT_QUOTES, "UTF-8")); $link = printf(__('%1$s %2$s'), $link, Html::showToolTip(nl2br(Html::Clean($content)), array('applyto' => 'ticket' . $job->fields["id"] . $rand, 'display' => false))); echo "</td>"; // Finish Line echo "</tr>"; } else { echo "<tr class='tab_bg_2'>"; echo "<td colspan='6' ><i>" . __('No ticket in progress.') . "</i></td></tr>"; } }
if (!is_writable(GLPI_SESSION_DIR)) { Html::redirect($CFG_GLPI['root_doc'] . "/index.php?error=2"); } else { Html::redirect($CFG_GLPI['root_doc'] . "/index.php?error=1"); } } $_POST = array_map('stripslashes', $_POST); //Do login and checks //$user_present = 1; if (isset($_SESSION['namfield']) && isset($_POST[$_SESSION['namfield']])) { $login = $_POST[$_SESSION['namfield']]; } else { $login = ''; } if (isset($_SESSION['pwdfield']) && isset($_POST[$_SESSION['pwdfield']])) { $password = Toolbox::unclean_cross_side_scripting_deep($_POST[$_SESSION['pwdfield']]); } else { $password = ''; } // Redirect management $REDIRECT = ""; if (isset($_POST['redirect']) && strlen($_POST['redirect']) > 0) { $REDIRECT = "?redirect=" . rawurlencode($_POST['redirect']); } else { if (isset($_GET['redirect']) && strlen($_GET['redirect']) > 0) { $REDIRECT = "?redirect=" . rawurlencode($_GET['redirect']); } } $auth = new Auth(); // now we can continue with the process... if ($auth->Login($login, $password, isset($_REQUEST["noAUTO"]) ? $_REQUEST["noAUTO"] : false)) {
} if (isset($data['transname']) && !empty($data['transname'])) { $outputval = $data['transname']; } else { if ($field == 'itemtype' && class_exists($data['itemtype'])) { $tmpitem = new $data[$field](); if ($tmpitem->getFromDB($data['items_id'])) { $outputval = sprintf(__('%1$s - %2$s'), $tmpitem->getTypeName(), $tmpitem->getName()); } else { $outputval = $tmpitem->getTypeName(); } } else { $outputval = $data[$field]; } } $outputval = Toolbox::unclean_cross_side_scripting_deep($outputval); if ($displaywith) { foreach ($_POST['displaywith'] as $key) { if (isset($data[$key])) { $withoutput = $data[$key]; if (isForeignKeyField($key)) { $withoutput = Dropdown::getDropdownName(getTableNameForForeignKeyField($key), $data[$key]); } if (strlen($withoutput) > 0 && $withoutput != ' ') { $outputval = sprintf(__('%1$s - %2$s'), $outputval, $withoutput); } } } } $ID = $data['id']; $addcomment = "";
/** * @since version 0.90 * * @param $rand **/ function showTimeline($rand) { global $CFG_GLPI, $DB; //get ticket actors $ticket_users_keys = $this->getTicketActors(); $user = new User(); $followup_obj = new TicketFollowup(); $pics_url = $CFG_GLPI['root_doc'] . "/pics/timeline"; $timeline = $this->getTimelineItems(); //include lib for parsing url require GLPI_ROOT . "/lib/urllinker/urllinker.php"; //display timeline echo "<div class='timeline_history'>"; $tmp = array_values($timeline); $first_item = array_shift($tmp); // show approbation form on top when ticket is solved if ($this->fields["status"] == CommonITILObject::SOLVED) { echo "<div class='approbation_form' id='approbation_form{$rand}'>"; $followup_obj->showApprobationForm($this); echo "</div>"; } // show title for timeline self::showTimelineHeader(); $timeline_index = 0; foreach ($timeline as $item) { $item_i = $item['item']; // don't display empty followup (ex : solution approbation) if ($item['type'] == 'TicketFollowup' && empty($item_i['content'])) { continue; } $date = ""; if (isset($item_i['date'])) { $date = $item_i['date']; } if (isset($item_i['date_mod'])) { $date = $item_i['date_mod']; } // check if curent item user is assignee or requester $user_position = 'left'; if (isset($ticket_users_keys[$item_i['users_id']]) && $ticket_users_keys[$item_i['users_id']] == CommonItilActor::ASSIGN || $item['type'] == 'Assign') { $user_position = 'right'; } //display solution in middle if ($timeline_index == 0 && $item['type'] == "Solution" && $this->fields["status"] == CommonITILObject::SOLVED) { $user_position .= ' middle'; } echo "<div class='h_item {$user_position}'>"; echo "<div class='h_info'>"; echo "<div class='h_date'>" . Html::convDateTime($date) . "</div>"; if ($item_i['users_id'] !== false) { echo "<div class='h_user'>"; if (isset($item_i['users_id']) && $item_i['users_id'] != 0) { $user->getFromDB($item_i['users_id']); echo "<div class='tooltip_picture_border'>"; echo "<img class='user_picture' alt=\"" . __s('Picture') . "\" src='" . User::getThumbnailURLForPicture($user->fields['picture']) . "'>"; echo "</div>"; echo $user->getLink(); } else { _e("Requester"); } echo "</div>"; // h_user } echo "</div>"; //h_date echo "<div class='h_content " . $item['type'] . (isset($item_i['status']) ? " " . $item_i['status'] : "") . "'"; if (!in_array($item['type'], array('Document_Item', 'Assign')) && $item_i['can_edit']) { echo " ondblclick='javascript:viewEditSubitem" . $this->fields['id'] . "{$rand}(event, \"" . $item['type'] . "\", " . $item_i['id'] . ", this)'"; } echo ">"; if (isset($item_i['requesttypes_id']) && file_exists("{$pics_url}/" . $item_i['requesttypes_id'] . ".png")) { echo "<img src='{$pics_url}/" . $item_i['requesttypes_id'] . ".png' title='' class='h_requesttype' />"; } if (isset($item_i['content'])) { $content = $item_i['content']; $content = linkUrlsInTrustedHtml($content); //$content = nl2br($content); $long_text = ""; if (substr_count($content, "<br") > 30 || strlen($content) > 2000) { $long_text = "long_text"; } echo "<div class='item_content {$long_text}'>"; echo "<p>{$content}</p>"; if (!empty($long_text)) { echo "<p class='read_more'>"; echo "<a class='read_more_button'>.....</a>"; echo "</p>"; } echo "</div>"; } echo "<div class='b_right'>"; if (isset($item_i['solutiontypes_id']) && !empty($item_i['solutiontypes_id'])) { echo Dropdown::getDropdownName("glpi_solutiontypes", $item_i['solutiontypes_id']) . "<br>"; } if (isset($item_i['taskcategories_id']) && !empty($item_i['taskcategories_id'])) { echo Dropdown::getDropdownName("glpi_taskcategories", $item_i['taskcategories_id']) . "<br>"; } if (isset($item_i['actiontime']) && !empty($item_i['actiontime'])) { echo "<span class='actiontime'>"; echo Html::timestampToString($item_i['actiontime'], false); echo "</span>"; } if (isset($item_i['state'])) { echo "<span class='state state_" . $item_i['state'] . "'>"; echo Planning::getState($item_i['state']); echo "</span>"; } if (isset($item_i['begin'])) { echo "<span class='planification'>"; echo Html::convDateTime($item_i["begin"]); echo " ⇒ "; echo Html::convDateTime($item_i["end"]); echo "</span>"; } if (isset($item_i['users_id_tech'])) { echo "<div class='users_id_tech'>"; $user->getFromDB($item_i['users_id_tech']); echo "<div class='tooltip_picture_border'>"; echo "<img class='user_picture' alt=\"" . __s('Picture') . "\" src='" . User::getThumbnailURLForPicture($user->fields['picture']) . "'>"; echo "</div>"; echo $user->getLink(); echo "</div>"; } // show "is_private" icon if (isset($item_i['is_private']) && $item_i['is_private']) { echo "<div class='private'>" . __('Private') . "</div>"; } echo "</div>"; // b_right if ($item['type'] == 'Document_Item') { $filename = $item_i['filename']; $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION)); echo "<img src='"; if (empty($filename)) { $filename = $item_i['name']; } if (file_exists(GLPI_ROOT . "/pics/icones/{$ext}-dist.png")) { echo $CFG_GLPI['root_doc'] . "/pics/icones/{$ext}-dist.png"; } else { echo "{$pics_url}/file.png"; } echo "' title='file' /> "; echo "<a href='" . $CFG_GLPI['root_doc'] . "/front/document.send.php?docid=" . $item_i['id'] . "&tickets_id=" . $this->getID() . "' target='_blank'>{$filename}"; if (in_array($ext, array('jpg', 'jpeg', 'png', 'bmp'))) { echo "<div class='timeline_img_preview'>"; echo "<img src='" . $CFG_GLPI['root_doc'] . "/front/document.send.php?docid=" . $item_i['id'] . "&tickets_id=" . $this->getID() . "'/>"; echo "</div>"; } echo "</a>"; if (!empty($item_i['mime'])) { echo " (" . $item_i['mime'] . ")"; } echo "<a href='" . $CFG_GLPI['root_doc'] . "/front/document.form.php?id=" . $item_i['id'] . "' class='edit_document' title='" . _sx("button", "Update") . "'>"; echo "<img src='{$pics_url}/edit.png' /></a>"; echo "<a href='" . $CFG_GLPI['root_doc'] . "/front/ticket.form.php?delete_document&documents_id=" . $item_i['id'] . "&tickets_id=" . $this->getID() . "' class='delete_document' title='" . _sx("button", "Delete permanently") . "'>"; echo "<img src='{$pics_url}/delete.png' /></a>"; } echo "</div>"; //end h_content echo "</div>"; //end h_info $timeline_index++; } // end foreach timeline echo "<div class='break'></div>"; // recall ticket content (not needed in classic and splitted layout) if (!CommonGLPI::isLayoutWithMain()) { echo "<div class='h_item middle'>"; echo "<div class='h_info'>"; echo "<div class='h_date'>" . Html::convDateTime($this->fields['date']) . "</div>"; echo "<div class='h_user'>"; if (isset($item_i['users_id_recipient']) && $item_i['users_id_recipient'] != 0) { $user->getFromDB($this->fields['users_id_recipient']); echo "<div class='tooltip_picture_border'>"; $picture = ""; if (isset($user->fields['picture'])) { $picture = $user->fields['picture']; } echo "<img class='user_picture' alt=\"" . __s('Picture') . "\" src='" . User::getThumbnailURLForPicture($picture) . "'>"; echo "</div>"; echo $user->getLink(); } else { _e("Requester"); } echo "</div>"; // h_user echo "</div>"; //h_info echo "<div class='h_content TicketContent'>"; echo "<div class='b_right'>" . __("Ticket recall") . "</div>"; echo "<div class='ticket_title'>"; echo html_entity_decode($this->fields['name']); echo "</div>"; echo "<div class='ticket_description'>"; echo Toolbox::unclean_cross_side_scripting_deep(Html::entity_decode_deep($this->fields['content'])); echo "</div>"; echo "</div>"; // h_content TicketContent echo "</div>"; // h_item middle echo "<div class='break'></div>"; } // end timeline echo "</div>"; // h_item $user_position echo "<script type='text/javascript'>read_more();</script>"; }
/** * Retrieve the value of a fields from a LDAP result * applying needed substitution of %{value} * * @since 9.1 * * @param $map String with field format * @param $res LDAP result * **/ private static function getLdapFieldValue($map, array $res) { $map = Toolbox::unclean_cross_side_scripting_deep($map); $ret = preg_replace_callback('/%{(.*)}/U', function ($matches) use($res) { return isset($res[0][$matches[1]][0]) ? $res[0][$matches[1]][0] : ''; }, $map); return addslashes($ret == $map ? isset($res[0][$map][0]) ? $res[0][$map][0] : '' : $ret); }
/** * @param $string * @param $data **/ static function process($string, $data) { $offset = $new_offset = 0; //Template processed $output = ""; $cleandata = array(); // clean data for strtr foreach ($data as $field => $value) { if (!is_array($value)) { $cleandata[$field] = $value; } } //Remove all $string = Toolbox::unclean_cross_side_scripting_deep($string); //First of all process the FOREACH tag if (preg_match_all("/##FOREACH[ ]?(FIRST|LAST)?[ ]?([0-9]*)?[ ]?([a-zA-Z-0-9\\.]*)##/i", $string, $out)) { foreach ($out[3] as $id => $tag_infos) { $regex = "/" . $out[0][$id] . "(.*)##ENDFOREACH" . $tag_infos . "##/Uis"; if (preg_match($regex, $string, $tag_out) && isset($data[$tag_infos]) && is_array($data[$tag_infos])) { $data_lang_foreach = $cleandata; unset($data_lang_foreach[$tag_infos]); //Manage FIRST & LAST statement $foreachvalues = $data[$tag_infos]; if (!empty($foreachvalues)) { if (isset($out[1][$id]) && $out[1][$id] != '') { if ($out[1][$id] == 'FIRST') { $foreachvalues = array_reverse($foreachvalues); } if (isset($out[2][$id]) && $out[2][$id]) { $foreachvalues = array_slice($foreachvalues, 0, $out[2][$id]); } else { $foreachvalues = array_slice($foreachvalues, 0, 1); } } } $output_foreach_string = ""; foreach ($foreachvalues as $line) { foreach ($line as $field => $value) { if (!is_array($value)) { $data_lang_foreach[$field] = $value; } } $tmp = self::processIf($tag_out[1], $data_lang_foreach); $output_foreach_string .= strtr($tmp, $data_lang_foreach); } $string = str_replace($tag_out[0], $output_foreach_string, $string); } else { $string = str_replace($tag_out, '', $string); } } } //Now process IF statements $string = self::processIf($string, $cleandata); $string = strtr($string, $cleandata); return $string; }
/** * Decrypt a string * * @param $string string to decrypt * @param $key string key used to decrypt * * @return decrypted string **/ static function decrypt($string, $key) { $result = ''; $string = base64_decode($string); for ($i = 0; $i < strlen($string); $i++) { $char = substr($string, $i, 1); $keychar = substr($key, $i % strlen($key) - 1, 1); $char = chr(ord($char) - ord($keychar)); $result .= $char; } return Toolbox::unclean_cross_side_scripting_deep($result); }
} Stat::showGraph(array(__('Number opened') => $cleandata), array('title' => __('Number opened'), 'showtotal' => 1, 'unit' => __('Tickets'), 'type' => 'pie')); } if (isset($data['solved']) && is_array($data['solved'])) { foreach ($data['solved'] as $key => $val) { $cleandata[Html::clean($key)] = $val; } Stat::showGraph(array(__('Number solved') => $cleandata), array('title' => __('Number solved'), 'showtotal' => 1, 'unit' => __('Tickets'), 'type' => 'pie')); } if (isset($data['late']) && is_array($data['late'])) { foreach ($data['late'] as $key => $val) { $cleandata[Html::clean($key)] = $val; } Stat::showGraph(array(__('Number solved late') => $cleandata), array('title' => __('Number solved late'), 'showtotal' => 1, 'unit' => __('Tickets'), 'type' => 'pie')); } if (isset($data['closed']) && is_array($data['closed'])) { foreach ($data['closed'] as $key => $val) { $newkey = Toolbox::unclean_cross_side_scripting_deep(Html::clean($key)); $cleandata[$newkey] = $val; } Stat::showGraph(array(__('Number closed') => $cleandata), array('title' => __('Number closed'), 'showtotal' => 1, 'unit' => __('Tickets'), 'type' => 'pie')); } if (isset($data['opensatisfaction']) && is_array($data['opensatisfaction'])) { foreach ($data['opensatisfaction'] as $key => $val) { $newkey = Toolbox::unclean_cross_side_scripting_deep(Html::clean($key)); $cleandata[$newkey] = $val; } Stat::showGraph(array(__('Satisfaction survey') => $cleandata), array('title' => __('Satisfaction survey'), 'showtotal' => 1, 'unit' => __('Tickets'), 'type' => 'pie')); } } Html::footer();
/** * Show the feed content **/ function showFeedContent() { if (!$this->canViewItem()) { return false; } $feed = self::getRSSFeed($this->fields['url'], $this->fields['refresh_rate']); echo "<div class='firstbloc'>"; if (!$feed || $feed->error()) { _e('Error retrieving RSS feed'); $this->setError(true); } else { $this->setError(false); echo "<table class='tab_cadre_fixehov'>"; echo "<tr><th colspan='3'>" . $feed->get_title() . "</th>"; foreach ($feed->get_items(0, $this->fields['max_items']) as $item) { $link = $item->get_permalink(); echo "<tr class='tab_bg_1'><td>"; echo HTML::convDateTime($item->get_date('Y-m-d H:i:s')); echo "</td><td>"; if (!is_null($link)) { echo "<a target='_blank' href='{$link}'>" . $item->get_title() . '</a>'; } else { $item->get_title(); } echo "</td><td>"; $rand = mt_rand(); echo "<span id='rssitem{$rand}' class='pointer'>"; echo Html::resume_text(Html::clean(Toolbox::unclean_cross_side_scripting_deep($item->get_content())), 1000); echo "</span>"; Html::showToolTip(Toolbox::unclean_html_cross_side_scripting_deep($item->get_content()), array('applyto' => "rssitem{$rand}", 'display' => true)); echo "</td></tr>"; } echo "</table>"; } echo "</div>"; }
/** * Get a KB/FAQ article * for an authenticated user (or anonymous if allowed from config) * * @param $params array of options * @param $protocol the commonication protocol used **/ static function methodGetKnowBaseItem($params, $protocol) { global $DB, $CFG_GLPI; if (isset($params['help'])) { return array('id' => 'integer,mandatory', 'help' => 'bool,optional'); } $kb = new KnowbaseItem(); if (!isset($params['id'])) { return self::Error($protocol, WEBSERVICES_ERROR_MISSINGPARAMETER, '', 'id'); } if (!is_numeric($params['id'])) { return self::Error($protocol, WEBSERVICES_ERROR_BADPARAMETER, '', 'id'); } if (!$kb->can($params['id'], 'r')) { return self::Error($protocol, WEBSERVICES_ERROR_NOTFOUND); } $answer = Toolbox::unclean_cross_side_scripting_deep($kb->getField('answer')); $resp = $kb->fields; $resp['answer'] = $answer; $resp['answer_text'] = html_entity_decode(Html::clean($answer), 0, 'UTF-8'); $resp['documents'] = self::getDocForItem($kb); $kb->updateCounter(); return $resp; }
static function pdfSolution(PluginPdfSimplePDF $pdf, Ticket $job) { global $CFG_GLPI, $DB; $pdf->setColumnsSize(100); $pdf->displayTitle("<b>" . __('Solution') . "</b>"); if ($job->fields['solutiontypes_id'] || !empty($job->fields['solution'])) { if ($job->fields['solutiontypes_id']) { $title = Html::clean(Dropdown::getDropdownName('glpi_solutiontypes', $job->getField('solutiontypes_id'))); } else { $title = __('Solution'); } $sol = Html::clean(Toolbox::unclean_cross_side_scripting_deep(html_entity_decode($job->getField('solution'), ENT_QUOTES, "UTF-8"))); $pdf->displayText("<b><i>{$title}</i></b> : ", $sol); } else { $pdf->displayLine(__('None')); } $pdf->displaySpace(); }
/** * Is this file a valid file ? check based on file extension * * @param $filename filename to clean **/ static function isValidDoc($filename) { global $DB; $splitter = explode(".", $filename); $ext = end($splitter); $query = "SELECT *\n FROM `glpi_documenttypes`\n WHERE `ext` LIKE '{$ext}'\n AND `is_uploadable`='1'"; if ($result = $DB->query($query)) { if ($DB->numrows($result) > 0) { return Toolbox::strtoupper($ext); } } // Not found try with regex one $query = "SELECT *\n FROM `glpi_documenttypes`\n WHERE `ext` LIKE '/%/'\n AND `is_uploadable` = '1'"; foreach ($DB->request($query) as $data) { if (preg_match(Toolbox::unclean_cross_side_scripting_deep($data['ext']) . "i", $ext, $results) > 0) { return Toolbox::strtoupper($ext); } } return ""; }
/** * @since version 0.90 * **/ function getTimelineItems() { global $DB, $CFG_GLPI; $timeline = array(); $user = new User(); $group = new Group(); $followup_obj = new TicketFollowup(); $task_obj = new TicketTask(); $document_item_obj = new Document_Item(); $ticket_valitation_obj = new TicketValidation(); //checks rights $showpublic = Session::haveRightsOr("followup", array(TicketFollowup::SEEPUBLIC, TicketFollowup::SEEPRIVATE)) || Session::haveRightsOr("task", array(TicketTask::SEEPUBLIC, TicketTask::SEEPRIVATE)); $restrict_fup = $restrict_task = ""; if (!Session::haveRight("followup", TicketFollowup::SEEPRIVATE)) { $restrict_fup = " AND (`is_private` = '0'\n OR `users_id` ='" . Session::getLoginUserID() . "') "; } if (!Session::haveRight("task", TicketTask::SEEPRIVATE)) { $restrict_task = " AND (`is_private` = '0'\n OR `users_id` ='" . Session::getLoginUserID() . "') "; } if (!$showpublic) { $restrict = " AND 1 = 0"; } //add ticket followups to timeline if ($followup_obj->canview()) { $followups = $followup_obj->find("tickets_id = " . $this->getID() . " {$restrict_fup}", 'date DESC'); foreach ($followups as $followups_id => $followup) { $followup_obj->getFromDB($followups_id); $followup['can_edit'] = $followup_obj->canUpdateItem(); $timeline[$followup['date'] . "_followup_" . $followups_id] = array('type' => 'TicketFollowup', 'item' => $followup); } } //add ticket tasks to timeline if ($task_obj->canview()) { $tasks = $task_obj->find("tickets_id = " . $this->getID() . " {$restrict_task}", 'date DESC'); foreach ($tasks as $tasks_id => $task) { $task_obj->getFromDB($tasks_id); $task['can_edit'] = $task_obj->canUpdateItem(); $timeline[$task['date'] . "_task_" . $tasks_id] = array('type' => 'TicketTask', 'item' => $task); } } //add ticket documents to timeline $document_obj = new Document(); $document_items = $document_item_obj->find("itemtype = 'Ticket' AND items_id = " . $this->getID()); foreach ($document_items as $document_item) { $document_obj->getFromDB($document_item['documents_id']); $timeline[$document_obj->fields['date_mod'] . "_document_" . $document_item['documents_id']] = array('type' => 'Document_Item', 'item' => $document_obj->fields); } //add existing solution if (!empty($this->fields['solution']) || !empty($this->fields['solutiontypes_id'])) { $users_id = 0; $solution_date = $this->fields['solvedate']; //search date and user of last solution in glpi_logs if ($res_solution = $DB->query("SELECT `date_mod` AS solution_date, `user_name`, `id`\n FROM `glpi_logs`\n WHERE `itemtype` = 'Ticket'\n AND `items_id` = " . $this->getID() . "\n AND `id_search_option` = 24\n ORDER BY `id` DESC\n LIMIT 1")) { $data_solution = $DB->fetch_assoc($res_solution); if (!empty($data_solution['solution_date'])) { $solution_date = $data_solution['solution_date']; } // find user if (!empty($data_solution['user_name'])) { $users_id = addslashes(trim(preg_replace("/.*\\(([0-9]+)\\)/", "\$1", $data_solution['user_name']))); } } // fix trouble with html_entity_decode who skip accented characters (on windows browser) $solution_content = preg_replace_callback("/(&#[0-9]+;)/", function ($m) { return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES"); }, $this->fields['solution']); $timeline[$solution_date . "_solution"] = array('type' => 'Solution', 'item' => array('id' => 0, 'content' => Toolbox::unclean_cross_side_scripting_deep($solution_content), 'date' => $solution_date, 'users_id' => $users_id, 'solutiontypes_id' => $this->fields['solutiontypes_id'], 'can_edit' => Ticket::canUpdate() && $this->canSolve())); } // add ticket validation to timeline if ($this->fields['type'] == Ticket::DEMAND_TYPE && (Session::haveRight('ticketvalidation', TicketValidation::VALIDATEREQUEST) || Session::haveRight('ticketvalidation', TicketValidation::CREATEREQUEST)) || $this->fields['type'] == Ticket::INCIDENT_TYPE && (Session::haveRight('ticketvalidation', TicketValidation::VALIDATEINCIDENT) || Session::haveRight('ticketvalidation', TicketValidation::CREATEINCIDENT))) { $ticket_validations = $ticket_valitation_obj->find('tickets_id = ' . $this->getID()); foreach ($ticket_validations as $validations_id => $validation) { $canedit = $ticket_valitation_obj->can($validations_id, UPDATE); $user->getFromDB($validation['users_id_validate']); $timeline[$validation['submission_date'] . "_validation_" . $validations_id] = array('type' => 'TicketValidation', 'item' => array('id' => $validations_id, 'date' => $validation['submission_date'], 'content' => __('Validation request') . " => " . $user->getlink() . "<br>" . $validation['comment_submission'], 'users_id' => $validation['users_id'], 'can_edit' => $canedit)); if (!empty($validation['validation_date'])) { $timeline[$validation['validation_date'] . "_validation_" . $validations_id] = array('type' => 'TicketValidation', 'item' => array('id' => $validations_id, 'date' => $validation['validation_date'], 'content' => __('Validation request answer') . " : " . _sx('status', ucfirst(TicketValidation::getStatus($validation['status']))) . "<br>" . $validation['comment_validation'], 'users_id' => $validation['users_id_validate'], 'status' => "status_" . $validation['status'], 'can_edit' => $canedit)); } } } //reverse sort timeline items by key (date) krsort($timeline); return $timeline; }
/** * Try to match a definied rule * * @param &$criterion RuleCriteria object * @param $field the field to match * @param &$criterias_results * @param &$regex_result * * @return true if the field match the rule, false if it doesn't match **/ static function match(RuleCriteria &$criterion, $field, &$criterias_results, &$regex_result) { $condition = $criterion->fields['condition']; $pattern = $criterion->fields['pattern']; $criteria = $criterion->fields['criteria']; //If pattern is wildcard, don't check the rule and return true //or if the condition is "already present in GLPI" : will be processed later if ($pattern == Rule::RULE_WILDCARD || $condition == Rule::PATTERN_FIND) { return true; } $pattern = trim($pattern); switch ($condition) { case Rule::PATTERN_EXISTS: return !empty($field); case Rule::PATTERN_DOES_NOT_EXISTS: return empty($field); case Rule::PATTERN_IS: if (is_array($field)) { // Special case (used only by UNIQUE_PROFILE, for now) // $pattern is an ID if (in_array($pattern, $field)) { $criterias_results[$criteria] = $pattern; return true; } } else { //Perform comparison with fields in lower case $field = Toolbox::strtolower($field); $pattern = Toolbox::strtolower($pattern); if ($field == $pattern) { $criterias_results[$criteria] = $pattern; return true; } } return false; case Rule::PATTERN_IS_NOT: //Perform comparison with fields in lower case $field = Toolbox::strtolower($field); $pattern = Toolbox::strtolower($pattern); if ($field != $pattern) { $criterias_results[$criteria] = $pattern; return true; } return false; case Rule::PATTERN_UNDER: $table = getTableNameForForeignKeyField($criteria); $values = getSonsOf($table, $pattern); if (isset($values[$field])) { return true; } return false; case Rule::PATTERN_NOT_UNDER: $table = getTableNameForForeignKeyField($criteria); $values = getSonsOf($table, $pattern); if (isset($values[$field])) { return false; } return true; case Rule::PATTERN_END: $value = "/" . $pattern . "\$/i"; if (preg_match($value, $field) > 0) { $criterias_results[$criteria] = $pattern; return true; } return false; case Rule::PATTERN_BEGIN: if (empty($pattern)) { return false; } $value = mb_stripos($field, $pattern, 0, 'UTF-8'); if ($value !== false && $value == 0) { $criterias_results[$criteria] = $pattern; return true; } return false; case Rule::PATTERN_CONTAIN: if (empty($pattern)) { return false; } $value = mb_stripos($field, $pattern, 0, 'UTF-8'); if ($value !== false && $value >= 0) { $criterias_results[$criteria] = $pattern; return true; } return false; case Rule::PATTERN_NOT_CONTAIN: if (empty($pattern)) { return false; } $value = mb_stripos($field, $pattern, 0, 'UTF-8'); if ($value === false) { $criterias_results[$criteria] = $pattern; return true; } return false; case Rule::REGEX_MATCH: $results = array(); // Permit use < and > $pattern = Toolbox::unclean_cross_side_scripting_deep($pattern); if (preg_match_all($pattern . "i", $field, $results) > 0) { // Drop $result[0] : complete match result array_shift($results); // And add to $regex_result array $regex_result[] = $results[1]; $criterias_results[$criteria] = $pattern; return true; } return false; case Rule::REGEX_NOT_MATCH: // Permit use < and > $pattern = Toolbox::unclean_cross_side_scripting_deep($pattern); if (preg_match($pattern . "i", $field) == 0) { $criterias_results[$criteria] = $pattern; return true; } return false; case Rule::PATTERN_FIND: case Rule::PATTERN_IS_EMPTY: // Global criteria will be evaluated later return true; } return false; }
/** * Create SQL search condition * * @param $val string value to search * @param $not boolean is a negative search ? (false by default) * * @return search string **/ static function makeTextSearch($val, $not = false) { $NOT = ""; if ($not) { $NOT = "NOT"; } // Unclean to permit < and > search $val = Toolbox::unclean_cross_side_scripting_deep($val); if ($val == 'NULL' || $val == 'null') { $SEARCH = " IS {$NOT} NULL "; } else { $begin = 0; $end = 0; if (($length = strlen($val)) > 0) { if ($val[0] == '^') { $begin = 1; } if ($val[$length - 1] == '$') { $end = 1; } } if ($begin || $end) { // no Toolbox::substr, to be consistent with strlen result $val = substr($val, $begin, $length - $end - $begin); } $SEARCH = " {$NOT} LIKE '" . (!$begin ? "%" : "") . $val . (!$end ? "%" : "") . "' "; } return $SEARCH; }
/** * Print out list kb item * * @param $options $_GET * @param $type string search type : browse / search (default search) **/ static function showList($options, $type = 'search') { global $DB, $CFG_GLPI; // Default values of parameters $params['faq'] = !Session::haveRight("knowbase", "r"); $params["start"] = "0"; $params["knowbaseitemcategories_id"] = "0"; $params["contains"] = ""; $params["target"] = $_SERVER['PHP_SELF']; if (is_array($options) && count($options)) { foreach ($options as $key => $val) { $params[$key] = $val; } } $ki = new self(); switch ($type) { case 'myunpublished': if (!Session::haveRight('knowbase', 'w') && !Session::haveRight('faq', 'w')) { return false; } break; case 'allunpublished': if (!Session::haveRight('knowbase_admin', 1)) { return false; } break; default: break; } if (!$params["start"]) { $params["start"] = 0; } $query = self::getListRequest($params, $type); // Get it from database if ($result = $DB->query($query)) { $KbCategory = new KnowbaseItemCategory(); $title = ""; if ($KbCategory->getFromDB($params["knowbaseitemcategories_id"])) { $title = empty($KbCategory->fields['name']) ? "(" . $params['knowbaseitemcategories_id'] . ")" : $KbCategory->fields['name']; $title = sprintf(__('%1$s: %2$s'), __('Category'), $title); } Session::initNavigateListItems('KnowbaseItem', $title); $numrows = $DB->numrows($result); $list_limit = $_SESSION['glpilist_limit']; $showwriter = in_array($type, array('myunpublished', 'allunpublished', 'allmy')); // Limit the result, if no limit applies, use prior result if ($numrows > $list_limit && !isset($_GET['export_all'])) { $query_limit = $query . " LIMIT " . intval($params["start"]) . ", " . intval($list_limit) . " "; $result_limit = $DB->query($query_limit); $numrows_limit = $DB->numrows($result_limit); } else { $numrows_limit = $numrows; $result_limit = $result; } if ($numrows_limit > 0) { // Set display type for export if define $output_type = Search::HTML_OUTPUT; if (isset($_GET["display_type"])) { $output_type = $_GET["display_type"]; } // Pager $parameters = "start=" . $params["start"] . "&knowbaseitemcategories_id=" . $params['knowbaseitemcategories_id'] . "&contains=" . $params["contains"] . "&is_faq=" . $params['faq']; if (isset($options['item_itemtype']) && isset($options['item_items_id'])) { $parameters .= "&item_items_id=" . $options['item_items_id'] . "&item_itemtype=" . $options['item_itemtype']; } if ($output_type == Search::HTML_OUTPUT) { Html::printPager($params['start'], $numrows, Toolbox::getItemTypeSearchURL('KnowbaseItem'), $parameters, 'KnowbaseItem'); } $nbcols = 1; // Display List Header echo Search::showHeader($output_type, $numrows_limit + 1, $nbcols); $header_num = 1; echo Search::showHeaderItem($output_type, __('Subject'), $header_num); if ($output_type != Search::HTML_OUTPUT) { echo Search::showHeaderItem($output_type, __('Content'), $header_num); } if ($showwriter) { echo Search::showHeaderItem($output_type, __('Writer'), $header_num); } echo Search::showHeaderItem($output_type, __('Category'), $header_num); if (isset($options['item_itemtype']) && isset($options['item_items_id']) && $output_type == Search::HTML_OUTPUT) { echo Search::showHeaderItem($output_type, ' ', $header_num); } // Num of the row (1=header_line) $row_num = 1; for ($i = 0; $i < $numrows_limit; $i++) { $data = $DB->fetch_assoc($result_limit); Session::addToNavigateListItems('KnowbaseItem', $data["id"]); // Column num $item_num = 1; $row_num++; echo Search::showNewLine($output_type, $i % 2); if ($output_type == Search::HTML_OUTPUT) { if (isset($options['item_itemtype']) && isset($options['item_items_id'])) { $href = " href='#' onClick=\"var w = window.open('" . $CFG_GLPI["root_doc"] . "/front/popup.php?popup=show_kb&id=" . $data['id'] . "' ,'glpipopup', " . "'height=400, width=1000, top=100, left=100, scrollbars=yes' );" . "w.focus();\""; } else { $href = " href=\"" . $CFG_GLPI['root_doc'] . "/front/knowbaseitem.form.php?id=" . $data["id"] . "\" "; } echo Search::showItem($output_type, "<div class='kb'><a " . ($data['is_faq'] ? " class='pubfaq' " : " class='knowbase' ") . " {$href}>" . Html::resume_text($data["name"], 80) . "</a></div>\n <div class='kb_resume'>" . Html::resume_text(Html::clean(Toolbox::unclean_cross_side_scripting_deep($data["answer"])), 600) . "</div>", $item_num, $row_num); } else { echo Search::showItem($output_type, $data["name"], $item_num, $row_num); echo Search::showItem($output_type, Html::clean(Toolbox::unclean_cross_side_scripting_deep(html_entity_decode($data["answer"], ENT_QUOTES, "UTF-8"))), $item_num, $row_num); } if ($showwriter) { echo Search::showItem($output_type, getUserName($data["users_id"], 1), $item_num, $row_num); } $categ = $data["category"]; if ($output_type == Search::HTML_OUTPUT) { $cathref = $ki->getSearchURL() . "?knowbaseitemcategories_id=" . $data["knowbaseitemcategories_id"] . '&forcetab=Knowbase$2'; $categ = "<a href='{$cathref}'>" . $categ . '</a>'; } echo Search::showItem($output_type, $categ, $item_num, $row_num); if (isset($options['item_itemtype']) && isset($options['item_items_id']) && $output_type == Search::HTML_OUTPUT) { $content = "<a href='" . Toolbox::getItemTypeFormURL($options['item_itemtype']) . "?load_kb_sol=" . $data['id'] . "&id=" . $options['item_items_id'] . "&forcetab=" . $options['item_itemtype'] . "\$2'>" . __('Use as a solution') . "</a>"; echo Search::showItem($output_type, $content, $item_num, $row_num); } // End Line echo Search::showEndLine($output_type); } // Display footer if ($output_type == Search::PDF_OUTPUT_LANDSCAPE || $output_type == Search::PDF_OUTPUT_PORTRAIT) { echo Search::showFooter($output_type, Dropdown::getDropdownName("glpi_knowbaseitemcategories", $params['knowbaseitemcategories_id'])); } else { echo Search::showFooter($output_type); } echo "<br>"; if ($output_type == Search::HTML_OUTPUT) { Html::printPager($params['start'], $numrows, Toolbox::getItemTypeSearchURL('KnowbaseItem'), $parameters, 'KnowbaseItem'); } } else { echo "<div class='center b'>" . __('No item found') . "</div>"; } } }
/** * Get all groups a user belongs to * * @param $ds ldap connection * @param $ldap_base_dn Basedn used * @param $user_dn Basedn of the user * @param $group_condition group search condition * @param $group_member_field group field member in a user object * @param $use_dn boolean search dn of user ($login_field=$user_dn) in group_member_field * @param $login_field string user login field * * @return String : basedn of the user / false if not founded **/ function ldap_get_user_groups($ds, $ldap_base_dn, $user_dn, $group_condition, $group_member_field, $use_dn, $login_field) { $groups = array(); $listgroups = array(); //User dn may contain ( or ), need to espace it! $user_dn = str_replace(array("(", ")", "\\,", "\\+"), array("\\(", "\\)", "\\\\,", "\\\\+"), $user_dn); //Only retrive cn and member attributes from groups $attrs = array('dn'); if (!$use_dn) { $filter = "(& {$group_condition} (|({$group_member_field}={$user_dn})\n ({$group_member_field}={$login_field}={$user_dn})))"; } else { $filter = "(& {$group_condition} ({$group_member_field}={$user_dn}))"; } //Perform the search $filter = Toolbox::unclean_cross_side_scripting_deep($filter); $sr = ldap_search($ds, $ldap_base_dn, $filter, $attrs); //Get the result of the search as an array $info = AuthLDAP::get_entries_clean($ds, $sr); //Browse all the groups for ($i = 0; $i < count($info); $i++) { //Get the cn of the group and add it to the list of groups if (isset($info[$i]["dn"]) && $info[$i]["dn"] != '') { $listgroups[$i] = $info[$i]["dn"]; } } //Create an array with the list of groups of the user $groups[0][$group_member_field] = $listgroups; //Return the groups of the user return $groups; }
/** * display a field using standard system * * @since version 0.83 * * @param $field_id_or_search_options integer/string/array id of the search option field * or field name * or search option array * @param $values mixed value to display * @param $options array of possible options: * Parameters which could be used in options array : * - comments : boolean / is the comments displayed near the value (default false) * - any others options passed to specific display method * * @return return the string to display **/ function getValueToDisplay($field_id_or_search_options, $values, $options = array()) { global $CFG_GLPI; $param['comments'] = false; $param['html'] = false; foreach ($param as $key => $val) { if (!isset($options[$key])) { $options[$key] = $val; } } $searchoptions = array(); if (is_array($field_id_or_search_options)) { $searchoptions = $field_id_or_search_options; } else { $searchopt = $this->getSearchOptions(); // Get if id of search option is passed if (is_numeric($field_id_or_search_options)) { if (isset($searchopt[$field_id_or_search_options])) { $searchoptions = $searchopt[$field_id_or_search_options]; } } else { // Get if field name is passed $searchoptions = $this->getSearchOptionByField('field', $field_id_or_search_options, $this->getTable()); } } if (count($searchoptions)) { $field = $searchoptions['field']; // Normalize option if (is_array($values)) { $value = $values[$field]; } else { $value = $values; $values = array($field => $value); } if (isset($searchoptions['datatype'])) { $unit = ''; if (isset($searchoptions['unit'])) { $unit = $searchoptions['unit']; } switch ($searchoptions['datatype']) { case "count": case "number": if (isset($searchoptions['toadd']) && isset($searchoptions['toadd'][$value])) { return $searchoptions['toadd'][$value]; } if ($options['html']) { return Dropdown::getValueWithUnit(Html::formatNumber($value, false, 0), $unit); } return $value; case "decimal": if ($options['html']) { return Dropdown::getValueWithUnit(Html::formatNumber($value), $unit); } return $value; case "string": case "mac": case "ip": return $value; case "text": if ($options['html']) { $text = nl2br($value); } else { $text = $value; } if (isset($searchoptions['htmltext']) && $searchoptions['htmltext']) { $text = Html::clean(Toolbox::unclean_cross_side_scripting_deep($text)); } return $text; case "bool": return Dropdown::getYesNo($value); case "date": case "date_delay": if (isset($options['relative_dates']) && $options['relative_dates']) { $dates = Html::getGenericDateTimeSearchItems(array('with_time' => true, 'with_future' => true)); return $dates[$value]; } return Html::convDate(Html::computeGenericDateTimeSearch($value, true)); case "datetime": if (isset($options['relative_dates']) && $options['relative_dates']) { $dates = Html::getGenericDateTimeSearchItems(array('with_time' => true, 'with_future' => true)); return $dates[$value]; } return Html::convDateTime(Html::computeGenericDateTimeSearch($value, false)); case "timestamp": if ($value == 0 && isset($searchoptions['emptylabel'])) { return $searchoptions['emptylabel']; } $withseconds = false; if (isset($searchoptions['withseconds'])) { $withseconds = $searchoptions['withseconds']; } return Html::timestampToString($value, $withseconds); case "email": if ($options['html']) { return "<a href='mailto:{$value}'>{$value}</a>"; } return $value; case "weblink": $orig_link = trim($value); if (!empty($orig_link)) { // strip begin of link $link = preg_replace('/https?:\\/\\/(www[^\\.]*\\.)?/', '', $orig_link); $link = preg_replace('/\\/$/', '', $link); if (Toolbox::strlen($link) > $CFG_GLPI["url_maxlength"]) { $link = Toolbox::substr($link, 0, $CFG_GLPI["url_maxlength"]) . "..."; } return "<a href=\"" . formatOutputWebLink($orig_link) . "\" target='_blank'>{$link}" . "</a>"; } return " "; case "itemlink": if ($searchoptions['table'] == $this->getTable()) { break; } case "dropdown": if (isset($searchoptions['toadd']) && isset($searchoptions['toadd'][$value])) { return $searchoptions['toadd'][$value]; } if (!is_numeric($value)) { return $value; } if ($value == 0 && isset($searchoptions['emptylabel'])) { return $searchoptions['emptylabel']; } if ($searchoptions['table'] == 'glpi_users') { if ($param['comments']) { $tmp = getUserName($value, 2); return $tmp['name'] . ' ' . Html::showToolTip($tmp['comment'], array('display' => false)); } return getUserName($value); } if ($param['comments']) { $tmp = Dropdown::getDropdownName($searchoptions['table'], $value, 1); return $tmp['name'] . ' ' . Html::showToolTip($tmp['comment'], array('display' => false)); } return Dropdown::getDropdownName($searchoptions['table'], $value); case "itemtypename": if ($obj = getItemForItemtype($value)) { return $obj->getTypeName(1); } break; case "language": if (isset($CFG_GLPI['languages'][$value])) { return $CFG_GLPI['languages'][$value][0]; } return __('Default value'); } } // Get specific display if available $itemtype = getItemTypeForTable($searchoptions['table']); if ($item = getItemForItemtype($itemtype)) { $options['searchopt'] = $searchoptions; $specific = $item->getSpecificValueToDisplay($field, $values, $options); if (!empty($specific)) { return $specific; } } } return $value; }