Exemple #1
0
 function canUpdateItem()
 {
     if (isset($this->fields['itemtype']) && ($item = getItemForItemtype($this->fields['itemtype']))) {
         return Session::haveRight($item::$rightname, UPDATENOTE);
     }
     return false;
 }
Exemple #2
0
 static function beforeAdd(Ticket $ticket)
 {
     global $DB;
     if (!is_array($ticket->input) || !count($ticket->input)) {
         // Already cancel by another plugin
         return false;
     }
     //Toolbox::logDebug("PluginBehaviorsTicket::beforeAdd(), Ticket=", $ticket);
     $config = PluginBehaviorsConfig::getInstance();
     if ($config->getField('tickets_id_format')) {
         $max = 0;
         $sql = 'SELECT MAX( id ) AS max
              FROM `glpi_tickets`';
         foreach ($DB->request($sql) as $data) {
             $max = $data['max'];
         }
         $want = date($config->getField('tickets_id_format'));
         if ($max < $want) {
             $DB->query("ALTER TABLE `glpi_tickets` AUTO_INCREMENT={$want}");
         }
     }
     if (!isset($ticket->input['_auto_import']) && isset($_SESSION['glpiactiveprofile']['interface']) && $_SESSION['glpiactiveprofile']['interface'] == 'central') {
         if ($config->getField('is_requester_mandatory') && !$ticket->input['_users_id_requester'] && (!isset($ticket->input['_users_id_requester_notif']['alternative_email']) || empty($ticket->input['_users_id_requester_notif']['alternative_email']))) {
             Session::addMessageAfterRedirect(__('Requester is mandatory', 'behaviors'), true, ERROR);
             $ticket->input = array();
             return true;
         }
     }
     if ($config->getField('use_requester_item_group') && isset($ticket->input['itemtype']) && isset($ticket->input['items_id']) && $ticket->input['items_id'] > 0 && ($item = getItemForItemtype($ticket->input['itemtype'])) && (!isset($ticket->input['_groups_id_requester']) || $ticket->input['_groups_id_requester'] <= 0)) {
         if ($item->isField('groups_id') && $item->getFromDB($ticket->input['items_id'])) {
             $ticket->input['_groups_id_requester'] = $item->getField('groups_id');
         }
     }
     // No Auto set Import for external source -> Duplicate from Ticket->prepareInputForAdd()
     if (!isset($ticket->input['_auto_import'])) {
         if (!isset($ticket->input['_users_id_requester'])) {
             if ($uid = Session::getLoginUserID()) {
                 $ticket->input['_users_id_requester'] = $uid;
             }
         }
     }
     if ($config->getField('use_requester_user_group') && isset($ticket->input['_users_id_requester']) && $ticket->input['_users_id_requester'] > 0 && (!isset($ticket->input['_groups_id_requester']) || $ticket->input['_groups_id_requester'] <= 0)) {
         if ($config->getField('use_requester_user_group') == 1) {
             // First group
             $ticket->input['_groups_id_requester'] = PluginBehaviorsUser::getRequesterGroup($ticket->input['entities_id'], $ticket->input['_users_id_requester'], true);
         } else {
             // All groups
             $g = PluginBehaviorsUser::getRequesterGroup($ticket->input['entities_id'], $ticket->input['_users_id_requester'], false);
             if (count($g)) {
                 $ticket->input['_groups_id_requester'] = array_shift($g);
             }
             if (count($g)) {
                 $ticket->input['_additional_groups_requesters'] = $g;
             }
         }
     }
     // Toolbox::logDebug("PluginBehaviorsTicket::beforeAdd(), Updated input=", $ticket->input);
 }
 /**
  * @see RuleCollection::replayRulesOnExistingDB()
  **/
 function replayRulesOnExistingDB($offset = 0, $maxtime = 0, $items = array(), $params = array())
 {
     global $DB;
     // Model check : need to check using manufacturer extra data so specific function
     if (strpos($this->item_table, 'models')) {
         return $this->replayRulesOnExistingDBForModel($offset, $maxtime);
     }
     if (isCommandLine()) {
         printf(__('Replay rules on existing database started on %s') . "\n", date("r"));
     }
     // Get All items
     $Sql = "SELECT *\n              FROM `" . $this->item_table . "`";
     if ($offset) {
         $Sql .= " LIMIT " . intval($offset) . ",999999999";
     }
     $result = $DB->query($Sql);
     $nb = $DB->numrows($result) + $offset;
     $i = $offset;
     if ($result && $nb > $offset) {
         // Step to refresh progressbar
         $step = $nb > 20 ? floor($nb / 20) : 1;
         $send = array();
         $send["tablename"] = $this->item_table;
         while ($data = $DB->fetch_assoc($result)) {
             if (!($i % $step)) {
                 if (isCommandLine()) {
                     //TRANS: %1$s is a row, %2$s is total rows
                     printf(__('Replay rules on existing database: %1$s/%2$s') . "\r", $i, $nb);
                 } else {
                     Html::changeProgressBarPosition($i, $nb, "{$i} / {$nb}");
                 }
             }
             //Replay Type dictionnary
             $ID = Dropdown::importExternal(getItemTypeForTable($this->item_table), addslashes($data["name"]), -1, array(), addslashes($data["comment"]));
             if ($data['id'] != $ID) {
                 $tomove[$data['id']] = $ID;
                 $type = GetItemTypeForTable($this->item_table);
                 if ($dropdown = getItemForItemtype($type)) {
                     $dropdown->delete(array('id' => $data['id'], '_replace_by' => $ID));
                 }
             }
             $i++;
             if ($maxtime) {
                 $crt = explode(" ", microtime());
                 if ($crt[0] + $crt[1] > $maxtime) {
                     break;
                 }
             }
         }
         // end while
     }
     if (isCommandLine()) {
         printf(__('Replay rules on existing database started on %s') . "\n", date("r"));
     } else {
         Html::changeProgressBarPosition($i, $nb, "{$i} / {$nb}");
     }
     return $i == $nb ? -1 : $i;
 }
 function getSubName()
 {
     $itemtype = $this->getParameterValue();
     if ($itemtype && ($item = getItemForItemtype($itemtype))) {
         $name = $item->getTypeName();
     } else {
         // All
         return '';
     }
     return " " . $this->getCriteriaLabel() . " : " . $name;
 }
 function __construct($name, $title, $itemtype, $options = array())
 {
     parent::__construct($name, $title, $options);
     $this->obj = getItemForItemtype($itemtype);
     if (isset($options['with_comment'])) {
         $this->with_comment = $options['with_comment'];
     }
     if (isset($options['with_navigate'])) {
         $this->with_navigate = $options['with_navigate'];
         Session::initNavigateListItems($this->obj->getType(), _n('Report', 'Reports', 2));
     }
 }
 static function surveilleResa($task)
 {
     global $DB, $CFG_GLPI;
     $valreturn = 0;
     $temps = time();
     $temps -= $temps % MINUTE_TIMESTAMP;
     $begin = date("Y-m-d H:i:s", $temps);
     $end = date("Y-m-d H:i:s", $temps + 5 * MINUTE_TIMESTAMP);
     $left = "";
     $where = "";
     $listResaTraitee = array();
     foreach ($CFG_GLPI["reservation_types"] as $itemtype) {
         if (!($item = getItemForItemtype($itemtype))) {
             continue;
         }
         $itemtable = getTableForItemType($itemtype);
         $otherserial = "'' AS otherserial";
         if ($item->isField('otherserial')) {
             $otherserial = "`{$itemtable}`.`otherserial`";
         }
         if (isset($begin) && isset($end)) {
             $left = "LEFT JOIN `glpi_reservations`\n      ON (`glpi_reservationitems`.`id` = `glpi_reservations`.`reservationitems_id`\n       AND '" . $begin . "' <= `glpi_reservations`.`end`\n       AND '" . $end . "' >= `glpi_reservations`.`end`)";
             $where = " AND `glpi_reservations`.`id` IS NOT NULL ";
         }
         $query = "SELECT `glpi_reservationitems`.`id`,\n`glpi_reservationitems`.`comment`,\n`{$itemtable}`.`name` AS name,\n`{$itemtable}`.`entities_id` AS entities_id,\n{$otherserial},\n`glpi_reservations`.`id` AS resaid,\n`glpi_reservations`.`comment`,\n`glpi_reservations`.`begin`,\n`glpi_reservations`.`end`,\n`glpi_users`.`name` AS username,\n`glpi_reservationitems`.`items_id` AS items_id\nFROM `glpi_reservationitems`\n{$left}\nINNER JOIN `{$itemtable}`\nON (`glpi_reservationitems`.`itemtype` = '{$itemtype}'\n  AND `glpi_reservationitems`.`items_id` = `{$itemtable}`.`id`)\nLEFT JOIN `glpi_users` \nON (`glpi_reservations`.`users_id` = `glpi_users`.`id`)\nWHERE `glpi_reservationitems`.`is_active` = '1'\nAND `glpi_reservationitems`.`is_deleted` = '0'\nAND `{$itemtable}`.`is_deleted` = '0'\n{$where} " . "ORDER BY username,\n`{$itemtable}`.`entities_id`,\n`{$itemtable}`.`name`";
         if ($result = $DB->query($query)) {
             while ($row = $DB->fetch_assoc($result)) {
                 $query = "SELECT * FROM `glpi_plugin_reservation_manageresa` WHERE `resaid` = " . $row["resaid"];
                 //on insere la reservation seulement si elle n'est pas deja presente dans la table
                 if ($res = $DB->query($query)) {
                     if (!$DB->numrows($res)) {
                         $query = "INSERT INTO  `glpi_plugin_reservation_manageresa` (`resaid`, `matid`, `date_theorique`, `itemtype`) VALUES ('" . $row["resaid"] . "','" . $row["items_id"] . "','" . $row['end'] . "','" . $itemtype . "');";
                         $DB->query($query) or die("error on 'insert' into glpi_plugin_reservation_manageresa  lors du cron/ hash: " . $DB->error());
                     }
                 }
             }
         }
     }
     //on va prolonger toutes les resa managées qui n'ont pas de date de retour
     $query = "SELECT * FROM `glpi_plugin_reservation_manageresa` WHERE date_return is NULL;";
     if ($result = $DB->query($query)) {
         while ($row = $DB->fetch_assoc($result)) {
             $newEnd = $temps + 5 * MINUTE_TIMESTAMP;
             $task->log("prolongation de la reservation numero " . $row['resaid']);
             // prolongation de la vrai resa
             self::verifDisponibiliteAndMailIGS($task, $row['itemtype'], $row['matid'], $row['resaid'], $begin, date("Y-m-d H:i:s", $newEnd));
             $query = "UPDATE `glpi_reservations` SET `end`='" . date("Y-m-d H:i:s", $newEnd) . "' WHERE `id`='" . $row["resaid"] . "';";
             $DB->query($query) or die("error on 'update' into glpi_reservations lors du cron : " . $DB->error());
             $valreturn++;
         }
     }
     return $valreturn;
 }
 function displayValue($output_type, $row)
 {
     if (!isset($row[$this->name]) || !$row[$this->name]) {
         return '';
     }
     if (!($value = getItemForItemtype($row[$this->name]))) {
         return $value;
     }
     if (is_null($this->obj) || get_class($this->obj) != $row[$this->name]) {
         $this->obj = new $row[$this->name]();
     }
     return $this->obj->getTypeName();
 }
 static function showPreferences()
 {
     global $DB, $CFG_GLPI, $PLUGIN_HOOKS;
     $target = Toolbox::getItemTypeFormURL(__CLASS__);
     $pref = new self();
     echo "<div class='center' id='pdf_type'>";
     foreach ($PLUGIN_HOOKS['plugin_pdf'] as $type => $plug) {
         if (!($item = getItemForItemtype($type))) {
             continue;
         }
         if ($item->canView()) {
             $pref->menu($item, $target);
         }
     }
     echo "</div>";
 }
 function displayValue($output_type, $row)
 {
     if (!isset($row[$this->name]) || !$row[$this->name]) {
         return '';
     }
     if (isset($row[$this->nametype]) && $row[$this->nametype] && (is_null($this->obj) || $this->obj->getType() != $row[$this->nametype])) {
         if (!($this->obj = getItemForItemtype($row[$this->nametype]))) {
             $this->obj = NULL;
         }
     }
     if (!$this->obj || !$this->obj->getFromDB($row[$this->name])) {
         return 'ID #' . $row[$this->name];
     }
     if ($output_type == Search::HTML_OUTPUT) {
         return $this->obj->getLink($this->with_comment);
     }
     return $this->obj->getNameID();
 }
 /**
  * Get all data needed for template processing
  *
  * @param $event
  * @param $options   array
  **/
 function getDatasForTemplate($event, $options = array())
 {
     $events = $this->getAllEvents();
     $this->datas['##infocom.entity##'] = Dropdown::getDropdownName('glpi_entities', $options['entities_id']);
     $this->datas['##infocom.action##'] = $events[$event];
     foreach ($options['items'] as $id => $item) {
         $tmp = array();
         if ($obj = getItemForItemtype($item['itemtype'])) {
             $tmp['##infocom.itemtype##'] = $obj->getTypeName(1);
             $tmp['##infocom.item##'] = $item['item_name'];
             $tmp['##infocom.expirationdate##'] = $item['warrantyexpiration'];
             $tmp['##infocom.url##'] = $this->formatURL($options['additionnaloption']['usertype'], $item['itemtype'] . "_" . $item['items_id'] . "_Infocom");
         }
         $this->datas['infocoms'][] = $tmp;
     }
     $this->getTags();
     foreach ($this->tag_descriptions[NotificationTarget::TAG_LANGUAGE] as $tag => $values) {
         if (!isset($this->datas[$tag])) {
             $this->datas[$tag] = $values['label'];
         }
     }
 }
 /**
  * Get all data needed for template processing
  *
  * @param $event
  * @param $options   array
  **/
 function getDatasForTemplate($event, $options = array())
 {
     global $CFG_GLPI;
     $events = $this->getAllEvents();
     $this->datas['##infocom.entity##'] = Dropdown::getDropdownName('glpi_entities', $options['entities_id']);
     $this->datas['##infocom.action##'] = $events[$event];
     foreach ($options['items'] as $id => $item) {
         $tmp = array();
         if ($obj = getItemForItemtype($item['itemtype'])) {
             $tmp['##infocom.itemtype##'] = $obj->getTypeName(1);
             $tmp['##infocom.item##'] = $item['item_name'];
             $tmp['##infocom.expirationdate##'] = $item['warrantyexpiration'];
             $tmp['##infocom.url##'] = urldecode($CFG_GLPI["url_base"] . "/index.php?redirect=" . strtolower($item['itemtype']) . "_" . $item['items_id'] . "_Infocom");
         }
         $this->datas['infocoms'][] = $tmp;
     }
     $this->getTags();
     foreach ($this->tag_descriptions[NotificationTarget::TAG_LANGUAGE] as $tag => $values) {
         if (!isset($this->datas[$tag])) {
             $this->datas[$tag] = $values['label'];
         }
     }
 }
 /**
  * Get all data needed for template processing
  *
  * @param $event
  * @param $options   array
  **/
 function getDatasForTemplate($event, $options = array())
 {
     //User who tries to add or update an item in DB
     $action = $options['action_user'] ? __('Add the item') : __('Update the item');
     $this->datas['##unicity.action_type##'] = $action;
     $this->datas['##unicity.action_user##'] = $options['action_user'];
     $this->datas['##unicity.date##'] = Html::convDateTime($options['date']);
     if ($item = getItemForItemtype($options['itemtype'])) {
         $this->datas['##unicity.itemtype##'] = $item->getTypeName(1);
         $this->datas['##unicity.message##'] = Html::clean($item->getUnicityErrorMessage($options['label'], $options['field'], $options['double']));
     }
     $this->datas['##unicity.entity##'] = Dropdown::getDropdownName('glpi_entities', $options['entities_id']);
     if ($options['refuse']) {
         $this->datas['##unicity.action##'] = __('Record into the database denied');
     } else {
         $this->datas['##unicity.action##'] = __('Item successfully added but duplicate record on');
     }
     $this->getTags();
     foreach ($this->tag_descriptions[NotificationTarget::TAG_LANGUAGE] as $tag => $values) {
         if (!isset($this->datas[$tag])) {
             $this->datas[$tag] = $values['label'];
         }
     }
 }
Exemple #13
0
 /**
  * @since version 0.85
  **/
 static function getHelpdeskItemtypes()
 {
     global $CFG_GLPI;
     $values = array();
     foreach ($CFG_GLPI["ticket_types"] as $key => $itemtype) {
         if ($item = getItemForItemtype($itemtype)) {
             $values[$itemtype] = $item->getTypeName();
         } else {
             unset($CFG_GLPI["ticket_types"][$key]);
         }
     }
     return $values;
 }
if (isset($_POST["sub_type"]) && class_exists($_POST["sub_type"])) {
    if (!isset($_POST["field"])) {
        $_POST["field"] = key(Rule::getActionsByType($_POST["sub_type"]));
    }
    if (!($item = getItemForItemtype($_POST["sub_type"]))) {
        exit;
    }
    if (!isset($_POST[$item->getRuleIdField()])) {
        exit;
    }
    // Existing action
    if ($_POST['ruleactions_id'] > 0) {
        $already_used = false;
    } else {
        // New action
        $ra = getItemForItemtype($item->getRuleActionClass());
        $used = $ra->getAlreadyUsedForRuleID($_POST[$item->getRuleIdField()], $item->getType());
        $already_used = in_array($_POST["field"], $used);
    }
    echo "<table width='100%'><tr><td width='30%'>";
    $action_type = '';
    if (isset($_POST["action_type"])) {
        $action_type = $_POST["action_type"];
    }
    $randaction = RuleAction::dropdownActions(array('subtype' => $_POST["sub_type"], 'name' => "action_type", 'field' => $_POST["field"], 'value' => $action_type, 'alreadyused' => $already_used));
    echo "</td><td>";
    echo "<span id='action_type_span{$randaction}'>\n";
    echo "</span>\n";
    $paramsaction = array('action_type' => '__VALUE__', 'field' => $_POST["field"], 'sub_type' => $_POST["sub_type"], $item->getForeignKeyField() => $_POST[$item->getForeignKeyField()]);
    Ajax::updateItemOnSelectEvent("dropdown_action_type{$randaction}", "action_type_span{$randaction}", $CFG_GLPI["root_doc"] . "/ajax/ruleactionvalue.php", $paramsaction);
    if (isset($_POST['value'])) {
Exemple #15
0
 /**
  * \brief get the instantiation of the current NetworkPort
  * The instantiation rely on the instantiation_type field and the id of the NetworkPort. If the
  * network port exists, but not its instantiation, then, the instantiation will be empty.
  *
  * @since version 0.84
  *
  * @return the instantiation object or false if the type of instantiation is not known
  **/
 function getInstantiation()
 {
     if (isset($this->fields['instantiation_type']) && in_array($this->fields['instantiation_type'], self::getNetworkPortInstantiations())) {
         if ($instantiation = getItemForItemtype($this->fields['instantiation_type'])) {
             if (!$instantiation->getFromDB($this->getID())) {
                 if (!$instantiation->getEmpty()) {
                     unset($instantiation);
                     return false;
                 }
             }
             return $instantiation;
         }
     }
     return false;
 }
Exemple #16
0
            case Log::HISTORY_DELETE_DEVICE:
                $field = NOT_AVAILABLE;
                if ($item = getItemForItemtype($data["itemtype_link"])) {
                    $field = $item->getTypeName();
                }
                $change = sprintf(__('%1$s: %1$s'), __('Delete the component'), $data["old_value"]);
                break;
            case Log::HISTORY_DISCONNECT_DEVICE:
                if (!($item = getItemForItemtype($data["itemtype_link"]))) {
                    continue;
                }
                $field = $item->getTypeName();
                $change = sprintf(__('%1$s: %2$s'), __('Logout'), $data["old_value"]);
                break;
            case Log::HISTORY_CONNECT_DEVICE:
                if (!($item = getItemForItemtype($data["itemtype_link"]))) {
                    continue;
                }
                $field = $item->getTypeName();
                $change = sprintf(__('%1$s: %2$s'), __('Logout'), $data["new_value"]);
                break;
        }
        //fin du switch
    }
    echo $field . "<td>" . $change;
}
if (!empty($prev)) {
    echo "</td></tr>\n";
}
echo "</table><p>" . __('The list is limited to 100 items and 21 days', 'reports') . "</p></div>\n";
Html::footer();
Exemple #17
0
*/
/** @file
* @brief
*/
// Direct access to file
if (strpos($_SERVER['PHP_SELF'], "rulecriteria.php")) {
    include '../inc/includes.php';
    header("Content-Type: text/html; charset=UTF-8");
    Html::header_nocache();
} else {
    if (!defined('GLPI_ROOT')) {
        die("Sorry. You can't access this file directly");
    }
}
Session::checkLoginUser();
if (isset($_POST["sub_type"]) && ($rule = getItemForItemtype($_POST["sub_type"]))) {
    $criterias = $rule->getAllCriteria();
    if (count($criterias)) {
        // First include -> first of the predefined array
        if (!isset($_POST["criteria"])) {
            $_POST["criteria"] = key($criterias);
        }
        if (isset($criterias[$_POST["criteria"]]['allow_condition'])) {
            $allow_condition = $criterias[$_POST["criteria"]]['allow_condition'];
        } else {
            $allow_condition = array();
        }
        $condparam = array('criterion' => $_POST["criteria"], 'allow_conditions' => $allow_condition);
        if (isset($_POST['condition'])) {
            $condparam['value'] = $_POST['condition'];
        }
 /**
  * Display a line for an object
  *
  * @since version 0.85 (befor in each object with differents parameters)
  *
  * @param $id                 Integer  ID of the object
  * @param $options            array of options
  *      output_type            : Default output type (see Search class / default Search::HTML_OUTPUT)
  *      row_num                : row num used for display
  *      type_for_massiveaction : itemtype for massive action
  *      id_for_massaction      : default 0 means no massive action
  *      followups              : only for Tickets : show followup columns
  */
 static function showShort($id, $options = array())
 {
     global $CFG_GLPI, $DB;
     $p['output_type'] = Search::HTML_OUTPUT;
     $p['row_num'] = 0;
     $p['type_for_massiveaction'] = 0;
     $p['id_for_massiveaction'] = 0;
     $p['followups'] = false;
     if (count($options)) {
         foreach ($options as $key => $val) {
             $p[$key] = $val;
         }
     }
     $rand = mt_rand();
     /// TODO to be cleaned. Get datas and clean display links
     // 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
     $item = new static();
     $candelete = static::canDelete();
     $canupdate = Session::haveRight(static::$rightname, UPDATE);
     $showprivate = Session::haveRight('followup', TicketFollowup::SEEPRIVATE);
     $align = "class='center";
     $align_desc = "class='left";
     if ($p['followups']) {
         $align .= " top'";
         $align_desc .= " top'";
     } else {
         $align .= "'";
         $align_desc .= "'";
     }
     if ($item->getFromDB($id)) {
         $item_num = 1;
         $bgcolor = $_SESSION["glpipriority_" . $item->fields["priority"]];
         echo Search::showNewLine($p['output_type'], $p['row_num'] % 2);
         $check_col = '';
         if (($candelete || $canupdate) && $p['output_type'] == Search::HTML_OUTPUT && $p['id_for_massiveaction']) {
             $check_col = Html::getMassiveActionCheckBox($p['type_for_massiveaction'], $p['id_for_massiveaction']);
         }
         echo Search::showItem($p['output_type'], $check_col, $item_num, $p['row_num'], $align);
         // First column
         $first_col = sprintf(__('%1$s: %2$s'), __('ID'), $item->fields["id"]);
         if ($p['output_type'] == Search::HTML_OUTPUT) {
             $first_col .= "<br><img src='" . static::getStatusIconURL($item->fields["status"]) . "'\n                                alt=\"" . static::getStatus($item->fields["status"]) . "\" title=\"" . static::getStatus($item->fields["status"]) . "\">";
         } else {
             $first_col = sprintf(__('%1$s - %2$s'), $first_col, static::getStatus($item->fields["status"]));
         }
         echo Search::showItem($p['output_type'], $first_col, $item_num, $p['row_num'], $align);
         // Second column
         if ($item->fields['status'] == static::CLOSED) {
             $second_col = sprintf(__('Closed on %s'), ($p['output_type'] == Search::HTML_OUTPUT ? '<br>' : '') . Html::convDateTime($item->fields['closedate']));
         } else {
             if ($item->fields['status'] == static::SOLVED) {
                 $second_col = sprintf(__('Solved on %s'), ($p['output_type'] == Search::HTML_OUTPUT ? '<br>' : '') . Html::convDateTime($item->fields['solvedate']));
             } else {
                 if ($item->fields['begin_waiting_date']) {
                     $second_col = sprintf(__('Put on hold on %s'), ($p['output_type'] == Search::HTML_OUTPUT ? '<br>' : '') . Html::convDateTime($item->fields['begin_waiting_date']));
                 } else {
                     if ($item->fields['due_date']) {
                         $second_col = sprintf(__('%1$s: %2$s'), __('Due date'), ($p['output_type'] == Search::HTML_OUTPUT ? '<br>' : '') . Html::convDateTime($item->fields['due_date']));
                     } else {
                         $second_col = sprintf(__('Opened on %s'), ($p['output_type'] == Search::HTML_OUTPUT ? '<br>' : '') . Html::convDateTime($item->fields['date']));
                     }
                 }
             }
         }
         echo Search::showItem($p['output_type'], $second_col, $item_num, $p['row_num'], $align . " width=130");
         // Second BIS column
         $second_col = Html::convDateTime($item->fields["date_mod"]);
         echo Search::showItem($p['output_type'], $second_col, $item_num, $p['row_num'], $align . " width=90");
         // Second TER column
         if (count($_SESSION["glpiactiveentities"]) > 1) {
             $second_col = Dropdown::getDropdownName('glpi_entities', $item->fields['entities_id']);
             echo Search::showItem($p['output_type'], $second_col, $item_num, $p['row_num'], $align . " width=100");
         }
         // Third Column
         echo Search::showItem($p['output_type'], "<span class='b'>" . static::getPriorityName($item->fields["priority"]) . "</span>", $item_num, $p['row_num'], "{$align} bgcolor='{$bgcolor}'");
         // Fourth Column
         $fourth_col = "";
         foreach ($item->getUsers(CommonITILActor::REQUESTER) as $d) {
             $userdata = getUserName($d["users_id"], 2);
             $fourth_col .= sprintf(__('%1$s %2$s'), "<span class='b'>" . $userdata['name'] . "</span>", Html::showToolTip($userdata["comment"], array('link' => $userdata["link"], 'display' => false)));
             $fourth_col .= "<br>";
         }
         foreach ($item->getGroups(CommonITILActor::REQUESTER) as $d) {
             $fourth_col .= Dropdown::getDropdownName("glpi_groups", $d["groups_id"]);
             $fourth_col .= "<br>";
         }
         echo Search::showItem($p['output_type'], $fourth_col, $item_num, $p['row_num'], $align);
         // Fifth column
         $fifth_col = "";
         foreach ($item->getUsers(CommonITILActor::ASSIGN) as $d) {
             $userdata = getUserName($d["users_id"], 2);
             $fifth_col .= sprintf(__('%1$s %2$s'), "<span class='b'>" . $userdata['name'] . "</span>", Html::showToolTip($userdata["comment"], array('link' => $userdata["link"], 'display' => false)));
             $fifth_col .= "<br>";
         }
         foreach ($item->getGroups(CommonITILActor::ASSIGN) as $d) {
             $fifth_col .= Dropdown::getDropdownName("glpi_groups", $d["groups_id"]);
             $fifth_col .= "<br>";
         }
         foreach ($item->getSuppliers(CommonITILActor::ASSIGN) as $d) {
             $fifth_col .= Dropdown::getDropdownName("glpi_suppliers", $d["suppliers_id"]);
             $fifth_col .= "<br>";
         }
         echo Search::showItem($p['output_type'], $fifth_col, $item_num, $p['row_num'], $align);
         // Sixth Colum
         // Ticket : simple link to item
         $sixth_col = "";
         $is_deleted = false;
         $item_ticket = new Item_Ticket();
         $data = $item_ticket->find("`tickets_id` = " . $item->fields['id']);
         if ($item->getType() == 'Ticket') {
             if (!empty($data)) {
                 foreach ($data as $val) {
                     if (!empty($val["itemtype"]) && $val["items_id"] > 0) {
                         if ($object = getItemForItemtype($val["itemtype"])) {
                             if ($object->getFromDB($val["items_id"])) {
                                 $is_deleted = $object->isDeleted();
                                 $sixth_col .= $object->getTypeName();
                                 $sixth_col .= " - <span class='b'>";
                                 if ($item->canView()) {
                                     $sixth_col .= $object->getLink();
                                 } else {
                                     $sixth_col .= $object->getNameID();
                                 }
                                 $sixth_col .= "</span><br>";
                             }
                         }
                     }
                 }
             } else {
                 $sixth_col = __('General');
             }
             echo Search::showItem($p['output_type'], $sixth_col, $item_num, $p['row_num'], $is_deleted ? " class='center deleted' " : $align);
         }
         // Seventh column
         echo Search::showItem($p['output_type'], "<span class='b'>" . Dropdown::getDropdownName('glpi_itilcategories', $item->fields["itilcategories_id"]) . "</span>", $item_num, $p['row_num'], $align);
         // Eigth column
         $eigth_column = "<span class='b'>" . $item->getName() . "</span>&nbsp;";
         // Add link
         if ($item->canViewItem()) {
             $eigth_column = "<a id='" . $item->getType() . $item->fields["id"] . "{$rand}' href=\"" . $item->getLinkURL() . "\">{$eigth_column}</a>";
             if ($p['followups'] && $p['output_type'] == Search::HTML_OUTPUT) {
                 $eigth_column .= TicketFollowup::showShortForTicket($item->fields["id"]);
             } else {
                 if (method_exists($item, 'numberOfFollowups')) {
                     $eigth_column = sprintf(__('%1$s (%2$s)'), $eigth_column, sprintf(__('%1$s - %2$s'), $item->numberOfFollowups($showprivate), $item->numberOfTasks($showprivate)));
                 } else {
                     $eigth_column = sprintf(__('%1$s (%2$s)'), $eigth_column, $item->numberOfTasks($showprivate));
                 }
             }
         }
         if ($p['output_type'] == Search::HTML_OUTPUT) {
             $eigth_column = sprintf(__('%1$s %2$s'), $eigth_column, Html::showToolTip(Html::clean(Html::entity_decode_deep($item->fields["content"])), array('display' => false, 'applyto' => $item->getType() . $item->fields["id"] . $rand)));
         }
         echo Search::showItem($p['output_type'], $eigth_column, $item_num, $p['row_num'], $align_desc . " width='200'");
         //tenth column
         $tenth_column = '';
         $planned_infos = '';
         $tasktype = $item->getType() . "Task";
         $plan = new $tasktype();
         $items = array();
         foreach ($DB->request($plan->getTable(), array($item->getForeignKeyField() => $item->fields['id'])) as $plan) {
             if (isset($plan['begin']) && $plan['begin']) {
                 $items[$plan['id']] = $plan['id'];
                 $planned_infos .= sprintf(__('From %s') . ($p['output_type'] == Search::HTML_OUTPUT ? '<br>' : ''), Html::convDateTime($plan['begin']));
                 $planned_infos .= sprintf(__('To %s') . ($p['output_type'] == Search::HTML_OUTPUT ? '<br>' : ''), Html::convDateTime($plan['end']));
                 if ($plan['users_id_tech']) {
                     $planned_infos .= sprintf(__('By %s') . ($p['output_type'] == Search::HTML_OUTPUT ? '<br>' : ''), getUserName($plan['users_id_tech']));
                 }
                 $planned_infos .= "<br>";
             }
         }
         unset($i, $j);
         $tenth_column = count($items);
         if ($tenth_column) {
             $tenth_column = "<span class='pointer'\n                              id='" . $item->getType() . $item->fields["id"] . "planning{$rand}'>" . $tenth_column . '</span>';
             $tenth_column = sprintf(__('%1$s %2$s'), $tenth_column, Html::showToolTip($planned_infos, array('display' => false, 'applyto' => $item->getType() . $item->fields["id"] . "planning" . $rand)));
         }
         echo Search::showItem($p['output_type'], $tenth_column, $item_num, $p['row_num'], $align_desc . " width='150'");
         // Finish Line
         echo Search::showEndLine($p['output_type']);
     } else {
         echo "<tr class='tab_bg_2'>";
         echo "<td colspan='6' ><i>" . __('No item in progress.') . "</i></td></tr>";
     }
 }
 /**
  * Print the HTML array for Items linked to a problem
  *
  * @param $problem Problem object
  *
  * @return Nothing (display)
  **/
 static function showForProblem(Problem $problem)
 {
     global $DB, $CFG_GLPI;
     $instID = $problem->fields['id'];
     if (!$problem->can($instID, READ)) {
         return false;
     }
     $canedit = $problem->canEdit($instID);
     $rand = mt_rand();
     $query = "SELECT DISTINCT `itemtype`\n                FROM `glpi_items_problems`\n                WHERE `glpi_items_problems`.`problems_id` = '{$instID}'\n                ORDER BY `itemtype`";
     $result = $DB->query($query);
     $number = $DB->numrows($result);
     if ($canedit) {
         echo "<div class='firstbloc'>";
         echo "<form name='problemitem_form{$rand}' id='problemitem_form{$rand}' method='post'\n                action='" . Toolbox::getItemTypeFormURL(__CLASS__) . "'>";
         echo "<table class='tab_cadre_fixe'>";
         echo "<tr class='tab_bg_2'><th colspan='2'>" . __('Add an item') . "</th></tr>";
         echo "<tr class='tab_bg_1'><td>";
         $types = array();
         foreach ($problem->getAllTypesForHelpdesk() as $key => $val) {
             $types[] = $key;
         }
         Dropdown::showSelectItemFromItemtypes(array('itemtypes' => $types, 'entity_restrict' => $problem->fields['is_recursive'] ? getSonsOf('glpi_entities', $problem->fields['entities_id']) : $problem->fields['entities_id']));
         echo "</td><td class='center' width='30%'>";
         echo "<input type='submit' name='add' value=\"" . _sx('button', 'Add') . "\" class='submit'>";
         echo "<input type='hidden' name='problems_id' value='{$instID}'>";
         echo "</td></tr>";
         echo "</table>";
         Html::closeForm();
         echo "</div>";
     }
     echo "<div class='spaced'>";
     if ($canedit && $number) {
         Html::openMassiveActionsForm('mass' . __CLASS__ . $rand);
         $massiveactionparams = array('container' => 'mass' . __CLASS__ . $rand);
         Html::showMassiveActions($massiveactionparams);
     }
     echo "<table class='tab_cadre_fixehov'>";
     $header_begin = "<tr>";
     $header_top = '';
     $header_bottom = '';
     $header_end = '';
     if ($canedit && $number) {
         $header_top .= "<th width='10'>" . Html::getCheckAllAsCheckbox('mass' . __CLASS__ . $rand);
         $header_top .= "</th>";
         $header_bottom .= "<th width='10'>" . Html::getCheckAllAsCheckbox('mass' . __CLASS__ . $rand);
         $header_bottom .= "</th>";
     }
     $header_end .= "<th>" . __('Type') . "</th>";
     $header_end .= "<th>" . __('Entity') . "</th>";
     $header_end .= "<th>" . __('Name') . "</th>";
     $header_end .= "<th>" . __('Serial number') . "</th>";
     $header_end .= "<th>" . __('Inventory number') . "</th></tr>";
     echo $header_begin . $header_top . $header_end;
     $totalnb = 0;
     for ($i = 0; $i < $number; $i++) {
         $itemtype = $DB->result($result, $i, "itemtype");
         if (!($item = getItemForItemtype($itemtype))) {
             continue;
         }
         if ($item->canView()) {
             $itemtable = getTableForItemType($itemtype);
             $query = "SELECT `{$itemtable}`.*,\n                             `glpi_items_problems`.`id` AS IDD,\n                             `glpi_entities`.`id` AS entity\n                      FROM `glpi_items_problems`,\n                           `{$itemtable}`";
             if ($itemtype != 'Entity') {
                 $query .= " LEFT JOIN `glpi_entities`\n                                 ON (`{$itemtable}`.`entities_id`=`glpi_entities`.`id`) ";
             }
             $query .= " WHERE `{$itemtable}`.`id` = `glpi_items_problems`.`items_id`\n                              AND `glpi_items_problems`.`itemtype` = '{$itemtype}'\n                              AND `glpi_items_problems`.`problems_id` = '{$instID}'";
             if ($item->maybeTemplate()) {
                 $query .= " AND `{$itemtable}`.`is_template` = '0'";
             }
             $query .= getEntitiesRestrictRequest(" AND", $itemtable, '', '', $item->maybeRecursive()) . "\n                      ORDER BY `glpi_entities`.`completename`, `{$itemtable}`.`name`";
             $result_linked = $DB->query($query);
             $nb = $DB->numrows($result_linked);
             for ($prem = true; $data = $DB->fetch_assoc($result_linked); $prem = false) {
                 $name = $data["name"];
                 if ($_SESSION["glpiis_ids_visible"] || empty($data["name"])) {
                     $name = sprintf(__('%1$s (%2$s)'), $name, $data["id"]);
                 }
                 $link = $itemtype::getFormURLWithID($data['id']);
                 $namelink = "<a href=\"" . $link . "\">" . $name . "</a>";
                 echo "<tr class='tab_bg_1'>";
                 if ($canedit) {
                     echo "<td width='10'>";
                     Html::showMassiveActionCheckBox(__CLASS__, $data["IDD"]);
                     echo "</td>";
                 }
                 if ($prem) {
                     $typename = $item->getTypeName($nb);
                     echo "<td class='center top' rowspan='{$nb}'>" . ($nb > 1 ? sprintf(__('%1$s: %2$s'), $typename, $nb) : $typename) . "</td>";
                 }
                 echo "<td class='center'>";
                 echo Dropdown::getDropdownName("glpi_entities", $data['entity']) . "</td>";
                 echo "<td class='center" . (isset($data['is_deleted']) && $data['is_deleted'] ? " tab_bg_2_2'" : "'");
                 echo ">" . $namelink . "</td>";
                 echo "<td class='center'>" . (isset($data["serial"]) ? "" . $data["serial"] . "" : "-") . "</td>";
                 echo "<td class='center'>" . (isset($data["otherserial"]) ? "" . $data["otherserial"] . "" : "-") . "</td>";
                 echo "</tr>";
             }
             $totalnb += $nb;
         }
     }
     if ($number) {
         echo $header_begin . $header_bottom . $header_end;
     }
     echo "</table>";
     if ($canedit && $number) {
         $massiveactionparams['ontop'] = false;
         Html::showMassiveActions($massiveactionparams);
         Html::closeForm();
     }
     echo "</div>";
 }
    Html::header_nocache();
}
if (!defined('GLPI_ROOT')) {
    die("Can not acces directly to this file");
}
Session::checkLoginUser();
if (isset($_POST['searchtype'])) {
    $searchopt = $_POST['searchopt'];
    $_POST['value'] = rawurldecode($_POST['value']);
    $fieldname = 'criteria';
    if (isset($_POST['meta']) && $_POST['meta']) {
        $fieldname = 'metacriteria';
    }
    $inputname = $fieldname . '[' . $_POST['num'] . '][value]';
    $display = false;
    $item = getItemForItemtype($_POST['itemtype']);
    $options2 = array();
    $options2['value'] = $_POST['value'];
    $options2['width'] = '100%';
    // For tree dropdpowns
    $options2['permit_select_parent'] = true;
    switch ($_POST['searchtype']) {
        case "equals":
        case "notequals":
        case "morethan":
        case "lessthan":
        case "under":
        case "notunder":
            if (!$display && isset($searchopt['field'])) {
                // Specific cases
                switch ($searchopt['table'] . "." . $searchopt['field']) {
 /**
  * @param $target
  * @param $date1
  * @param $date2
  * @param $start
  **/
 static function showItems($target, $date1, $date2, $start)
 {
     global $DB, $CFG_GLPI;
     $view_entities = Session::isMultiEntitiesMode();
     if ($view_entities) {
         $entities = getAllDatasFromTable('glpi_entities');
     }
     $output_type = Search::HTML_OUTPUT;
     if (isset($_GET["display_type"])) {
         $output_type = $_GET["display_type"];
     }
     if (empty($date2)) {
         $date2 = date("Y-m-d");
     }
     $date2 .= " 23:59:59";
     // 1 an par defaut
     if (empty($date1)) {
         $date1 = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d"), date("Y") - 1));
     }
     $date1 .= " 00:00:00";
     $query = "SELECT `glpi_items_tickets`.`itemtype`,\n                       `glpi_items_tickets`.`items_id`,\n                       COUNT(*) AS NB\n                FROM `glpi_tickets`\n                LEFT JOIN `glpi_items_tickets`\n                   ON (`glpi_tickets`.`id` = `glpi_items_tickets`.`tickets_id`)\n                WHERE `date` <= '{$date2}'\n                      AND `glpi_tickets`.`date` >= '{$date1}' " . getEntitiesRestrictRequest("AND", "glpi_tickets") . "\n                      AND `glpi_items_tickets`.`itemtype` <> ''\n                      AND `glpi_items_tickets`.`items_id` > 0\n                GROUP BY `glpi_items_tickets`.`itemtype`, `glpi_items_tickets`.`items_id`\n                ORDER BY NB DESC";
     $result = $DB->query($query);
     $numrows = $DB->numrows($result);
     if ($numrows > 0) {
         if ($output_type == Search::HTML_OUTPUT) {
             Html::printPager($start, $numrows, $target, "date1=" . $date1 . "&amp;date2=" . $date2 . "&amp;type=hardwares&amp;start={$start}", 'Stat');
             echo "<div class='center'>";
         }
         $end_display = $start + $_SESSION['glpilist_limit'];
         if (isset($_GET['export_all'])) {
             $end_display = $numrows;
         }
         echo Search::showHeader($output_type, $end_display - $start + 1, 2, 1);
         $header_num = 1;
         echo Search::showNewLine($output_type);
         echo Search::showHeaderItem($output_type, _n('Associated element', 'Associated elements', 2), $header_num);
         if ($view_entities) {
             echo Search::showHeaderItem($output_type, __('Entity'), $header_num);
         }
         echo Search::showHeaderItem($output_type, __('Number of tickets'), $header_num);
         echo Search::showEndLine($output_type);
         $DB->data_seek($result, $start);
         $i = $start;
         if (isset($_GET['export_all'])) {
             $start = 0;
         }
         for ($i = $start; $i < $numrows && $i < $end_display; $i++) {
             $item_num = 1;
             // Get data and increment loop variables
             $data = $DB->fetch_assoc($result);
             if (!($item = getItemForItemtype($data["itemtype"]))) {
                 continue;
             }
             if ($item->getFromDB($data["items_id"])) {
                 echo Search::showNewLine($output_type, $i % 2);
                 echo Search::showItem($output_type, sprintf(__('%1$s - %2$s'), $item->getTypeName(), $item->getLink()), $item_num, $i - $start + 1, "class='center'" . " " . ($item->isDeleted() ? " class='deleted' " : ""));
                 if ($view_entities) {
                     $ent = $item->getEntityID();
                     $ent = $entities[$ent]['completename'];
                     echo Search::showItem($output_type, $ent, $item_num, $i - $start + 1, "class='center'" . " " . ($item->isDeleted() ? " class='deleted' " : ""));
                 }
                 echo Search::showItem($output_type, $data["NB"], $item_num, $i - $start + 1, "class='center'" . " " . ($item->isDeleted() ? " class='deleted' " : ""));
             }
         }
         echo Search::showFooter($output_type);
         if ($output_type == Search::HTML_OUTPUT) {
             echo "</div>";
         }
     }
 }
<?php

include '../../../inc/includes.php';
header("Content-Type: text/html; charset=UTF-8");
Html::header_nocache();
Session::checkLoginUser();
if (!isset($_POST['type'])) {
    exit;
}
if (!isset($_POST['parenttype'])) {
    exit;
}
if (($item = getItemForItemtype($_POST['type'])) && ($parent = getItemForItemtype($_POST['parenttype']))) {
    if (isset($_POST[$parent->getForeignKeyField()]) && isset($_POST["id"]) && $parent->getFromDB($_POST[$parent->getForeignKeyField()])) {
        PluginTalkTicket::showSubForm($item, $_POST["id"], array('parent' => $parent, 'tickets_id' => $_POST["tickets_id"]));
    } else {
        _e('Access denied');
    }
} else {
    if ($_POST['type'] == "Solution") {
        PluginTalkTicket::showSubFormSolution($_POST["tickets_id"]);
    }
}
Html::ajaxFooter();
Exemple #23
0
 /**
  * Show items of the current user
  *
  * @param $tech
  **/
 function showItems($tech)
 {
     global $DB, $CFG_GLPI;
     $ID = $this->getField('id');
     if ($tech) {
         $type_user = $CFG_GLPI['linkuser_tech_types'];
         $type_group = $CFG_GLPI['linkgroup_tech_types'];
         $field_user = '******';
         $field_group = 'groups_id_tech';
     } else {
         $type_user = $CFG_GLPI['linkuser_types'];
         $type_group = $CFG_GLPI['linkgroup_types'];
         $field_user = '******';
         $field_group = 'groups_id';
     }
     $group_where = "";
     $groups = array();
     $query = "SELECT `glpi_groups_users`.`groups_id`,\n                       `glpi_groups`.`name`\n                FROM `glpi_groups_users`\n                LEFT JOIN `glpi_groups` ON (`glpi_groups`.`id` = `glpi_groups_users`.`groups_id`)\n                WHERE `glpi_groups_users`.`users_id` = '{$ID}'";
     $result = $DB->query($query);
     $number = $DB->numrows($result);
     if ($number > 0) {
         $first = true;
         while ($data = $DB->fetch_assoc($result)) {
             if ($first) {
                 $first = false;
             } else {
                 $group_where .= " OR ";
             }
             $group_where .= " `" . $field_group . "` = '" . $data["groups_id"] . "' ";
             $groups[$data["groups_id"]] = $data["name"];
         }
     }
     echo "<div class='spaced'><table class='tab_cadre_fixe'>";
     echo "<tr><th>" . __('Type') . "</th>";
     echo "<th>" . __('Entity') . "</th>";
     echo "<th>" . __('Name') . "</th>";
     echo "<th>" . __('Serial number') . "</th>";
     echo "<th>" . __('Inventory number') . "</th>";
     echo "<th>" . __('Status') . "</th>";
     echo "<th>&nbsp;</th></tr>";
     foreach ($type_user as $itemtype) {
         if (!($item = getItemForItemtype($itemtype))) {
             continue;
         }
         if ($item->canView()) {
             $itemtable = getTableForItemType($itemtype);
             $query = "SELECT *\n                      FROM `{$itemtable}`\n                      WHERE `" . $field_user . "` = '{$ID}'";
             if ($item->maybeTemplate()) {
                 $query .= " AND `is_template` = '0' ";
             }
             if ($item->maybeDeleted()) {
                 $query .= " AND `is_deleted` = '0' ";
             }
             $result = $DB->query($query);
             $type_name = $item->getTypeName();
             if ($DB->numrows($result) > 0) {
                 while ($data = $DB->fetch_assoc($result)) {
                     $cansee = $item->can($data["id"], "r");
                     $link = $data["name"];
                     if ($cansee) {
                         $link_item = Toolbox::getItemTypeFormURL($itemtype);
                         if ($_SESSION["glpiis_ids_visible"] || empty($link)) {
                             $link = sprintf(__('%1$s (%2$s)'), $link, $data["id"]);
                         }
                         $link = "<a href='" . $link_item . "?id=" . $data["id"] . "'>" . $link . "</a>";
                     }
                     $linktype = "";
                     if ($data[$field_user] == $ID) {
                         $linktype = self::getTypeName(1);
                     }
                     echo "<tr class='tab_bg_1'><td class='center'>{$type_name}</td>";
                     echo "<td class='center'>" . Dropdown::getDropdownName("glpi_entities", $data["entities_id"]) . "</td>";
                     echo "<td class='center'>{$link}</td>";
                     echo "<td class='center'>";
                     if (isset($data["serial"]) && !empty($data["serial"])) {
                         echo $data["serial"];
                     } else {
                         echo '&nbsp;';
                     }
                     echo "</td><td class='center'>";
                     if (isset($data["otherserial"]) && !empty($data["otherserial"])) {
                         echo $data["otherserial"];
                     } else {
                         echo '&nbsp;';
                     }
                     echo "</td><td class='center'>";
                     if (isset($data["states_id"])) {
                         echo Dropdown::getDropdownName("glpi_states", $data['states_id']);
                     } else {
                         echo '&nbsp;';
                     }
                     echo "</td><td class='center'>{$linktype}</td></tr>";
                 }
             }
         }
     }
     echo "</table></div>";
     if (!empty($group_where)) {
         echo "<div class='spaced'><table class='tab_cadre_fixe'><tr>" . "<th>" . __('Type') . "</th>" . "<th>" . __('Entity') . "</th>" . "<th>" . __('Name') . "</th>" . "<th>" . __('Serial number') . "</th>" . "<th>" . __('Inventory number') . "</th>" . "<th>" . __('Status') . "</th>" . "<th>&nbsp;</th></tr>";
         foreach ($type_group as $itemtype) {
             if (!($item = getItemForItemtype($itemtype))) {
                 continue;
             }
             if ($item->canView()) {
                 $itemtable = getTableForItemType($itemtype);
                 $query = "SELECT *\n                         FROM `{$itemtable}`\n                         WHERE {$group_where}";
                 if ($item->maybeTemplate()) {
                     $query .= " AND `is_template` = '0' ";
                 }
                 if ($item->maybeDeleted()) {
                     $query .= " AND `is_deleted` = '0' ";
                 }
                 $result = $DB->query($query);
                 $type_name = $item->getTypeName();
                 if ($DB->numrows($result) > 0) {
                     while ($data = $DB->fetch_assoc($result)) {
                         $cansee = $item->can($data["id"], "r");
                         $link = $data["name"];
                         if ($cansee) {
                             $link_item = Toolbox::getItemTypeFormURL($itemtype);
                             if ($_SESSION["glpiis_ids_visible"] || empty($link)) {
                                 $link = sprintf(__('%1$s (%2$s)'), $link, $data["id"]);
                             }
                             $link = "<a href='" . $link_item . "?id=" . $data["id"] . "'>" . $link . "</a>";
                         }
                         $linktype = "";
                         if (isset($groups[$data[$field_group]])) {
                             $linktype = sprintf(__('%1$s = %2$s'), _n('Group', 'Groups', 1), $groups[$data[$field_group]]);
                         }
                         echo "<tr class='tab_bg_1'><td class='center'>{$type_name}</td>";
                         echo "<td class='center'>" . Dropdown::getDropdownName("glpi_entities", $data["entities_id"]);
                         echo "</td><td class='center'>{$link}</td>";
                         echo "<td class='center'>";
                         if (isset($data["serial"]) && !empty($data["serial"])) {
                             echo $data["serial"];
                         } else {
                             echo '&nbsp;';
                         }
                         echo "</td><td class='center'>";
                         if (isset($data["otherserial"]) && !empty($data["otherserial"])) {
                             echo $data["otherserial"];
                         } else {
                             echo '&nbsp;';
                         }
                         echo "</td><td class='center'>";
                         if (isset($data["states_id"])) {
                             echo Dropdown::getDropdownName("glpi_states", $data['states_id']);
                         } else {
                             echo '&nbsp;';
                         }
                         echo "</td><td class='center'>{$linktype}</td></tr>";
                     }
                 }
             }
         }
         echo "</table></div>";
     }
 }
Exemple #24
0
 /**
  * @param $itemtype
  * @param $items_id
  * @param $unaffect
  **/
 static function cleanItemDeviceDBOnItemDelete($itemtype, $items_id, $unaffect)
 {
     global $DB;
     foreach (self::getItemAffinities($itemtype) as $link_type) {
         $link = getItemForItemtype($link_type);
         if ($link) {
             if ($unaffect) {
                 $query = "SELECT `id`\n                         FROM `" . $link->getTable() . "`\n                         WHERE `itemtype` = '{$itemtype}'\n                               AND `items_id` = '{$items_id}'";
                 $input = array('items_id' => 0, 'itemtype' => '');
                 foreach ($DB->request($query) as $data) {
                     $input['id'] = $data['id'];
                     $link->update($input);
                 }
             } else {
                 $link->cleanDBOnItemDelete($itemtype, $items_id);
             }
         }
     }
 }
 /**
  * show defined display preferences for a user
  *
  * @param $users_id integer user ID
  **/
 static function showForUser($users_id)
 {
     global $DB;
     $url = Toolbox::getItemTypeFormURL(__CLASS__);
     $query = "SELECT `itemtype`,\n                       COUNT(*) AS nb\n                FROM `glpi_displaypreferences`\n                WHERE `users_id` = '{$users_id}'\n                GROUP BY `itemtype`";
     $req = $DB->request($query);
     if ($req->numrows() > 0) {
         $rand = mt_rand();
         echo "<div class='spaced'>";
         Html::openMassiveActionsForm('mass' . __CLASS__ . $rand);
         $massiveactionparams = array('width' => 400, 'height' => 200, 'container' => 'mass' . __CLASS__ . $rand, 'specific_actions' => array(__CLASS__ . MassiveAction::CLASS_ACTION_SEPARATOR . 'delete_for_user' => _x('button', 'Delete permanently')), 'extraparams' => array('massive_action_fields' => array('users_id')));
         Html::showMassiveActions($massiveactionparams);
         echo Html::hidden('users_id', array('value' => $users_id, 'data-glpicore-ma-tags' => 'common'));
         echo "<table class='tab_cadre_fixe'>";
         echo "<tr>";
         echo "<th width='10'>";
         Html::checkAllAsCheckbox('mass' . __CLASS__ . $rand);
         echo "</th>";
         echo "<th colspan='2'>" . __('Type') . "</th></tr>";
         foreach ($req as $data) {
             echo "<tr class='tab_bg_1'><td width='10'>";
             Html::showMassiveActionCheckBox(__CLASS__, $data["itemtype"]);
             echo "</td>";
             if ($item = getItemForItemtype($data["itemtype"])) {
                 $name = $item->getTypeName(1);
             } else {
                 $name = $data["itemtype"];
             }
             echo "<td>{$name}</td><td class='numeric'>" . $data['nb'] . "</td>";
             echo "</tr>";
         }
         echo "</table>";
         $massiveactionparams['ontop'] = false;
         Html::showMassiveActions($massiveactionparams);
         Html::closeForm();
         echo "</div>";
     } else {
         echo "<table class='tab_cadre_fixe'>";
         echo "<tr class='tab_bg_2'><td class='b center'>" . __('No item found') . "</td></tr>";
         echo "</table>";
     }
 }
Exemple #26
0
 /**
  * @param $itemtype
  * @param $field_num
  **/
 static function getActionsFor($itemtype, $field_num)
 {
     $searchopt =& self::getOptions($itemtype);
     $actions = array('contains' => __('contains'), 'searchopt' => array());
     if (isset($searchopt[$field_num])) {
         $actions['searchopt'] = $searchopt[$field_num];
         // Force search type
         if (isset($actions['searchopt']['searchtype'])) {
             // Reset search option
             $actions = array();
             $actions['searchopt'] = $searchopt[$field_num];
             if (!is_array($actions['searchopt']['searchtype'])) {
                 $actions['searchopt']['searchtype'] = array($actions['searchopt']['searchtype']);
             }
             foreach ($actions['searchopt']['searchtype'] as $searchtype) {
                 switch ($searchtype) {
                     case "equals":
                         $actions['equals'] = __('is');
                         break;
                     case "notequals":
                         $actions['notequals'] = __('is not');
                         break;
                     case "contains":
                         $actions['contains'] = __('contains');
                         break;
                     case "under":
                         $actions['under'] = __('under');
                         break;
                     case "notunder":
                         $actions['notunder'] = __('not under');
                         break;
                     case "lessthan":
                         $actions['lessthan'] = __('before');
                         break;
                     case "morethan":
                         $actions['morethan'] = __('after');
                         break;
                 }
             }
             return $actions;
         }
         if (isset($searchopt[$field_num]['datatype'])) {
             switch ($searchopt[$field_num]['datatype']) {
                 case 'count':
                 case 'number':
                     $opt = array('contains' => __('contains'), 'equals' => __('is'), 'notequals' => __('is not'), 'searchopt' => $searchopt[$field_num]);
                     // No is / isnot if no limits defined
                     if (!isset($searchopt[$field_num]['min']) && !isset($searchopt[$field_num]['max'])) {
                         unset($opt['equals']);
                         unset($opt['notequals']);
                     }
                     return $opt;
                 case 'bool':
                     return array('equals' => __('is'), 'notequals' => __('is not'), 'contains' => __('contains'), 'searchopt' => $searchopt[$field_num]);
                 case 'right':
                     return array('equals' => __('is'), 'notequals' => __('is not'), 'searchopt' => $searchopt[$field_num]);
                 case 'itemtypename':
                     return array('equals' => __('is'), 'notequals' => __('is not'), 'searchopt' => $searchopt[$field_num]);
                 case 'date':
                 case 'datetime':
                 case 'date_delay':
                     return array('equals' => __('is'), 'notequals' => __('is not'), 'lessthan' => __('before'), 'morethan' => __('after'), 'contains' => __('contains'), 'searchopt' => $searchopt[$field_num]);
             }
         }
         //          switch ($searchopt[$field_num]['table']) {
         //             case 'glpi_users_validation' :
         //                return array('equals'    => __('is'),
         //                             'notequals' => __('is not'),
         //                             'searchopt' => $searchopt[$field_num]);
         //          }
         switch ($searchopt[$field_num]['field']) {
             case 'id':
                 return array('equals' => __('is'), 'notequals' => __('is not'), 'searchopt' => $searchopt[$field_num]);
             case 'name':
             case 'completename':
                 $actions = array('contains' => __('contains'), 'equals' => __('is'), 'notequals' => __('is not'), 'searchopt' => $searchopt[$field_num]);
                 // Specific case of TreeDropdown : add under
                 $itemtype_linked = getItemTypeForTable($searchopt[$field_num]['table']);
                 if ($itemlinked = getItemForItemtype($itemtype_linked)) {
                     if ($itemlinked instanceof CommonTreeDropdown) {
                         $actions['under'] = __('under');
                         $actions['notunder'] = __('not under');
                     }
                     return $actions;
                 }
         }
     }
     return $actions;
 }
Exemple #27
0
 /**
  * Cron action on reservation : alert on end of reservations
  *
  * @param $task to log, if NULL use display (default NULL)
  *
  * @return 0 : nothing to do 1 : done with success
  **/
 static function cronReservation($task = NULL)
 {
     global $DB, $CFG_GLPI;
     if (!$CFG_GLPI["use_mailing"]) {
         return 0;
     }
     $message = array();
     $cron_status = 0;
     $items_infos = array();
     $items_messages = array();
     foreach (Entity::getEntitiesToNotify('use_reservations_alert') as $entity => $value) {
         $secs = $value * HOUR_TIMESTAMP;
         // Reservation already begin and reservation ended in $value hours
         $query_end = "SELECT `glpi_reservationitems`.*,\n                              `glpi_reservations`.`end` AS `end`,\n                              `glpi_reservations`.`id` AS `resaid`\n                       FROM `glpi_reservations`\n                       LEFT JOIN `glpi_alerts`\n                           ON (`glpi_reservations`.`id` = `glpi_alerts`.`items_id`\n                               AND `glpi_alerts`.`itemtype` = 'Reservation'\n                               AND `glpi_alerts`.`type` = '" . Alert::END . "')\n                       LEFT JOIN `glpi_reservationitems`\n                           ON (`glpi_reservations`.`reservationitems_id`\n                                 = `glpi_reservationitems`.`id`)\n                       WHERE `glpi_reservationitems`.`entities_id` = '{$entity}'\n                             AND (UNIX_TIMESTAMP(`glpi_reservations`.`end`) - {$secs}) < UNIX_TIMESTAMP()\n                             AND `glpi_reservations`.`begin` < NOW()\n                             AND `glpi_alerts`.`date` IS NULL";
         foreach ($DB->request($query_end) as $data) {
             if ($item_resa = getItemForItemtype($data['itemtype'])) {
                 if ($item_resa->getFromDB($data["items_id"])) {
                     $data['item_name'] = $item_resa->getName();
                     $data['entity'] = $entity;
                     $items_infos[$entity][$data['resaid']] = $data;
                     if (!isset($items_messages[$entity])) {
                         $items_messages[$entity] = __('Device reservations expiring today') . "<br>";
                     }
                     $items_messages[$entity] .= sprintf(__('%1$s - %2$s'), $item_resa->getTypeName(), $item_resa->getName()) . "<br>";
                 }
             }
         }
     }
     foreach ($items_infos as $entity => $items) {
         $resitem = new self();
         if (NotificationEvent::raiseEvent("alert", new Reservation(), array('entities_id' => $entity, 'items' => $items))) {
             $message = $items_messages[$entity];
             $cron_status = 1;
             if ($task) {
                 $task->addVolume(1);
                 $task->log(sprintf(__('%1$s: %2$s') . "\n", Dropdown::getDropdownName("glpi_entities", $entity), $message));
             } else {
                 //TRANS: %1$s is a name, %2$s is text of message
                 Session::addMessageAfterRedirect(sprintf(__('%1$s: %2$s'), Dropdown::getDropdownName("glpi_entities", $entity), $message));
             }
             $alert = new Alert();
             $input["itemtype"] = 'Reservation';
             $input["type"] = Alert::END;
             foreach ($items as $resaid => $item) {
                 $input["items_id"] = $resaid;
                 $alert->add($input);
                 unset($alert->fields['id']);
             }
         } else {
             $entityname = Dropdown::getDropdownName('glpi_entities', $entity);
             //TRANS: %s is entity name
             $msg = sprintf(__('%1$s: %2$s'), $entityname, __('Send reservation alert failed'));
             if ($task) {
                 $task->log($msg);
             } else {
                 Session::addMessageAfterRedirect($msg, false, ERROR);
             }
         }
     }
     return $cron_status;
 }
 /**
  * Print the HTML array for device on link
  *
  * @param $link : Link
  *
  * @return Nothing (display)
  **/
 static function showForLink($link)
 {
     global $DB, $CFG_GLPI;
     $links_id = $link->getField('id');
     $canedit = $link->can($links_id, 'w');
     $rand = mt_rand();
     if (!Session::haveRight("link", "r") || !$link->can($links_id, 'r')) {
         return false;
     }
     $query = "SELECT *\n                FROM `glpi_links_itemtypes`\n                WHERE `links_id` = '{$links_id}'\n                ORDER BY `itemtype`";
     $result = $DB->query($query);
     $types = array();
     $used = array();
     if ($numrows = $DB->numrows($result)) {
         while ($data = $DB->fetch_assoc($result)) {
             $types[$data['id']] = $data;
             $used[$data['itemtype']] = $data['itemtype'];
         }
     }
     if ($canedit) {
         echo "<div class='firstbloc'>";
         echo "<form name='changeticket_form{$rand}' id='changeticket_form{$rand}' method='post'\n                action='" . Toolbox::getItemTypeFormURL(__CLASS__) . "'>";
         echo "<table class='tab_cadre_fixe'>";
         echo "<tr class='tab_bg_2'><th colspan='2'>" . __('Add an item type') . "</th></tr>";
         echo "<tr class='tab_bg_2'><td class='right'>";
         echo "<input type='hidden' name='links_id' value='{$links_id}'>";
         Dropdown::showItemTypes('itemtype', $CFG_GLPI["link_types"], array('used' => $used));
         echo "</td><td class='center'>";
         echo "<input type='submit' name='add' value=\"" . _sx('button', 'Add') . "\" class='submit'>";
         echo "</td></tr>";
         echo "</table>";
         Html::closeForm();
         echo "</div>";
     }
     echo "<div class='spaced'>";
     if ($canedit && $numrows) {
         Html::openMassiveActionsForm('mass' . __CLASS__ . $rand);
         $massiveactionparams = array('num_displayed' => $numrows);
         Html::showMassiveActions(__CLASS__, $massiveactionparams);
     }
     echo "<table class='tab_cadre_fixe'>";
     echo "<tr>";
     if ($canedit && $numrows) {
         echo "<th width='10'>" . Html::getCheckAllAsCheckbox('mass' . __CLASS__ . $rand) . "</th>";
     }
     echo "<th>" . __('Type') . "</th>";
     echo "</tr>";
     foreach ($types as $data) {
         $typename = NOT_AVAILABLE;
         if ($item = getItemForItemtype($data['itemtype'])) {
             $typename = $item->getTypeName(1);
             echo "<tr class='tab_bg_1'>";
             if ($canedit) {
                 echo "<td>";
                 Html::showMassiveActionCheckBox(__CLASS__, $data["id"]);
                 echo "</td>";
             }
             echo "<td class='center'>{$typename}</td>";
             echo "</tr>";
         }
     }
     echo "</table>";
     if ($canedit && $numrows) {
         $massiveactionparams['ontop'] = false;
         Html::showMassiveActions(__CLASS__, $massiveactionparams);
         Html::closeForm();
     }
     echo "</div>";
 }
 /**
  * Can I change recursive flag to false
  * check if there is "linked" object in another entity
  *
  * Overloaded from CommonDBTM
  *
  * @since version 0.85
  *
  * @return booleen
  **/
 function canUnrecurs()
 {
     global $DB;
     $ID = $this->fields['id'];
     if ($ID < 0 || !$this->fields['is_recursive']) {
         return true;
     }
     if (!parent::canUnrecurs()) {
         return false;
     }
     $entities = "(" . $this->fields['entities_id'];
     foreach (getAncestorsOf("glpi_entities", $this->fields['entities_id']) as $papa) {
         $entities .= ",{$papa}";
     }
     $entities .= ")";
     // RELATION : device -> item_device -> item
     $linktype = static::getItem_DeviceType();
     $linktable = getTableForItemType($linktype);
     $sql = "SELECT `itemtype`,\n                     GROUP_CONCAT(DISTINCT `items_id`) AS ids\n              FROM `{$linktable}`\n              WHERE `{$linktable}`.`" . $this->getForeignKeyField() . "` = '{$ID}'\n              GROUP BY `itemtype`";
     foreach ($DB->request($sql) as $data) {
         if (!empty($data["itemtype"])) {
             $itemtable = getTableForItemType($data["itemtype"]);
             if ($item = getItemForItemtype($data["itemtype"])) {
                 // For each itemtype which are entity dependant
                 if ($item->isEntityAssign()) {
                     if (countElementsInTable($itemtable, "id IN (" . $data["ids"] . ")\n                                           AND entities_id NOT IN {$entities}") > 0) {
                         return false;
                     }
                 }
             }
         }
     }
     return true;
 }
Exemple #30
0
 /**
  * Print the HTML array for infocoms linked
  *
  *@return Nothing (display)
  *
  **/
 function showInfocoms()
 {
     global $DB, $CFG_GLPI;
     $instID = $this->fields['id'];
     if (!$this->can($instID, 'r')) {
         return false;
     }
     $query = "SELECT DISTINCT `itemtype`\n                FROM `glpi_infocoms`\n                WHERE `suppliers_id` = '{$instID}'\n                      AND `itemtype` NOT IN ('ConsumableItem', 'CartridgeItem', 'Software')\n                ORDER BY `itemtype`";
     $result = $DB->query($query);
     $number = $DB->numrows($result);
     echo "<div class='spaced'><table class='tab_cadre_fixe'>";
     echo "<tr><th colspan='2'>";
     Html::printPagerForm();
     echo "</th><th colspan='3'>";
     if ($DB->numrows($result) == 0) {
         _e('No associated item');
     } else {
         echo _n('Associated item', 'Associated items', $DB->numrows($result));
     }
     echo "</th></tr>";
     echo "<tr><th>" . __('Type') . "</th>";
     echo "<th>" . __('Entity') . "</th>";
     echo "<th>" . __('Name') . "</th>";
     echo "<th>" . __('Serial number') . "</th>";
     echo "<th>" . __('Inventory number') . "</th>";
     echo "</tr>";
     $num = 0;
     for ($i = 0; $i < $number; $i++) {
         $itemtype = $DB->result($result, $i, "itemtype");
         if (!($item = getItemForItemtype($itemtype))) {
             continue;
         }
         if ($item->canView()) {
             $linktype = $itemtype;
             $linkfield = 'id';
             $itemtable = getTableForItemType($itemtype);
             $query = "SELECT `glpi_infocoms`.`entities_id`, `name`, `{$itemtable}`.*\n                      FROM `glpi_infocoms`\n                      INNER JOIN `{$itemtable}` ON (`{$itemtable}`.`id` = `glpi_infocoms`.`items_id`) ";
             // Set $linktype for entity restriction AND link to search engine
             if ($itemtype == 'Cartridge') {
                 $query .= "INNER JOIN `glpi_cartridgeitems`\n                            ON (`glpi_cartridgeitems`.`id`=`glpi_cartridges`.`cartridgeitems_id`) ";
                 $linktype = 'CartridgeItem';
                 $linkfield = 'cartridgeitems_id';
             }
             if ($itemtype == 'Consumable') {
                 $query .= "INNER JOIN `glpi_consumableitems`\n                            ON (`glpi_consumableitems`.`id`=`glpi_consumables`.`consumableitems_id`) ";
                 $linktype = 'ConsumableItem';
                 $linkfield = 'consumableitems_id';
             }
             $linktable = getTableForItemType($linktype);
             $query .= "WHERE `glpi_infocoms`.`itemtype` = '{$itemtype}'\n                             AND `glpi_infocoms`.`suppliers_id` = '{$instID}'" . getEntitiesRestrictRequest(" AND", $linktable) . "\n                       ORDER BY `glpi_infocoms`.`entities_id`,\n                                `{$linktable}`.`name`";
             $result_linked = $DB->query($query);
             $nb = $DB->numrows($result_linked);
             // Set $linktype for link to search engine pnly
             if ($itemtype == 'SoftwareLicense' && $nb > $_SESSION['glpilist_limit']) {
                 $linktype = 'Software';
                 $linkfield = 'softwares_id';
             }
             if ($nb > $_SESSION['glpilist_limit']) {
                 echo "<tr class='tab_bg_1'>";
                 $title = $item->getTypeName($nb);
                 if ($nb > 0) {
                     $title = sprintf(__('%1$s: %2$s'), $title, $nb);
                 }
                 echo "<td class='center'>" . $title . "</td>";
                 echo "<td class='center' colspan='2'>";
                 echo "<a href='" . Toolbox::getItemTypeSearchURL($linktype) . "?" . rawurlencode("contains[0]") . "=" . rawurlencode('$$$$' . $instID) . "&" . rawurlencode("field[0]") . "=53&sort=80&order=ASC&is_deleted=0&start=0" . "'>" . __('Device list') . "</a></td>";
                 echo "<td class='center'>-</td><td class='center'>-</td></tr>";
             } else {
                 if ($nb) {
                     for ($prem = true; $data = $DB->fetch_assoc($result_linked); $prem = false) {
                         $name = $data["name"];
                         if ($_SESSION["glpiis_ids_visible"] || empty($data["name"])) {
                             $name = sprintf(__('%1$s (%2$s)'), $name, $data["id"]);
                         }
                         $link = Toolbox::getItemTypeFormURL($linktype);
                         $name = "<a href=\"" . $link . "?id=" . $data[$linkfield] . "\">" . $name . "</a>";
                         echo "<tr class='tab_bg_1'>";
                         if ($prem) {
                             $title = $item->getTypeName($nb);
                             if ($nb > 0) {
                                 $title = sprintf(__('%1$s: %2$s'), $title, $nb);
                             }
                             echo "<td class='center top' rowspan='{$nb}'>" . $title . "</td>";
                         }
                         echo "<td class='center'>" . Dropdown::getDropdownName("glpi_entities", $data["entities_id"]) . "</td>";
                         echo "<td class='center";
                         echo (isset($data['is_deleted']) && $data['is_deleted'] ? " tab_bg_2_2'" : "'") . ">";
                         echo $name . "</td>";
                         echo "<td class='center'>" . (isset($data["serial"]) ? "" . $data["serial"] . "" : "-") . "</td>";
                         echo "<td class='center'>" . (isset($data["otherserial"]) ? "" . $data["otherserial"] . "" : "-") . "</td>";
                         echo "</tr>";
                     }
                 }
             }
             $num += $nb;
         }
     }
     echo "<tr class='tab_bg_2'>";
     echo "<td class='center'>" . ($num > 0 ? sprintf(__('%1$s = %2$s'), __('Total'), $num) : "&nbsp;") . "</td>";
     echo "<td colspan='4'>&nbsp;</td></tr> ";
     echo "</table></div>";
 }