Relation between Tickets and Items
Inheritance: extends CommonDBRelation
Example #1
0
 function showForm($ID, $options = array())
 {
     global $DB, $CFG_GLPI;
     $default_values = self::getDefaultValues();
     // Get default values from posted values on reload form
     // On get because of tabs
     // we use REQUEST because method differ with layout (lefttab : GET, vsplit: POST)
     if (!isset($options['template_preview'])) {
         if (isset($_REQUEST)) {
             $values = Html::cleanPostForTextArea($_REQUEST);
         }
     }
     // Restore saved value or override with page parameter
     $saved = $this->restoreInput();
     foreach ($default_values as $name => $value) {
         if (!isset($values[$name])) {
             if (isset($saved[$name])) {
                 $values[$name] = $saved[$name];
             } else {
                 $values[$name] = $value;
             }
         }
     }
     if (isset($values['content'])) {
         // Clean new lines to be fix encoding
         $order = array('\\r', '\\n', "\\");
         $replace = array("", "", "");
         $values['content'] = str_replace($order, $replace, $values['content']);
     }
     if (isset($values['name'])) {
         $values['name'] = str_replace("\\", "", $values['name']);
     }
     if (!$ID) {
         // Override defaut values from projecttask if needed
         if (isset($options['_projecttasks_id'])) {
             $pt = new ProjectTask();
             if ($pt->getFromDB($options['_projecttasks_id'])) {
                 $values['name'] = $pt->getField('name');
                 $values['content'] = $pt->getField('name');
             }
         }
     }
     // Check category / type validity
     if ($values['itilcategories_id']) {
         $cat = new ITILCategory();
         if ($cat->getFromDB($values['itilcategories_id'])) {
             switch ($values['type']) {
                 case self::INCIDENT_TYPE:
                     if (!$cat->getField('is_incident')) {
                         $values['itilcategories_id'] = 0;
                     }
                     break;
                 case self::DEMAND_TYPE:
                     if (!$cat->getField('is_request')) {
                         $values['itilcategories_id'] = 0;
                     }
                     break;
                 default:
                     break;
             }
         }
     }
     // Default check
     if ($ID > 0) {
         $this->check($ID, READ);
     } else {
         // Create item
         $this->check(-1, CREATE, $values);
     }
     if (!$ID) {
         $this->userentities = array();
         if ($values["_users_id_requester"]) {
             //Get all the user's entities
             $all_entities = Profile_User::getUserEntities($values["_users_id_requester"], true, true);
             //For each user's entity, check if the technician which creates the ticket have access to it
             foreach ($all_entities as $tmp => $ID_entity) {
                 if (Session::haveAccessToEntity($ID_entity)) {
                     $this->userentities[] = $ID_entity;
                 }
             }
         }
         $this->countentitiesforuser = count($this->userentities);
         if ($this->countentitiesforuser > 0 && !in_array($this->fields["entities_id"], $this->userentities)) {
             // If entity is not in the list of user's entities,
             // then use as default value the first value of the user's entites list
             $this->fields["entities_id"] = $this->userentities[0];
             // Pass to values
             $values['entities_id'] = $this->userentities[0];
         }
     }
     if ($values['type'] <= 0) {
         $values['type'] = Entity::getUsedConfig('tickettype', $values['entities_id'], '', Ticket::INCIDENT_TYPE);
     }
     if (!isset($options['template_preview'])) {
         $options['template_preview'] = 0;
     }
     // Load ticket template if available :
     if ($ID) {
         $tt = $this->getTicketTemplateToUse($options['template_preview'], $this->fields['type'], $this->fields['itilcategories_id'], $this->fields['entities_id']);
     } else {
         $tt = $this->getTicketTemplateToUse($options['template_preview'], $values['type'], $values['itilcategories_id'], $values['entities_id']);
     }
     // Predefined fields from template : reset them
     if (isset($values['_predefined_fields'])) {
         $values['_predefined_fields'] = Toolbox::decodeArrayFromInput($values['_predefined_fields']);
     } else {
         $values['_predefined_fields'] = array();
     }
     // Store predefined fields to be able not to take into account on change template
     // Only manage predefined values on ticket creation
     $predefined_fields = array();
     if (!$ID) {
         if (isset($tt->predefined) && count($tt->predefined)) {
             foreach ($tt->predefined as $predeffield => $predefvalue) {
                 if (isset($default_values[$predeffield])) {
                     // Is always default value : not set
                     // Set if already predefined field
                     // Set if ticket template change
                     if (count($values['_predefined_fields']) == 0 && $values[$predeffield] == $default_values[$predeffield] || isset($values['_predefined_fields'][$predeffield]) && $values[$predeffield] == $values['_predefined_fields'][$predeffield] || isset($values['_tickettemplates_id']) && $values['_tickettemplates_id'] != $tt->getID() || $predeffield == 'requesttypes_id' && empty($saved)) {
                         // Load template data
                         $values[$predeffield] = $predefvalue;
                         $this->fields[$predeffield] = $predefvalue;
                         $predefined_fields[$predeffield] = $predefvalue;
                     }
                 }
             }
             // All predefined override : add option to say predifined exists
             if (count($predefined_fields) == 0) {
                 $predefined_fields['_all_predefined_override'] = 1;
             }
         } else {
             // No template load : reset predefined values
             if (count($values['_predefined_fields'])) {
                 foreach ($values['_predefined_fields'] as $predeffield => $predefvalue) {
                     if ($values[$predeffield] == $predefvalue) {
                         $values[$predeffield] = $default_values[$predeffield];
                     }
                 }
             }
         }
     }
     // Put ticket template on $values for actors
     $values['_tickettemplate'] = $tt;
     $canupdate = Session::haveRight(self::$rightname, UPDATE);
     $canpriority = Session::haveRight(self::$rightname, self::CHANGEPRIORITY);
     $canstatus = $canupdate;
     if ($ID && in_array($this->fields['status'], $this->getClosedStatusArray())) {
         $canupdate = false;
         // No update for actors
         $values['_noupdate'] = true;
     }
     $showuserlink = 0;
     if (Session::haveRight('user', READ)) {
         $showuserlink = 1;
     }
     if ($options['template_preview']) {
         // Add all values to fields of tickets for template preview
         foreach ($values as $key => $val) {
             if (!isset($this->fields[$key])) {
                 $this->fields[$key] = $val;
             }
         }
     }
     // In percent
     $colsize1 = '13';
     $colsize2 = '29';
     $colsize3 = '13';
     $colsize4 = '45';
     $canupdate_descr = $canupdate || $this->fields['status'] == self::INCOMING && $this->isUser(CommonITILActor::REQUESTER, Session::getLoginUserID()) && $this->numberOfFollowups() == 0 && $this->numberOfTasks() == 0;
     if (!$options['template_preview']) {
         echo "<form method='post' name='form_ticket' enctype='multipart/form-data' action='" . $CFG_GLPI["root_doc"] . "/front/ticket.form.php'>";
         if (isset($options['_projecttasks_id'])) {
             echo "<input type='hidden' name='_projecttasks_id' value='" . $options['_projecttasks_id'] . "'>";
         }
     }
     echo "<div class='spaced' id='tabsbody'>";
     echo "<table class='tab_cadre_fixe' id='mainformtable'>";
     // Optional line
     $ismultientities = Session::isMultiEntitiesMode();
     echo "<tr class='headerRow responsive_hidden'>";
     echo "<th colspan='4'>";
     if ($ID) {
         $text = sprintf(__('%1$s - %2$s'), $this->getTypeName(1), sprintf(__('%1$s: %2$s'), __('ID'), $ID));
         if ($ismultientities) {
             $text = sprintf(__('%1$s (%2$s)'), $text, Dropdown::getDropdownName('glpi_entities', $this->fields['entities_id']));
         }
         echo $text;
     } else {
         if ($ismultientities) {
             printf(__('The ticket will be added in the entity %s'), Dropdown::getDropdownName("glpi_entities", $this->fields['entities_id']));
         } else {
             _e('New ticket');
         }
     }
     echo "</th></tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<th width='{$colsize1}%'>";
     echo $tt->getBeginHiddenFieldText('date');
     if (!$ID) {
         printf(__('%1$s%2$s'), __('Opening date'), $tt->getMandatoryMark('date'));
     } else {
         _e('Opening date');
     }
     echo $tt->getEndHiddenFieldText('date');
     echo "</th>";
     echo "<td width='{$colsize2}%'>";
     echo $tt->getBeginHiddenFieldValue('date');
     $date = $this->fields["date"];
     if ($canupdate) {
         Html::showDateTimeField("date", array('value' => $date, 'timestep' => 1, 'maybeempty' => false));
     } else {
         echo Html::convDateTime($date);
     }
     echo $tt->getEndHiddenFieldValue('date', $this);
     echo "</td><td colspan='2'></td></tr>";
     // SLTs
     echo "<tr class='tab_bg_1'>";
     echo "<th width='{$colsize1}%'>" . $tt->getBeginHiddenFieldText('time_to_own');
     if (!$ID) {
         printf(__('%1$s%2$s'), __('Time to own'), $tt->getMandatoryMark('time_to_own'));
     } else {
         _e('Time to own');
     }
     echo $tt->getEndHiddenFieldText('time_to_own');
     echo "</th>";
     echo "<td width='{$colsize2}%' class='nopadding'>";
     $slt = new SLT();
     $slt->showSltForTicket($this, SLT::TTO, $tt, $canupdate);
     echo "</td>";
     echo "<th width='{$colsize3}%'>" . $tt->getBeginHiddenFieldText('due_date');
     if (!$ID) {
         printf(__('%1$s%2$s'), __('Time to resolve'), $tt->getMandatoryMark('due_date'));
     } else {
         _e('Time to resolve');
     }
     echo $tt->getEndHiddenFieldText('due_date');
     echo "</th>";
     echo "<td width='{$colsize4}%' class='nopadding'>";
     $slt->showSltForTicket($this, SLT::TTR, $tt, $canupdate);
     echo "</td>";
     echo "</tr>";
     if ($ID) {
         echo "<tr class='tab_bg_1'>";
         echo "<th width='{$colsize1}%'>" . __('By') . "</th>";
         echo "<td width='{$colsize2}%'>";
         if ($canupdate) {
             User::dropdown(array('name' => 'users_id_recipient', 'value' => $this->fields["users_id_recipient"], 'entity' => $this->fields["entities_id"], 'right' => 'all'));
         } else {
             echo getUserName($this->fields["users_id_recipient"], $showuserlink);
         }
         echo "</td>";
         echo "<th width='{$colsize3}%'>" . __('Last update') . "</th>";
         echo "<td width='{$colsize4}%'>";
         if ($this->fields['users_id_lastupdater'] > 0) {
             //TRANS: %1$s is the update date, %2$s is the last updater name
             printf(__('%1$s by %2$s'), Html::convDateTime($this->fields["date_mod"]), getUserName($this->fields["users_id_lastupdater"], $showuserlink));
         }
         echo "</td>";
         echo "</tr>";
     }
     if ($ID && (in_array($this->fields["status"], $this->getSolvedStatusArray()) || in_array($this->fields["status"], $this->getClosedStatusArray()))) {
         echo "<tr class='tab_bg_1'>";
         echo "<th width='{$colsize1}%'>" . __('Resolution date') . "</th>";
         echo "<td width='{$colsize2}%'>";
         Html::showDateTimeField("solvedate", array('value' => $this->fields["solvedate"], 'timestep' => 1, 'maybeempty' => false, 'canedit' => $canupdate));
         echo "</td>";
         if (in_array($this->fields["status"], $this->getClosedStatusArray())) {
             echo "<th width='{$colsize3}%'>" . __('Close date') . "</th>";
             echo "<td width='{$colsize4}%'>";
             Html::showDateTimeField("closedate", array('value' => $this->fields["closedate"], 'timestep' => 1, 'maybeempty' => false, 'canedit' => $canupdate));
             echo "</td>";
         } else {
             echo "<td colspan='2'>&nbsp;</td>";
         }
         echo "</tr>";
     }
     if ($ID) {
         echo "</table>";
         echo "<table  class='tab_cadre_fixe' id='mainformtable2'>";
     }
     echo "<tr class='tab_bg_1'>";
     echo "<th width='{$colsize1}%'>" . sprintf(__('%1$s%2$s'), __('Type'), $tt->getMandatoryMark('type')) . "</th>";
     echo "<td width='{$colsize2}%'>";
     // Permit to set type when creating ticket without update right
     if ($canupdate || !$ID) {
         $opt = array('value' => $this->fields["type"]);
         /// Auto submit to load template
         if (!$ID) {
             $opt['on_change'] = 'this.form.submit()';
         }
         $rand = self::dropdownType('type', $opt);
         if ($ID) {
             $params = array('type' => '__VALUE__', 'entity_restrict' => $this->fields['entities_id'], 'value' => $this->fields['itilcategories_id'], 'currenttype' => $this->fields['type']);
             Ajax::updateItemOnSelectEvent("dropdown_type{$rand}", "show_category_by_type", $CFG_GLPI["root_doc"] . "/ajax/dropdownTicketCategories.php", $params);
         }
     } else {
         echo self::getTicketTypeName($this->fields["type"]);
     }
     echo "</td>";
     echo "<th width='{$colsize3}%'>" . sprintf(__('%1$s%2$s'), __('Category'), $tt->getMandatoryMark('itilcategories_id')) . "</th>";
     echo "<td width='{$colsize4}%'>";
     // Permit to set category when creating ticket without update right
     if ($canupdate || !$ID || $canupdate_descr) {
         $opt = array('value' => $this->fields["itilcategories_id"], 'entity' => $this->fields["entities_id"]);
         if ($_SESSION["glpiactiveprofile"]["interface"] == "helpdesk") {
             $opt['condition'] = "`is_helpdeskvisible`='1' AND ";
         } else {
             $opt['condition'] = '';
         }
         /// Auto submit to load template
         if (!$ID) {
             $opt['on_change'] = 'this.form.submit()';
         }
         /// if category mandatory, no empty choice
         /// no empty choice is default value set on ticket creation, else yes
         if (($ID || $values['itilcategories_id']) && $tt->isMandatoryField("itilcategories_id") && $this->fields["itilcategories_id"] > 0) {
             $opt['display_emptychoice'] = false;
         }
         switch ($this->fields["type"]) {
             case self::INCIDENT_TYPE:
                 $opt['condition'] .= "`is_incident`='1'";
                 break;
             case self::DEMAND_TYPE:
                 $opt['condition'] .= "`is_request`='1'";
                 break;
             default:
                 break;
         }
         echo "<span id='show_category_by_type'>";
         ITILCategory::dropdown($opt);
         echo "</span>";
     } else {
         echo Dropdown::getDropdownName("glpi_itilcategories", $this->fields["itilcategories_id"]);
     }
     echo "</td>";
     echo "</tr>";
     if (!$ID) {
         echo "</table>";
         $this->showActorsPartForm($ID, $values);
         echo "<table class='tab_cadre_fixe' id='mainformtable3'>";
     }
     echo "<tr class='tab_bg_1'>";
     echo "<th width='{$colsize1}%'>" . $tt->getBeginHiddenFieldText('status');
     printf(__('%1$s%2$s'), __('Status'), $tt->getMandatoryMark('status'));
     echo $tt->getEndHiddenFieldText('status') . "</th>";
     echo "<td width='{$colsize2}%'>";
     echo $tt->getBeginHiddenFieldValue('status');
     if ($canstatus) {
         self::dropdownStatus(array('value' => $this->fields["status"], 'showtype' => 'allowed'));
         TicketValidation::alertValidation($this, 'status');
     } else {
         echo self::getStatus($this->fields["status"]);
         if (in_array($this->fields["status"], $this->getClosedStatusArray()) && $this->isAllowedStatus($this->fields['status'], Ticket::INCOMING)) {
             echo "&nbsp;<a class='vsubmit' href='" . $this->getLinkURL() . "&amp;forcetab=TicketFollowup\$1&amp;_openfollowup=1'>" . __('Reopen') . "</a>";
         }
     }
     echo $tt->getEndHiddenFieldValue('status', $this);
     echo "</td>";
     echo "<th width='{$colsize3}%'>" . $tt->getBeginHiddenFieldText('requesttypes_id');
     printf(__('%1$s%2$s'), __('Request source'), $tt->getMandatoryMark('requesttypes_id'));
     echo $tt->getEndHiddenFieldText('requesttypes_id') . "</th>";
     echo "<td width='{$colsize4}%'>";
     echo $tt->getBeginHiddenFieldValue('requesttypes_id');
     if ($canupdate) {
         RequestType::dropdown(array('value' => $this->fields["requesttypes_id"], 'condition' => 'is_active = 1 AND is_ticketheader = 1'));
     } else {
         echo Dropdown::getDropdownName('glpi_requesttypes', $this->fields["requesttypes_id"]);
         echo Html::hidden('requesttypes_id', array('value' => $this->fields["requesttypes_id"]));
     }
     echo $tt->getEndHiddenFieldValue('requesttypes_id', $this);
     echo "</td>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<th>" . $tt->getBeginHiddenFieldText('urgency');
     printf(__('%1$s%2$s'), __('Urgency'), $tt->getMandatoryMark('urgency'));
     echo $tt->getEndHiddenFieldText('urgency') . "</th>";
     echo "<td>";
     if ($canupdate && $canpriority || !$ID || $canupdate_descr) {
         // Only change during creation OR when allowed to change priority OR when user is the creator
         echo $tt->getBeginHiddenFieldValue('urgency');
         $idurgency = self::dropdownUrgency(array('value' => $this->fields["urgency"]));
         echo $tt->getEndHiddenFieldValue('urgency', $this);
     } else {
         $idurgency = "value_urgency" . mt_rand();
         echo "<input id='{$idurgency}' type='hidden' name='urgency' value='" . $this->fields["urgency"] . "'>";
         echo $tt->getBeginHiddenFieldValue('urgency');
         echo parent::getUrgencyName($this->fields["urgency"]);
         echo $tt->getEndHiddenFieldValue('urgency', $this);
     }
     echo "</td>";
     // Display validation state
     echo "<th>";
     if (!$ID) {
         echo $tt->getBeginHiddenFieldText('_add_validation');
         printf(__('%1$s%2$s'), __('Approval request'), $tt->getMandatoryMark('_add_validation'));
         echo $tt->getEndHiddenFieldText('_add_validation');
     } else {
         echo $tt->getBeginHiddenFieldText('global_validation');
         _e('Approval');
         echo $tt->getEndHiddenFieldText('global_validation');
     }
     echo "</th>";
     echo "<td>";
     if (!$ID) {
         echo $tt->getBeginHiddenFieldValue('_add_validation');
         $validation_right = '';
         if ($values['type'] == self::INCIDENT_TYPE && Session::haveRight('ticketvalidation', TicketValidation::CREATEINCIDENT)) {
             $validation_right = 'validate_incident';
         }
         if ($values['type'] == self::DEMAND_TYPE && Session::haveRight('ticketvalidation', TicketValidation::CREATEREQUEST)) {
             $validation_right = 'validate_request';
         }
         if (!empty($validation_right)) {
             echo "<input type='hidden' name='_add_validation' value='" . $values['_add_validation'] . "'>";
             $params = array('name' => "users_id_validate", 'entity' => $this->fields['entities_id'], 'right' => $validation_right, 'users_id_validate' => $values['users_id_validate']);
             TicketValidation::dropdownValidator($params);
         }
         echo $tt->getEndHiddenFieldValue('_add_validation', $this);
         if ($tt->isPredefinedField('global_validation')) {
             echo "<input type='hidden' name='global_validation' value='" . $tt->predefined['global_validation'] . "'>";
         }
     } else {
         echo $tt->getBeginHiddenFieldValue('global_validation');
         if (Session::haveRightsOr('ticketvalidation', TicketValidation::getCreateRights()) && $canupdate) {
             TicketValidation::dropdownStatus('global_validation', array('global' => true, 'value' => $this->fields['global_validation']));
         } else {
             echo TicketValidation::getStatus($this->fields['global_validation']);
         }
         echo $tt->getEndHiddenFieldValue('global_validation', $this);
     }
     echo "</td></tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<th>" . $tt->getBeginHiddenFieldText('impact');
     printf(__('%1$s%2$s'), __('Impact'), $tt->getMandatoryMark('impact'));
     echo $tt->getEndHiddenFieldText('impact') . "</th>";
     echo "<td>";
     echo $tt->getBeginHiddenFieldValue('impact');
     if ($canupdate) {
         $idimpact = self::dropdownImpact(array('value' => $this->fields["impact"]));
     } else {
         $idimpact = "value_impact" . mt_rand();
         echo "<input id='{$idimpact}' type='hidden' name='impact' value='" . $this->fields["impact"] . "'>";
         echo parent::getImpactName($this->fields["impact"]);
     }
     echo $tt->getEndHiddenFieldValue('impact', $this);
     echo "</td>";
     echo "<th>" . $tt->getBeginHiddenFieldText('locations_id');
     printf(__('%1$s%2$s'), __('Location'), $tt->getMandatoryMark('locations_id'));
     echo $tt->getEndHiddenFieldText('locations_id') . "</th>";
     echo "<td>";
     echo $tt->getBeginHiddenFieldValue('locations_id');
     if ($canupdate || !$ID) {
         Location::dropdown(array('value' => $this->fields['locations_id'], 'entity' => $this->fields['entities_id']));
     } else {
         echo Dropdown::getDropdownName('glpi_locations', $this->fields["locations_id"]);
     }
     echo $tt->getEndHiddenFieldValue('locations_id', $this);
     echo "</td>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<th>" . $tt->getBeginHiddenFieldText('priority');
     printf(__('%1$s%2$s'), __('Priority'), $tt->getMandatoryMark('priority'));
     echo $tt->getEndHiddenFieldText('priority') . "</th>";
     echo "<td>";
     $idajax = 'change_priority_' . mt_rand();
     if ($canpriority && !$tt->isHiddenField('priority')) {
         $idpriority = parent::dropdownPriority(array('value' => $this->fields["priority"], 'withmajor' => true));
         $idpriority = 'dropdown_priority' . $idpriority;
         echo "&nbsp;<span id='{$idajax}' style='display:none'></span>";
     } else {
         $idpriority = 0;
         echo $tt->getBeginHiddenFieldValue('priority');
         echo "<span id='{$idajax}'>" . parent::getPriorityName($this->fields["priority"]) . "</span>";
         echo $tt->getEndHiddenFieldValue('priority', $this);
     }
     if ($canupdate || $canupdate_descr) {
         $params = array('urgency' => '__VALUE0__', 'impact' => '__VALUE1__', 'priority' => $idpriority);
         Ajax::updateItemOnSelectEvent(array('dropdown_urgency' . $idurgency, 'dropdown_impact' . $idimpact), $idajax, $CFG_GLPI["root_doc"] . "/ajax/priority.php", $params);
     }
     echo "</td>";
     echo "<th rowspan='2'>" . $tt->getBeginHiddenFieldText('items_id');
     printf(__('%1$s%2$s'), _n('Associated element', 'Associated elements', Session::getPluralNumber()), $tt->getMandatoryMark('items_id'));
     if ($ID && $canupdate) {
         echo "&nbsp;<a  href='" . $this->getFormURL() . "?id=" . $ID . "&amp;forcetab=Item_Ticket\$1'><img title='" . __s('Update') . "' alt='" . __s('Update') . "'\n                      class='pointer' src='" . $CFG_GLPI["root_doc"] . "/pics/showselect.png'></a>";
     }
     echo $tt->getEndHiddenFieldText('items_id');
     echo "</th>";
     if (!$ID) {
         echo "<td rowspan='2'>";
         echo $tt->getBeginHiddenFieldValue('items_id');
         $values['_canupdate'] = Session::haveRight('ticket', CREATE);
         if ($values['_canupdate']) {
             Item_Ticket::itemAddForm($this, $values);
         }
         echo $tt->getEndHiddenFieldValue('items_id', $this);
         echo "</td>";
     } else {
         echo "<td>";
         echo $tt->getBeginHiddenFieldValue('items_id');
         $values['_canupdate'] = $canupdate || $canupdate_descr;
         Item_Ticket::itemAddForm($this, $values);
         echo $tt->getEndHiddenFieldValue('items_id', $this);
         echo "</td>";
     }
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     // Need comment right to add a followup with the actiontime
     if (!$ID && Session::haveRight('followup', TicketFollowup::ADDALLTICKET)) {
         echo "<th>" . $tt->getBeginHiddenFieldText('actiontime');
         printf(__('%1$s%2$s'), __('Total duration'), $tt->getMandatoryMark('actiontime'));
         echo $tt->getEndHiddenFieldText('actiontime') . "</th>";
         echo "<td>";
         echo $tt->getBeginHiddenFieldValue('actiontime');
         Dropdown::showTimeStamp('actiontime', array('value' => $values['actiontime'], 'addfirstminutes' => true));
         echo $tt->getEndHiddenFieldValue('actiontime', $this);
         echo "</td>";
     }
     echo "</tr>";
     echo "</table>";
     if ($ID) {
         $this->showActorsPartForm($ID, $values);
     }
     $view_linked_tickets = $ID || $canupdate;
     echo "<table class='tab_cadre_fixe' id='mainformtable4'>";
     echo "<tr class='tab_bg_1'>";
     echo "<th style='width:{$colsize1}%'>" . $tt->getBeginHiddenFieldText('name');
     printf(__('%1$s%2$s'), __('Title'), $tt->getMandatoryMark('name'));
     echo $tt->getEndHiddenFieldText('name') . "</th>";
     echo "<td colspan='3'>";
     if (!$ID || $canupdate_descr) {
         echo $tt->getBeginHiddenFieldValue('name');
         echo "<input type='text' style='width:98%' maxlength=250 name='name' " . " value=\"" . Html::cleanInputText($this->fields["name"]) . "\">";
         echo $tt->getEndHiddenFieldValue('name', $this);
     } else {
         if (empty($this->fields["name"])) {
             _e('Without title');
         } else {
             echo $this->fields["name"];
         }
     }
     echo "</td>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<th style='width:{$colsize1}%'>" . $tt->getBeginHiddenFieldText('content');
     printf(__('%1$s%2$s'), __('Description'), $tt->getMandatoryMark('content'));
     if (!$ID || $canupdate_descr) {
         $content = Toolbox::unclean_cross_side_scripting_deep(Html::entity_decode_deep($this->fields['content']));
         Html::showTooltip(nl2br(Html::Clean($content)));
     }
     echo $tt->getEndHiddenFieldText('content') . "</th>";
     echo "<td colspan='3'>";
     if (!$ID || $canupdate_descr) {
         // Admin =oui on autorise la modification de la description
         echo $tt->getBeginHiddenFieldValue('content');
         $rand = mt_rand();
         $rand_text = mt_rand();
         $rows = 6;
         $content_id = "content{$rand}";
         if ($CFG_GLPI["use_rich_text"]) {
             $this->fields["content"] = $this->setRichTextContent($content_id, $this->fields["content"], $rand);
             $rows = 10;
         } else {
             $this->fields["content"] = $this->setSimpleTextContent($this->fields["content"]);
         }
         echo "<div id='content{$rand_text}'>";
         echo "<textarea id='{$content_id}' name='content' style='width:100%' rows='{$rows}'>" . $this->fields["content"] . "</textarea></div>";
         echo Html::scriptBlock("\$(document).ready(function() { \$('#{$content_id}').autogrow(); });");
         echo $tt->getEndHiddenFieldValue('content', $this);
     } else {
         $content = Toolbox::unclean_cross_side_scripting_deep(Html::entity_decode_deep($this->fields['content']));
         echo nl2br(Html::Clean($content));
     }
     echo "</td>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     if ($view_linked_tickets) {
         echo "<th style='width:{$colsize1}%'>" . _n('Linked ticket', 'Linked tickets', Session::getPluralNumber());
         $rand_linked_ticket = mt_rand();
         if ($canupdate) {
             echo "&nbsp;";
             echo "<img onClick=\"" . Html::jsShow("linkedticket{$rand_linked_ticket}") . "\"\n                   title=\"" . __s('Add') . "\" alt=\"" . __s('Add') . "\"\n                   class='pointer' src='" . $CFG_GLPI["root_doc"] . "/pics/add_dropdown.png'>";
         }
         echo '</th>';
         echo "<td colspan='3'>";
         if ($canupdate) {
             echo "<div style='display:none' id='linkedticket{$rand_linked_ticket}'>";
             echo "<table class='tab_format' width='100%'><tr><td width='30%'>";
             Ticket_Ticket::dropdownLinks('_link[link]', isset($values["_link"]) ? $values["_link"]['link'] : '');
             echo "<input type='hidden' name='_link[tickets_id_1]' value='{$ID}'>\n";
             echo "</td><td width='70%'>";
             $linkparam = array('name' => '_link[tickets_id_2]', 'displaywith' => array('id'));
             if (isset($values["_link"])) {
                 $linkparam['value'] = $values["_link"]['tickets_id_2'];
             }
             Ticket::dropdown($linkparam);
             echo "</td></tr></table>";
             echo "</div>";
             if (isset($values["_link"]) && !empty($values["_link"]['tickets_id_2'])) {
                 echo "<script language='javascript'>";
                 echo Html::jsShow("linkedticket{$rand_linked_ticket}");
                 echo "</script>";
             }
         }
         Ticket_Ticket::displayLinkedTicketsTo($ID);
         echo "</td>";
     }
     echo "</tr>";
     // View files added
     echo "<tr class='tab_bg_1'>";
     // Permit to add doc when creating a ticket
     echo "<th style='width:{$colsize1}%'>";
     echo $tt->getBeginHiddenFieldText('_documents_id');
     $doctitle = sprintf(__('File (%s)'), Document::getMaxUploadSize());
     printf(__('%1$s%2$s'), $doctitle, $tt->getMandatoryMark('_documents_id'));
     // Do not show if hidden.
     if (!$tt->isHiddenField('_documents_id')) {
         DocumentType::showAvailableTypesLink();
     }
     echo $tt->getEndHiddenFieldText('_documents_id');
     echo "</th>";
     echo "<td colspan='3'>";
     // Do not set values
     echo $tt->getEndHiddenFieldValue('_documents_id');
     if ($tt->isPredefinedField('_documents_id')) {
         if (isset($values['_documents_id']) && is_array($values['_documents_id']) && count($values['_documents_id'])) {
             echo "<span class='b'>" . __('Default documents:') . '</span>';
             echo "<br>";
             $doc = new Document();
             foreach ($values['_documents_id'] as $key => $val) {
                 if ($doc->getFromDB($val)) {
                     echo "<input type='hidden' name='_documents_id[{$key}]' value='{$val}'>";
                     echo "- " . $doc->getNameID() . "<br>";
                 }
             }
         }
     }
     echo "<div id='fileupload_info'></div>";
     echo "</td>";
     echo "</tr>";
     if ((!$ID || $canupdate || $canupdate_descr || Session::haveRightsOr(self::$rightname, array(self::ASSIGN, self::STEAL, DELETE, PURGE))) && !$options['template_preview']) {
         echo "<tr class='tab_bg_1'>";
         if ($ID) {
             if (Session::haveRightsOr(self::$rightname, array(UPDATE, DELETE, PURGE)) || $this->canDeleteItem() || $this->canUpdateItem()) {
                 echo "<td class='tab_bg_2 center' colspan='4'>";
                 if ($this->fields["is_deleted"] == 1) {
                     if (self::canPurge()) {
                         echo "<input type='submit' class='submit' name='restore' value='" . _sx('button', 'Restore') . "'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                     }
                 } else {
                     if (self::canUpdate()) {
                         echo "<input type='submit' class='submit' name='update' value='" . _sx('button', 'Save') . "'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                     }
                 }
                 if ($this->fields["is_deleted"] == 1) {
                     if (self::canPurge()) {
                         echo "<input type='submit' class='submit' name='purge' value='" . _sx('button', 'Delete permanently') . "' " . Html::addConfirmationOnAction(__('Confirm the final deletion?')) . ">";
                     }
                 } else {
                     if ($this->canDeleteItem()) {
                         echo "<input type='submit' class='submit' name='delete' value='" . _sx('button', 'Put in dustbin') . "'>";
                     }
                 }
                 echo "<input type='hidden' name='_read_date_mod' value='" . $this->getField('date_mod') . "'>";
                 echo "</td>";
             }
         } else {
             echo "<td class='tab_bg_2 center' colspan='4'>";
             echo "<input type='submit' name='add' value=\"" . _sx('button', 'Add') . "\" class='submit'>";
             if ($tt->isField('id') && $tt->fields['id'] > 0) {
                 echo "<input type='hidden' name='_tickettemplates_id' value='" . $tt->fields['id'] . "'>";
                 echo "<input type='hidden' name='_predefined_fields'\n                      value=\"" . Toolbox::prepareArrayForInput($predefined_fields) . "\">";
             }
         }
     }
     // File upload system
     $colspan = 3;
     if (!$CFG_GLPI['use_rich_text']) {
         $colspan = 4;
     }
     echo "<tr class='tab_bg_1'>";
     echo "<td colspan='{$colspan}'>";
     echo $tt->getBeginHiddenFieldValue('_documents_id');
     echo Html::file(array('multiple' => true, 'showfilecontainer' => 'fileupload_info', 'values' => array('filename' => $values['_filename'], 'tag' => $values['_tag_filename'])));
     echo "</td>";
     if ($CFG_GLPI['use_rich_text']) {
         echo "</tr>";
         echo "<tr class='tab_bg_1'>";
         echo "<td colspan='{$colspan}'>";
         if (!isset($rand)) {
             $rand = mt_rand();
         }
         if ($canupdate_descr) {
             echo Html::initImagePasteSystem($content_id, $rand);
         }
         echo "</td>";
     }
     echo "</tr>";
     echo "</table>";
     echo "<input type='hidden' name='id' value='{$ID}'>";
     echo "</div>";
     if (!$options['template_preview']) {
         Html::closeForm();
     }
     return true;
 }
 /**
  * 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>";
     }
 }
Example #3
0
 /**
  * @param $type
  * @param $model_id
  * @param $tab_ids
  * @param $location
  **/
 static function replace($type, $model_id, $tab_ids, $location)
 {
     global $DB, $CFG_GLPI, $PLUGIN_HOOKS;
     $model = new PluginUninstallModel();
     $model->getConfig($model_id);
     $overwrite = $model->fields["overwrite"];
     echo "<div class='center'>";
     echo "<table class='tab_cadre_fixe'><tr><th>" . __('Replacement', 'uninstall') . "</th></tr>";
     echo "<tr class='tab_bg_2'><td>";
     $count = 0;
     $tot = count($tab_ids);
     Html::createProgressBar(__('Please wait, replacement is running...', 'uninstall'));
     foreach ($tab_ids as $olditem_id => $newitem_id) {
         $count++;
         $olditem = new $type();
         $olditem->getFromDB($olditem_id);
         $newitem = new $type();
         $newitem->getFromDB($newitem_id);
         //Hook to perform actions before item is being replaced
         $olditem->fields['_newid'] = $newitem_id;
         $olditem->fields['_uninstall_event'] = $model_id;
         $olditem->fields['_action'] = 'replace';
         Plugin::doHook("plugin_uninstall_replace_before", $olditem);
         // Retrieve informations
         //States
         if ($model->fields['states_id'] != 0) {
             $olditem->update(array('id' => $olditem_id, 'states_id' => $model->fields['states_id']), false);
         }
         // METHOD REPLACEMENT 1 : Archive
         if ($model->fields['replace_method'] == self::METHOD_PURGE) {
             $name_out = str_shuffle(Toolbox::getRandomString(5) . time());
             $plugin = new Plugin();
             if ($plugin->isActivated('PDF')) {
                 // USE PDF EXPORT
                 $plugin->load('pdf', true);
                 include_once GLPI_ROOT . "/lib/ezpdf/class.ezpdf.php";
                 //Get all item's tabs
                 $tab = array_keys($olditem->defineTabs());
                 //Tell PDF to also export item's main tab, and in first position
                 array_unshift($tab, "_main_");
                 $itempdf = new $PLUGIN_HOOKS['plugin_pdf'][$type]($olditem);
                 $out = $itempdf->generatePDF(array($olditem_id), $tab, 1, false);
                 $name_out .= ".pdf";
             } else {
                 //TODO Which datas ? Add Defaults...
                 $out = __('Replacement', 'uninstall') . "\r\n";
                 $datas = $olditem->fields;
                 unset($datas['comment']);
                 foreach ($datas as $k => $v) {
                     $out .= $k . ";";
                 }
                 $out .= "\r\n";
                 foreach ($datas as $k => $v) {
                     $out .= $v . ";";
                 }
                 // USE CSV EXPORT
                 $name_out .= ".csv";
             }
             // Write document
             $out_file = GLPI_DOC_DIR . "/_uploads/" . $name_out;
             $open_file = fopen($out_file, 'a');
             fwrite($open_file, $out);
             fclose($open_file);
             // Compute comment text
             $comment = __('This document is the archive of this replaced item', 'uninstall') . " " . self::getCommentsForReplacement($olditem, false, false);
             // Create & Attach new document to current item
             $doc = new Document();
             $input = array('name' => addslashes(__('Archive of old material', 'uninstall')), 'upload_file' => $name_out, 'comment' => addslashes($comment), 'add' => __('Add'), 'entities_id' => $newitem->getEntityID(), 'is_recursive' => $newitem->isRecursive(), 'link' => "", 'documentcategories_id' => 0, 'items_id' => $olditem_id, 'itemtype' => $type);
             //Attached the document to the old item, to generate an accurate name
             $document_added = $doc->add($input);
             //Attach the document to the new item, once the document's name is correct
             $docItem = new Document_Item();
             $docItemId = $docItem->add(array('documents_id' => $document_added, 'itemtype' => $type, 'items_id' => (int) $newitem_id));
         }
         // General Informations - NAME
         if ($model->fields["replace_name"]) {
             if ($overwrite || empty($newitem->fields['name'])) {
                 $newitem->update(array('id' => $newitem_id, 'name' => $olditem->getField('name')), false);
             }
         }
         $data['id'] = $newitem->getID();
         // General Informations - SERIAL
         if ($model->fields["replace_serial"]) {
             if ($overwrite || empty($newitem->fields['serial'])) {
                 $newitem->update(array('id' => $newitem_id, 'serial' => $olditem->getField('serial')), false);
             }
         }
         // General Informations - OTHERSERIAL
         if ($model->fields["replace_otherserial"]) {
             if ($overwrite || empty($newitem->fields['otherserial'])) {
                 $newitem->update(array('id' => $newitem_id, 'otherserial' => $olditem->getField('otherserial')), false);
             }
         }
         // Documents
         if ($model->fields["replace_documents"] && in_array($type, $CFG_GLPI["document_types"])) {
             $doc_item = new Document_Item();
             foreach (self::getAssociatedDocuments($olditem) as $document) {
                 $doc_item->update(array('id' => $document['assocID'], 'itemtype' => $type, 'items_id' => $newitem_id), false);
             }
         }
         // Contracts
         if ($model->fields["replace_contracts"] && in_array($type, $CFG_GLPI["contract_types"])) {
             $contract_item = new Contract_Item();
             foreach (self::getAssociatedContracts($olditem) as $contract) {
                 $contract_item->update(array('id' => $contract['id'], 'itemtype' => $type, 'items_id' => $newitem_id), false);
             }
         }
         // Infocoms
         if ($model->fields["replace_infocoms"] && in_array($type, $CFG_GLPI["infocom_types"])) {
             $infocom = new Infocom();
             if ($overwrite) {
                 // Delete current Infocoms of new item
                 if ($infocom->getFromDBforDevice($type, $newitem_id)) {
                     //Do not log infocom deletion in the new item's history
                     $infocom->dohistory = false;
                     $infocom->deleteFromDB(1);
                 }
             }
             // Update current Infocoms of old item
             if ($infocom->getFromDBforDevice($type, $olditem_id)) {
                 $infocom->update(array('id' => $infocom->getID(), 'itemtype' => $type, 'items_id' => $newitem_id), false);
             }
         }
         // Reservations
         if ($model->fields["replace_reservations"] && in_array($type, $CFG_GLPI["reservation_types"])) {
             $resaitem = new ReservationItem();
             if ($overwrite) {
                 // Delete current reservation of new item
                 $resa_new = new Reservation();
                 $resa_new->getFromDB($newitem_id);
                 if ($resa_new->is_reserved()) {
                     $resa_new = new ReservationItem();
                     $resa_new->getFromDBbyItem($type, $newitem_id);
                     if (count($resa_new->fields)) {
                         $resa_new->deleteFromDB(1);
                     }
                 }
             }
             // Update old reservation for attribute to new item
             $resa_old = new Reservation();
             $resa_old->getFromDB($olditem_id);
             if ($resa_old->is_reserved()) {
                 $resa_old = new ReservationItem();
                 $resa_old->getFromDBbyItem($type, $olditem_id);
                 if (count($resa_old->fields)) {
                     $resa_old->update(array('id' => $resa_old->getID(), 'itemtype' => $type, 'items_id' => $newitem_id), false);
                 }
             }
         }
         // User
         if ($model->fields["replace_users"] && in_array($type, $CFG_GLPI["linkuser_types"])) {
             $data = array();
             $data['id'] = $newitem->getID();
             if ($newitem->isField('users_id') && ($overwrite || empty($data['users_id']))) {
                 $data['users_id'] = $olditem->getField('users_id');
             }
             if ($newitem->isField('contact') && ($overwrite || empty($data['contact']))) {
                 $data['contact'] = $olditem->getField('contact');
             }
             if ($newitem->isField('contact_num') && ($overwrite || empty($data['contact_num']))) {
                 $data['contact_num'] = $olditem->getField('contact_num');
             }
             $newitem->update($data, false);
         }
         // Group
         if ($model->fields["replace_groups"] && in_array($type, $CFG_GLPI["linkgroup_types"])) {
             if ($newitem->isField('groups_id') && ($overwrite || empty($data['groups_id']))) {
                 $newitem->update(array('id' => $newitem_id, 'groups_id' => $olditem->getField('groups_id')), false);
             }
         }
         // Tickets
         if ($model->fields["replace_tickets"] && in_array($type, $CFG_GLPI["ticket_types"])) {
             $ticket_item = new Item_Ticket();
             foreach (self::getAssociatedTickets($type, $olditem_id) as $ticket) {
                 $ticket_item->update(array('id' => $ticket['id'], 'items_id' => $newitem_id), false);
             }
         }
         //Array netport_types renamed in networkport_types in GLPI 0.80
         if (isset($CFG_GLPI["netport_types"])) {
             $netport_types = $CFG_GLPI["netport_types"];
         } else {
             $netport_types = $CFG_GLPI["networkport_types"];
         }
         // NetPorts
         if ($model->fields["replace_netports"] && in_array($type, $netport_types)) {
             $netport_item = new NetworkPort();
             foreach (self::getAssociatedNetports($type, $olditem_id) as $netport) {
                 $netport_item->update(array('id' => $netport['id'], 'itemtype' => $type, 'items_id' => $newitem_id), false);
             }
         }
         // Directs connections
         if ($model->fields["replace_direct_connections"] && in_array($type, array('Computer'))) {
             $comp_item = new Computer_Item();
             foreach (self::getAssociatedItems($olditem) as $itemtype => $connections) {
                 foreach ($connections as $connection) {
                     $comp_item->update(array('id' => $connection['id'], 'computers_id' => $newitem_id, 'itemtype' => $itemtype), false);
                 }
             }
         }
         // Location
         if ($location != 0 && $olditem->isField('locations_id')) {
             $olditem->getFromDB($olditem_id);
             switch ($location) {
                 case -1:
                     break;
                 default:
                     $olditem->update(array('id' => $olditem_id, 'locations_id' => $location), false);
                     break;
             }
         }
         $plug = new Plugin();
         if ($plug->isActivated('ocsinventoryng')) {
             //Delete computer from OCS
             if ($model->fields["remove_from_ocs"] == 1) {
                 PluginUninstallUninstall::deleteComputerInOCSByGlpiID($olditem_id);
             }
             //Delete link in glpi_ocs_link
             if ($model->fields["delete_ocs_link"] || $model->fields["remove_from_ocs"]) {
                 PluginUninstallUninstall::deleteOcsLink($olditem_id);
             }
         }
         if ($plug->isActivated('fusioninventory')) {
             if ($model->fields['raz_fusioninventory']) {
                 PluginUninstallUninstall::deleteFusionInventoryLink(get_class($olditem), $olditem_id);
             }
         }
         // METHOD REPLACEMENT 1 : Purge
         if ($model->fields['replace_method'] == self::METHOD_PURGE) {
             // Retrieve, Compute && Update NEW comment field
             $comment = self::getCommentsForReplacement($olditem, true);
             $comment .= "\n- " . __('See attached document', 'uninstall');
             $newitem->update(array('id' => $newitem_id, 'comment' => addslashes($comment)), false);
             // If old item is attached in PDF/CSV
             // Delete AND Purge it in DB
             if ($document_added) {
                 $olditem->delete(array('id' => $olditem_id), true);
             }
         }
         // METHOD REPLACEMENT 2 : Delete AND Comment
         if ($model->fields['replace_method'] == self::METHOD_DELETE_AND_COMMENT) {
             //Add comment on the new item first
             $comment = self::getCommentsForReplacement($olditem, true);
             $newitem->update(array('id' => $newitem_id, 'comment' => Toolbox::addslashes_deep($comment)), false);
             // Retrieve, Compute && Update OLD comment field
             $comment = self::getCommentsForReplacement($newitem, false);
             $olditem->update(array('id' => $olditem_id, 'comment' => Toolbox::addslashes_deep($comment)), false);
             // Delete OLD item from DB (not PURGE)
             PluginUninstallUninstall::addUninstallLog($type, $olditem_id, 'replaced_by');
             $olditem->delete(array('id' => $olditem_id), 0, false);
         }
         //Plugin hook after replacement
         Plugin::doHook("plugin_uninstall_replace_after", $olditem);
         //Add history
         PluginUninstallUninstall::addUninstallLog($type, $newitem_id, 'replace');
         Html::changeProgressBarPosition($count, $tot + 1);
     }
     Html::changeProgressBarPosition($count, $tot, __('Replacement successful', 'uninstall'));
     echo "</td></tr>";
     echo "</table></div>";
 }
 /**
  * @see NotificationTargetCommonITILObject::getDatasForObject()
  **/
 function getDatasForObject(CommonDBTM $item, array $options, $simple = false)
 {
     global $CFG_GLPI;
     // Common ITIL datas
     $datas = parent::getDatasForObject($item, $options, $simple);
     $datas['##ticket.description##'] = Html::clean($datas['##ticket.description##']);
     $datas['##ticket.description##'] = $item->convertContentForNotification($datas['##ticket.description##'], $item);
     $datas['##ticket.content##'] = $datas['##ticket.description##'];
     // Specific datas
     $datas['##ticket.urlvalidation##'] = $this->formatURL($options['additionnaloption']['usertype'], "ticket_" . $item->getField("id") . "_TicketValidation\$1");
     $datas['##ticket.globalvalidation##'] = TicketValidation::getStatus($item->getField('global_validation'));
     $datas['##ticket.type##'] = Ticket::getTicketTypeName($item->getField('type'));
     $datas['##ticket.requesttype##'] = Dropdown::getDropdownName('glpi_requesttypes', $item->getField('requesttypes_id'));
     $autoclose_value = Entity::getUsedConfig('autoclose_delay', $this->getEntity(), '', Entity::CONFIG_NEVER);
     $datas['##ticket.autoclose##'] = __('Never');
     $datas['##lang.ticket.autoclosewarning##'] = "";
     if ($autoclose_value > 0) {
         $datas['##ticket.autoclose##'] = $autoclose_value;
         $datas['##lang.ticket.autoclosewarning##'] = sprintf(_n('Without a reply, the ticket will be automatically closed after %s day', 'Without a reply, the ticket will be automatically closed after %s days', $autoclose_value), $autoclose_value);
     }
     $datas['##ticket.sla##'] = '';
     if ($item->getField('slas_id')) {
         $datas['##ticket.sla##'] = Dropdown::getDropdownName('glpi_slas', $item->getField('slas_id'));
     }
     $datas['##ticket.location##'] = '';
     if ($item->getField('locations_id')) {
         $datas['##ticket.location##'] = Dropdown::getDropdownName('glpi_locations', $item->getField('locations_id'));
     }
     // is ticket deleted
     $datas['##ticket.isdeleted##'] = Dropdown::getYesNo($item->getField('is_deleted'));
     //Tags associated with the object linked to the ticket
     $datas['##ticket.itemtype##'] = '';
     $datas['##ticket.item.name##'] = '';
     $datas['##ticket.item.serial##'] = '';
     $datas['##ticket.item.otherserial##'] = '';
     $datas['##ticket.item.location##'] = '';
     $datas['##ticket.item.contact##'] = '';
     $datas['##ticket.item.contactnumber##'] = '';
     $datas['##ticket.item.user##'] = '';
     $datas['##ticket.item.group##'] = '';
     $datas['##ticket.item.model##'] = '';
     $item_ticket = new Item_Ticket();
     $items = $item_ticket->find("`tickets_id` = '" . $item->getField('id') . "'");
     $datas['items'] = array();
     if (count($items)) {
         foreach ($items as $val) {
             if (isset($val['itemtype']) && ($hardware = getItemForItemtype($val['itemtype'])) && isset($val["items_id"]) && $hardware->getFromDB($val["items_id"])) {
                 $tmp = array();
                 //Object type
                 $tmp['##ticket.itemtype##'] = $hardware->getTypeName();
                 //Object name
                 $tmp['##ticket.item.name##'] = $hardware->getField('name');
                 //Object serial
                 if ($hardware->isField('serial')) {
                     $tmp['##ticket.item.serial##'] = $hardware->getField('serial');
                 }
                 //Object contact
                 if ($hardware->isField('contact')) {
                     $tmp['##ticket.item.contact##'] = $hardware->getField('contact');
                 }
                 //Object contact num
                 if ($hardware->isField('contact_num')) {
                     $tmp['##ticket.item.contactnumber##'] = $hardware->getField('contact_num');
                 }
                 //Object otherserial
                 if ($hardware->isField('otherserial')) {
                     $tmp['##ticket.item.otherserial##'] = $hardware->getField('otherserial');
                 }
                 //Object location
                 if ($hardware->isField('locations_id')) {
                     $tmp['##ticket.item.location##'] = Dropdown::getDropdownName('glpi_locations', $hardware->getField('locations_id'));
                 }
                 //Object user
                 if ($hardware->getField('users_id')) {
                     $user_tmp = new User();
                     if ($user_tmp->getFromDB($hardware->getField('users_id'))) {
                         $tmp['##ticket.item.user##'] = $user_tmp->getName();
                     }
                 }
                 //Object group
                 if ($hardware->getField('groups_id')) {
                     $tmp['##ticket.item.group##'] = Dropdown::getDropdownName('glpi_groups', $hardware->getField('groups_id'));
                 }
                 $modeltable = getSingular($hardware->getTable()) . "models";
                 $modelfield = getForeignKeyFieldForTable($modeltable);
                 if ($hardware->isField($modelfield)) {
                     $tmp['##ticket.item.model##'] = Dropdown::getDropdownName($modeltable, $hardware->getField($modelfield));
                 }
                 $datas['items'][] = $tmp;
             }
         }
     }
     $datas['##ticket.numberofitems##'] = count($datas['items']);
     // Get followups, log, validation, satisfaction, linked tickets
     if (!$simple) {
         // Linked tickets
         $linked_tickets = Ticket_Ticket::getLinkedTicketsTo($item->getField('id'));
         $datas['linkedtickets'] = array();
         if (count($linked_tickets)) {
             $linkedticket = new Ticket();
             foreach ($linked_tickets as $data) {
                 if ($linkedticket->getFromDB($data['tickets_id'])) {
                     $tmp = array();
                     $tmp['##linkedticket.id##'] = $data['tickets_id'];
                     $tmp['##linkedticket.link##'] = Ticket_Ticket::getLinkName($data['link']);
                     $tmp['##linkedticket.url##'] = $this->formatURL($options['additionnaloption']['usertype'], "ticket_" . $data['tickets_id']);
                     $tmp['##linkedticket.title##'] = $linkedticket->getField('name');
                     $tmp['##linkedticket.content##'] = $linkedticket->getField('content');
                     $datas['linkedtickets'][] = $tmp;
                 }
             }
         }
         $datas['##ticket.numberoflinkedtickets##'] = count($datas['linkedtickets']);
         $restrict = "`tickets_id`='" . $item->getField('id') . "'";
         $problems = getAllDatasFromTable('glpi_problems_tickets', $restrict);
         $datas['problems'] = array();
         if (count($problems)) {
             $problem = new Problem();
             foreach ($problems as $data) {
                 if ($problem->getFromDB($data['problems_id'])) {
                     $tmp = array();
                     $tmp['##problem.id##'] = $data['problems_id'];
                     $tmp['##problem.date##'] = $problem->getField('date');
                     $tmp['##problem.title##'] = $problem->getField('name');
                     $tmp['##problem.url##'] = $this->formatURL($options['additionnaloption']['usertype'], "problem_" . $data['problems_id']);
                     $tmp['##problem.content##'] = $problem->getField('content');
                     $datas['problems'][] = $tmp;
                 }
             }
         }
         $datas['##ticket.numberofproblems##'] = count($datas['problems']);
         $restrict = "`tickets_id`='" . $item->getField('id') . "'";
         $changes = getAllDatasFromTable('glpi_changes_tickets', $restrict);
         $datas['changes'] = array();
         if (count($changes)) {
             $change = new Change();
             foreach ($changes as $data) {
                 if ($change->getFromDB($data['changes_id'])) {
                     $tmp = array();
                     $tmp['##change.id##'] = $data['changes_id'];
                     $tmp['##change.date##'] = $change->getField('date');
                     $tmp['##change.title##'] = $change->getField('name');
                     $tmp['##change.url##'] = $this->formatURL($options['additionnaloption']['usertype'], "change_" . $data['changes_id']);
                     $tmp['##change.content##'] = $change->getField('content');
                     $datas['changes'][] = $tmp;
                 }
             }
         }
         $datas['##ticket.numberofchanges##'] = count($datas['changes']);
         if (!isset($options['additionnaloption']['show_private']) || !$options['additionnaloption']['show_private']) {
             $restrict .= " AND `is_private` = '0'";
         }
         $restrict .= " ORDER BY `date` DESC, `id` ASC";
         //Followup infos
         $followups = getAllDatasFromTable('glpi_ticketfollowups', $restrict);
         $datas['followups'] = array();
         foreach ($followups as $followup) {
             $tmp = array();
             $tmp['##followup.isprivate##'] = Dropdown::getYesNo($followup['is_private']);
             $tmp['##followup.author##'] = Html::clean(getUserName($followup['users_id']));
             $tmp['##followup.requesttype##'] = Dropdown::getDropdownName('glpi_requesttypes', $followup['requesttypes_id']);
             $tmp['##followup.date##'] = Html::convDateTime($followup['date']);
             $tmp['##followup.description##'] = $followup['content'];
             $datas['followups'][] = $tmp;
         }
         $datas['##ticket.numberoffollowups##'] = count($datas['followups']);
         // Approbation of solution
         $restrict .= " LIMIT 1";
         $replysolved = getAllDatasFromTable('glpi_ticketfollowups', $restrict);
         $data = current($replysolved);
         $datas['##ticket.solution.approval.description##'] = $data['content'];
         $datas['##ticket.solution.approval.date##'] = Html::convDateTime($data['date']);
         $datas['##ticket.solution.approval.author##'] = Html::clean(getUserName($data['users_id']));
         //Validation infos
         $restrict = "`tickets_id`='" . $item->getField('id') . "'";
         if (isset($options['validation_id']) && $options['validation_id']) {
             $restrict .= " AND `glpi_ticketvalidations`.`id` = '" . $options['validation_id'] . "'";
         }
         $restrict .= " ORDER BY `submission_date` DESC, `id` ASC";
         $validations = getAllDatasFromTable('glpi_ticketvalidations', $restrict);
         $datas['validations'] = array();
         foreach ($validations as $validation) {
             $tmp = array();
             $tmp['##validation.submission.title##'] = sprintf(__('An approval request has been submitted by %s'), Html::clean(getUserName($validation['users_id'])));
             $tmp['##validation.answer.title##'] = sprintf(__('An answer to an an approval request was produced by %s'), Html::clean(getUserName($validation['users_id_validate'])));
             $tmp['##validation.author##'] = Html::clean(getUserName($validation['users_id']));
             $tmp['##validation.status##'] = TicketValidation::getStatus($validation['status']);
             $tmp['##validation.storestatus##'] = $validation['status'];
             $tmp['##validation.submissiondate##'] = Html::convDateTime($validation['submission_date']);
             $tmp['##validation.commentsubmission##'] = $validation['comment_submission'];
             $tmp['##validation.validationdate##'] = Html::convDateTime($validation['validation_date']);
             $tmp['##validation.validator##'] = Html::clean(getUserName($validation['users_id_validate']));
             $tmp['##validation.commentvalidation##'] = $validation['comment_validation'];
             $datas['validations'][] = $tmp;
         }
         // Ticket Satisfaction
         $inquest = new TicketSatisfaction();
         $datas['##satisfaction.type##'] = '';
         $datas['##satisfaction.datebegin##'] = '';
         $datas['##satisfaction.dateanswered##'] = '';
         $datas['##satisfaction.satisfaction##'] = '';
         $datas['##satisfaction.description##'] = '';
         if ($inquest->getFromDB($item->getField('id'))) {
             // internal inquest
             if ($inquest->fields['type'] == 1) {
                 $datas['##ticket.urlsatisfaction##'] = $this->formatURL($options['additionnaloption']['usertype'], "ticket_" . $item->getField("id") . '_Ticket$3');
                 // external inquest
             } else {
                 if ($inquest->fields['type'] == 2) {
                     $datas['##ticket.urlsatisfaction##'] = Entity::generateLinkSatisfaction($item);
                 }
             }
             $datas['##satisfaction.type##'] = $inquest->getTypeInquestName($inquest->getfield('type'));
             $datas['##satisfaction.datebegin##'] = Html::convDateTime($inquest->fields['date_begin']);
             $datas['##satisfaction.dateanswered##'] = Html::convDateTime($inquest->fields['date_answered']);
             $datas['##satisfaction.satisfaction##'] = $inquest->fields['satisfaction'];
             $datas['##satisfaction.description##'] = $inquest->fields['comment'];
         }
     }
     return $datas;
 }
Example #5
0
 /**
  * Print the HTML ajax associated item add
  *
  * @param $ticket Ticket object
  * @param $options   array of possible options:
  *    - id                  : ID of the ticket
  *    - _users_id_requester : ID of the requester user
  *    - items_id            : array of elements (itemtype => array(id1, id2, id3, ...))
  *
  * @return Nothing (display)
  **/
 static function itemAddForm(Ticket $ticket, $options = array())
 {
     global $CFG_GLPI;
     $params = array('id' => isset($ticket->fields['id']) && $ticket->fields['id'] != '' ? $ticket->fields['id'] : 0, '_users_id_requester' => 0, 'items_id' => array(), 'itemtype' => '');
     $opt = array();
     foreach ($options as $key => $val) {
         if (!empty($val)) {
             $params[$key] = $val;
         }
     }
     if (!$ticket->can($params['id'], READ)) {
         return false;
     }
     $canedit = $ticket->can($params['id'], UPDATE);
     // Ticket update case
     if ($params['id'] > 0) {
         // Get requester
         $class = new $ticket->userlinkclass();
         $tickets_user = $class->getActors($params['id']);
         if (isset($tickets_user[CommonITILActor::REQUESTER]) && count($tickets_user[CommonITILActor::REQUESTER]) == 1) {
             foreach ($tickets_user[CommonITILActor::REQUESTER] as $user_id_single) {
                 $params['_users_id_requester'] = $user_id_single['users_id'];
             }
         }
         // Get associated elements for ticket
         $used = self::getUsedItems($params['id']);
         foreach ($used as $itemtype => $items) {
             foreach ($items as $items_id) {
                 if (!isset($params['items_id'][$itemtype]) || !in_array($items_id, $params['items_id'][$itemtype])) {
                     $params['items_id'][$itemtype][] = $items_id;
                 }
             }
         }
     }
     // Get ticket template
     $tt = new TicketTemplate();
     if (isset($options['_tickettemplate'])) {
         $tt = $options['_tickettemplate'];
         if (isset($tt->fields['id'])) {
             $opt['templates_id'] = $tt->fields['id'];
         }
     } else {
         if (isset($options['templates_id'])) {
             $tt->getFromDBWithDatas($options['templates_id']);
             if (isset($tt->fields['id'])) {
                 $opt['templates_id'] = $tt->fields['id'];
             }
         }
     }
     $rand = mt_rand();
     $count = 0;
     echo "<div id='itemAddForm{$rand}'>";
     // Show associated item dropdowns
     if ($canedit) {
         echo "<div style='float:left'>";
         $p = array('used' => $params['items_id'], 'rand' => $rand, 'tickets_id' => $params['id']);
         // My items
         if ($params['_users_id_requester'] > 0) {
             Item_Ticket::dropdownMyDevices($params['_users_id_requester'], $ticket->fields["entities_id"], $params['itemtype'], 0, $p);
         }
         // Global search
         Item_Ticket::dropdownAllDevices("itemtype", $params['itemtype'], 0, 1, $params['_users_id_requester'], $ticket->fields["entities_id"], $p);
         echo "<span id='item_ticket_selection_information'></span>";
         echo "</div>";
         // Add button
         echo "<a href='javascript:itemAction{$rand}(\"add\");' class='vsubmit' style='float:left'>" . _sx('button', 'Add') . "</a>";
     }
     // Display list
     echo "<div style='clear:both;'>";
     if (!empty($params['items_id'])) {
         // No delete if mandatory and only one item
         $delete = true;
         $cpt = 0;
         foreach ($params['items_id'] as $itemtype => $items) {
             foreach ($items as $items_id) {
                 $cpt++;
             }
         }
         if ($cpt == 1 && isset($tt->mandatory['items_id'])) {
             $delete = false;
         }
         foreach ($params['items_id'] as $itemtype => $items) {
             foreach ($items as $items_id) {
                 if ($count < 5 && $params['id'] || $params['id'] == 0) {
                     echo Item_Ticket::showItemToAdd($params['id'], $itemtype, $items_id, array('rand' => $rand, 'delete' => $delete));
                 }
                 $count++;
             }
         }
     }
     if ($count == 0) {
         echo "<input type='hidden' value='0' name='items_id'>";
     }
     if ($params['id'] > 0 && $count > 5) {
         echo "<i><a href='" . $ticket->getFormURL() . "?id=" . $params['id'] . "&amp;forcetab=Item_Ticket\$1'>" . __('Display all items') . " (" . $count . ")</a></i>";
     }
     echo "</div>";
     foreach (array('id', '_users_id_requester', 'items_id', 'itemtype') as $key) {
         $opt[$key] = $params[$key];
     }
     $js = " function itemAction{$rand}(action, itemtype, items_id) {";
     $js .= "    \$.ajax({\n                     url: '" . $CFG_GLPI['root_doc'] . "/ajax/itemTicket.php',\n                     dataType: 'html',\n                     data: {'action'     : action,\n                            'rand'       : {$rand},\n                            'params'     : " . json_encode($opt) . ",\n                            'my_items'   : \$('#dropdown_my_items{$rand}').val(),\n                            'itemtype'   : (itemtype === undefined) ? \$('#dropdown_itemtype{$rand}').val() : itemtype,\n                            'items_id'   : (items_id === undefined) ? \$('#dropdown_add_items_id{$rand}').val() : items_id},\n                     success: function(response) {";
     $js .= "          \$(\"#itemAddForm{$rand}\").html(response);";
     $js .= "       }";
     $js .= "    });";
     $js .= " }";
     echo Html::scriptBlock($js);
     echo "</div>";
 }
GLPI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with GLPI. If not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------
*/
/** @file
* @brief
*/
include '../inc/includes.php';
Session::checkLoginUser();
$item = new Item_Ticket();
if (isset($_POST["add"])) {
    if (isset($_POST['my_items']) && !empty($_POST['my_items'])) {
        list($_POST['itemtype'], $_POST['items_id']) = explode('_', $_POST['my_items']);
    }
    if (!isset($_POST['items_id']) || empty($_POST['items_id'])) {
        $message = sprintf(__('Mandatory fields are not filled. Please correct: %s'), _n('Associated element', 'Associated elements', 1));
        Session::addMessageAfterRedirect($message, false, ERROR);
        Html::back();
    }
    $item->check(-1, CREATE, $_POST);
    if ($item->add($_POST)) {
        Event::log($_POST["tickets_id"], "ticket", 4, "tracking", sprintf(__('%s adds a link with an item'), $_SESSION["glpiname"]));
    }
    Html::back();
}
 /**
  * Clean data in the tables which have linked the deleted item
  * Clear 1/N Relation
  *
  * @return nothing
  **/
 function cleanRelationData()
 {
     global $DB, $CFG_GLPI;
     $RELATION = getDbRelations();
     if (isset($RELATION[$this->getTable()])) {
         $newval = isset($this->input['_replace_by']) ? $this->input['_replace_by'] : 0;
         foreach ($RELATION[$this->getTable()] as $tablename => $field) {
             if ($tablename[0] != '_') {
                 $itemtype = getItemTypeForTable($tablename);
                 // Code factorization : we transform the singleton to an array
                 if (!is_array($field)) {
                     $field = array($field);
                 }
                 foreach ($field as $f) {
                     foreach ($DB->request($tablename, array($f => $this->getID())) as $data) {
                         // Be carefull : we must use getIndexName because self::update rely on that !
                         if ($object = getItemForItemtype($itemtype)) {
                             $idName = $object->getIndexName();
                             // And we must ensure that the index name is not the same as the field
                             // we try to modify. Otherwise we will loose this element because all
                             // will be set to $newval ...
                             if ($idName != $f) {
                                 $object->update(array($idName => $data[$idName], $f => $newval, '_disablenotif' => true));
                                 // Disable notifs
                             }
                         }
                     }
                 }
             }
         }
     }
     // Clean ticket open against the item
     if (in_array($this->getType(), $CFG_GLPI["ticket_types"])) {
         $job = new Ticket();
         $itemsticket = new Item_Ticket();
         $query = "SELECT *\n                   FROM `glpi_items_tickets`\n                   WHERE `items_id` = '" . $this->fields['id'] . "'\n                         AND `itemtype`='" . $this->getType() . "'";
         $result = $DB->query($query);
         if ($DB->numrows($result)) {
             while ($data = $DB->fetch_assoc($result)) {
                 $cnt = countElementsInTable('glpi_items_tickets', "`tickets_id`='" . $data['tickets_id'] . "'");
                 $job->getFromDB($data['tickets_id']);
                 if ($cnt == 1) {
                     if ($CFG_GLPI["keep_tickets_on_delete"] == 1) {
                         $itemsticket->delete(array("id" => $data["id"]));
                     } else {
                         $job->delete(array("id" => $data["tickets_id"]));
                     }
                 } else {
                     $itemsticket->delete(array("id" => $data["id"]));
                 }
             }
         }
     }
 }
 /**
  * Save form datas to the target
  *
  * @param  PluginFormcreatorFormanswer $formanswer    Answers previously saved
  */
 public function save(PluginFormcreatorFormanswer $formanswer)
 {
     $datas = array();
     $ticket = new Ticket();
     $docItem = new Document_Item();
     $form = new PluginFormcreatorForm();
     $form->getFromDB($formanswer->fields['plugin_formcreator_forms_id']);
     // Get default request type
     $query = "SELECT id FROM `glpi_requesttypes` WHERE `name` LIKE 'Formcreator';";
     $result = $GLOBALS['DB']->query($query) or die($GLOBALS['DB']->error());
     list($requesttypes_id) = $GLOBALS['DB']->fetch_array($result);
     $datas['requesttypes_id'] = $requesttypes_id;
     // Get predefined Fields
     $ttp = new TicketTemplatePredefinedField();
     $predefined_fields = $ttp->getPredefinedFields($this->fields['tickettemplates_id'], true);
     $datas = array_merge($datas, $predefined_fields);
     // Parse datas and tags
     $datas['name'] = addslashes($this->parseTags($this->fields['name'], $formanswer));
     $datas['content'] = htmlentities($this->parseTags($this->fields['comment'], $formanswer));
     $datas['entities_id'] = isset($_SESSION['glpiactive_entity']) ? $_SESSION['glpiactive_entity'] : $form->fields['entities_id'];
     $datas['_users_id_requester'] = 0;
     $datas['_users_id_recipient'] = $_SESSION['glpiID'];
     $datas['_tickettemplates_id'] = $this->fields['tickettemplates_id'];
     // Define due date
     $answer = new PluginFormcreatorAnswer();
     $found = $answer->find('plugin_formcreator_formanwers_id = ' . (int) $formanswer->fields['id'] . ' AND plugin_formcreator_question_id = ' . (int) $this->fields['due_date_question']);
     $date = array_shift($found);
     $str = "+" . $this->fields['due_date_value'] . " " . $this->fields['due_date_period'];
     switch ($this->fields['due_date_rule']) {
         case 'answer':
             $due_date = $date['answer'];
             break;
         case 'ticket':
             $due_date = date('Y-m-d H:i:s', strtotime($str));
             break;
         case 'calcul':
             $due_date = date('Y-m-d H:i:s', strtotime($date['answer'] . " " . $str));
             break;
         default:
             $due_date = null;
             break;
     }
     if (!is_null($due_date)) {
         $datas['due_date'] = $due_date;
     }
     // Select ticket actors
     $query = "SELECT id, actor_type, actor_value, use_notification\n                FROM glpi_plugin_formcreator_targettickets_actors\n                WHERE plugin_formcreator_targettickets_id = " . $this->getID() . "\n                AND actor_role = 'requester'";
     $result = $GLOBALS['DB']->query($query);
     // If there is only one requester add it on creation, otherwize we will add them later
     if ($GLOBALS['DB']->numrows($result) == 1) {
         $actor = $GLOBALS['DB']->fetch_array($result);
         switch ($actor['actor_type']) {
             case 'creator':
                 $user_id = $formanswer->fields['requester_id'];
                 break;
             case 'validator':
                 $user_id = $formanswer->fields['validator_id'];
                 break;
             case 'person':
             case 'group':
             case 'supplier':
                 $user_id = $actor['actor_value'];
                 break;
             case 'question_person':
             case 'question_group':
             case 'question_supplier':
                 $answer = new PluginFormcreatorAnswer();
                 $found = $answer->find('`plugin_formcreator_question_id` = ' . (int) $actor['actor_value'] . ' AND `plugin_formcreator_formanwers_id` = ' . (int) $formanswer->fields['id']);
                 $found = array_shift($found);
                 if (empty($found['answer'])) {
                     continue;
                 } else {
                     $user_id = (int) $found['answer'];
                 }
                 break;
         }
         $datas['_users_id_requester'] = $user_id;
     }
     // Create the target ticket
     if (!($ticketID = $ticket->add($datas))) {
         return false;
     }
     // Add link between Ticket and FormAnswer
     $itemlink = new Item_Ticket();
     $itemlink->add(array('itemtype' => 'PluginFormcreatorFormanswer', 'items_id' => $formanswer->fields['id'], 'tickets_id' => $ticketID));
     // Add actors to ticket
     $query = "SELECT id, actor_role, actor_type, actor_value, use_notification\n                FROM glpi_plugin_formcreator_targettickets_actors\n                WHERE plugin_formcreator_targettickets_id = " . $this->getID();
     $result = $GLOBALS['DB']->query($query);
     while ($actor = $GLOBALS['DB']->fetch_array($result)) {
         // If actor type is validator and if the form doesn't have a validator, continue to other actors
         if ($actor['actor_type'] == 'validator' && !$form->fields['validation_required']) {
             continue;
         }
         switch ($actor['actor_role']) {
             case 'requester':
                 $role = CommonITILActor::REQUESTER;
                 break;
             case 'observer':
                 $role = CommonITILActor::OBSERVER;
                 break;
             case 'assigned':
                 $role = CommonITILActor::ASSIGN;
                 break;
         }
         switch ($actor['actor_type']) {
             case 'creator':
                 $user_id = $formanswer->fields['requester_id'];
                 break;
             case 'validator':
                 $user_id = $formanswer->fields['validator_id'];
                 break;
             case 'person':
             case 'group':
             case 'supplier':
                 $user_id = $actor['actor_value'];
                 break;
             case 'question_person':
             case 'question_group':
             case 'question_supplier':
                 $answer = new PluginFormcreatorAnswer();
                 $found = $answer->find('`plugin_formcreator_question_id` = ' . (int) $actor['actor_value'] . ' AND `plugin_formcreator_formanwers_id` = ' . (int) $formanswer->fields['id']);
                 $found = array_shift($found);
                 if (empty($found['answer'])) {
                     continue;
                 } else {
                     $user_id = (int) $found['answer'];
                 }
                 break;
         }
         switch ($actor['actor_type']) {
             case 'creator':
             case 'validator':
             case 'person':
             case 'question_person':
                 $obj = new Ticket_User();
                 $obj->add(array('tickets_id' => $ticketID, 'users_id' => $user_id, 'type' => $role, 'use_notification' => $actor['use_notification']));
                 break;
             case 'group':
             case 'question_group':
                 $obj = new Group_Ticket();
                 $obj->add(array('tickets_id' => $ticketID, 'groups_id' => $user_id, 'type' => $role, 'use_notification' => $actor['use_notification']));
                 break;
             case 'supplier':
             case 'question_supplier':
                 $obj = new Supplier_Ticket();
                 $obj->add(array('tickets_id' => $ticketID, 'suppliers_id' => $user_id, 'type' => $role, 'use_notification' => $actor['use_notification']));
                 break;
         }
     }
     // Attach documents to ticket
     $found = $docItem->find("itemtype = 'PluginFormcreatorFormanswer' AND items_id = " . (int) $formanswer->getID());
     if (count($found) > 0) {
         foreach ($found as $document) {
             $docItem->add(array('documents_id' => $document['documents_id'], 'itemtype' => 'Ticket', 'items_id' => $ticketID));
         }
     }
     // Attach validation message as first ticket followup if validation is required and
     // if is set in ticket target configuration
     // /!\ Followup is directly saved to the database to avoid double notification on ticket
     //     creation and add followup
     if ($form->fields['validation_required'] && $this->fields['validation_followup']) {
         $message = addslashes(__('Your form have been accepted by the validator', 'formcreator'));
         if (!empty($formanswer->fields['comment'])) {
             $message .= "\n" . addslashes($formanswer->fields['comment']);
         }
         $query = "INSERT INTO `glpi_ticketfollowups` SET\n                     `tickets_id` = {$ticketID},\n                     `date`       = NOW(),\n                     `users_id`   = {$_SESSION['glpiID']},\n                     `content`    = \"{$message}\"";
         $GLOBALS['DB']->query($query);
     }
     return true;
 }
Example #9
0
-------------------------------------------------------------------------

LICENSE

This file is part of GLPI.

GLPI is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

GLPI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with GLPI. If not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------
*/
/** @file
* @brief
*/
$AJAX_INCLUDE = 1;
include '../inc/includes.php';
header("Content-Type: text/html; charset=UTF-8");
Html::header_nocache();
Session::checkRight("ticket", UPDATE);
Item_Ticket::dropdownMyDevices($_POST["userID"], $_POST["entity_restrict"]);
Html::ajaxFooter();
Example #10
0
 /**
  * Transfer tickets
  *
  * @param $itemtype  type of transfered item
  * @param $ID        original ID of the ticket
  * @param $newID     new ID of the ticket
  **/
 function transferTickets($itemtype, $ID, $newID)
 {
     global $DB;
     $job = new Ticket();
     $rel = new Item_Ticket();
     $query = "SELECT `glpi_tickets`.*, `glpi_items_tickets`.`id` as _relid\n                FROM `glpi_tickets`\n                LEFT JOIN `glpi_items_tickets`\n                   ON `glpi_items_tickets`.`tickets_id` = `glpi_tickets`.`id`\n                WHERE `items_id` = '{$ID}'\n                      AND `itemtype` = '{$itemtype}'";
     if ($result = $DB->query($query)) {
         if ($DB->numrows($result) != 0) {
             switch ($this->options['keep_ticket']) {
                 // Transfer
                 case 2:
                     // Same Item / Copy Item -> update entity
                     while ($data = $DB->fetch_assoc($result)) {
                         $input = $this->transferHelpdeskAdditionalInformations($data);
                         $input['id'] = $data['id'];
                         $input['entities_id'] = $this->to;
                         $job->update($input);
                         $input = array();
                         $input['id'] = $data['_relid'];
                         $input['items_id'] = $newID;
                         $input['itemtype'] = $itemtype;
                         $rel->update($input);
                         $this->addToAlreadyTransfer('Ticket', $data['id'], $data['id']);
                         $this->transferTaskCategory('Ticket', $data['id'], $data['id']);
                     }
                     break;
                     // Clean ref : keep ticket but clean link
                 // Clean ref : keep ticket but clean link
                 case 1:
                     // Same Item / Copy Item : keep and clean ref
                     while ($data = $DB->fetch_assoc($result)) {
                         $rel->delete(array('id' => $data['relid']));
                         $this->addToAlreadyTransfer('Ticket', $data['id'], $data['id']);
                     }
                     break;
                     // Delete
                 // Delete
                 case 0:
                     // Same item -> delete
                     if ($ID == $newID) {
                         while ($data = $DB->fetch_assoc($result)) {
                             $job->delete(array('id' => $data['id']));
                         }
                     }
                     // Copy Item : nothing to do
                     break;
             }
         }
     }
 }
Example #11
0
    public static function show($ID, $from_helpdesk)
    {
        global $LANG, $CFG_GLPI, $DB;
        //$logged = $_SESSION['glpiID'];
        if (!isset($_REQUEST['session'])) {
            $IDO = Session::getLoginUserID();
        } else {
            $IDO = $_REQUEST['session'];
        }
        $logged = $ID;
        /*
        echo $logged."logged2 ";
        echo Session::getLoginUserID()."session ";
        */
        if (isset($_REQUEST['id'])) {
            $ID = $_REQUEST['id'];
            $_SESSION["glpiID"] = $_REQUEST['id'];
            $query = "SELECT `profiles_id` AS id\nFROM `glpi_profiles_users`\nWHERE `users_id` = " . $IDO . "\nORDER BY `glpi_profiles_users`.`profiles_id` DESC";
            $result = $DB->query($query);
            $cont = $DB->numrows($result);
            $profile = $DB->fetch_assoc($result);
        } else {
            $ID = $_SESSION['glpiID'];
            $_SESSION['glpiID'] = $_SESSION['glpiID'];
            $query = "SELECT `profiles_id` AS id\nFROM `glpi_profiles_users`\nWHERE `users_id` = " . $IDO . "\nORDER BY `glpi_profiles_users`.`profiles_id` DESC";
            $result = $DB->query($query);
            $cont = $DB->numrows($result);
            $profile = $DB->fetch_assoc($result);
        }
        /*		
        echo $ID."id ";
        echo $_SESSION['glpiID']."glpiid ";
        echo $_SESSION['logged']."logged ";
        echo $logged."logged2 ";
        */
        if (!Session::haveRight("ticket", CREATE)) {
            return false;
        }
        if (Session::haveRight('validate_ticket', 1)) {
            //	      if (Session::haveRightsOr('ticketvalidation', array(TicketValidation::VALIDATEREQUEST, TicketValidation::VALIDATEINCIDENT))) {
            $opt = array();
            $opt['reset'] = 'reset';
            $opt['field'][0] = 55;
            // validation status
            $opt['searchtype'][0] = 'equals';
            $opt['contains'][0] = 'waiting';
            $opt['link'][0] = 'AND';
            $opt['field'][1] = 59;
            // validation aprobator
            $opt['searchtype'][1] = 'equals';
            $opt['contains'][1] = Session::getLoginUserID();
            //$opt['contains'][1]   = $ID;
            $opt['link'][1] = 'AND';
            $url_validate = $CFG_GLPI["root_doc"] . "/front/ticket.php?" . Toolbox::append_params($opt, '&amp;');
            if (TicketValidation::getNumberTicketsToValidate(Session::getLoginUserID()) > 0) {
                //if (TicketValidation::getNumberTicketsToValidate( $ID >0) {
                echo "<a href='{$url_validate}' title=\"" . $LANG['validation'][15] . "\"\n                      alt=\"" . $LANG['validation'][15] . "\">" . $LANG['validation'][33] . "</a><br><br>";
            }
        }
        // Stevenes Donato
        //email user
        $query = "SELECT  gu.id, ge.email, gu.`firstname`, gu.`realname`, gu.`name`\n                 FROM `glpi_users` gu, glpi_useremails ge\n                 WHERE gu.`id` = '{$ID}'\n\t\t\t\t\t  AND ge.users_id = gu.id ";
        $result = $DB->query($query);
        $email = $DB->result($result, 0, "email");
        $user_name = $DB->result($result, 0, "firstname") . " ";
        $user_sname = $DB->result($result, 0, "realname");
        //categories
        $query_cat = "SELECT id, completename\n\t\t\t\t\t\t\tFROM `glpi_itilcategories` \n\t\t\t\t\t\t\tWHERE `is_helpdeskvisible` = 1";
        $result_cat = $DB->query($query_cat);
        $itilcategories_id = $DB->fetch_assoc($result_cat);
        $sql_user = "******";
        $result_user = $DB->query($sql_user);
        $user = $DB->fetch_assoc($result_user);
        // Get saved data from a back system
        $use_email_notification = 1;
        if ($email == "") {
            $use_email_notification = 0;
        }
        $itemtype = 0;
        $items_id = "";
        $content = "";
        $title = "";
        //$itilcategories_id = 0;
        $urgency = 3;
        if (isset($_SESSION["helpdeskSaved"]["use_email_notification"])) {
            $use_email_notification = stripslashes($_SESSION["helpdeskSaved"]["use_email_notification"]);
        }
        if (isset($_SESSION["helpdeskSaved"]["email"])) {
            $email = stripslashes($_SESSION["helpdeskSaved"]["user_email"]);
        }
        if (isset($_SESSION["helpdeskSaved"]["itemtype"])) {
            $itemtype = stripslashes($_SESSION["helpdeskSaved"]["itemtype"]);
        }
        if (isset($_SESSION["helpdeskSaved"]["items_id"])) {
            $items_id = stripslashes($_SESSION["helpdeskSaved"]["items_id"]);
        }
        if (isset($_SESSION["helpdeskSaved"]["content"])) {
            $content = cleanPostForTextArea($_SESSION["helpdeskSaved"]["content"]);
        }
        if (isset($_SESSION["helpdeskSaved"]["name"])) {
            $title = stripslashes($_SESSION["helpdeskSaved"]["name"]);
        }
        if (isset($_SESSION["helpdeskSaved"]["itilcategories_id"])) {
            //$itilcategories_id = stripslashes($_SESSION["helpdeskSaved"]["itilcategories_id"]);
            $itilcategories_id = $_SESSION["helpdeskSaved"]["itilcategories_id"];
        }
        if (isset($_SESSION["helpdeskSaved"]["urgency"])) {
            $urgency = stripslashes($_SESSION["helpdeskSaved"]["urgency"]);
        }
        unset($_SESSION["helpdeskSaved"]);
        echo "<form method='post' name=\"helpdeskform\" action=\"" . $CFG_GLPI["root_doc"] . "/plugins/mobile/front/tracking.injector.php?ido=" . $IDO . "\" enctype=\"multipart/form-data\">";
        echo "<input type='hidden' name='_from_helpdesk' value='{$from_helpdesk}'>";
        if ($CFG_GLPI['urgency_mask'] == 1 << 3) {
            // Dont show dropdown if only 1 value enabled
            echo "<input type='hidden' name='urgency' value='3'>";
        }
        echo "<input type='hidden' name='entities_id' value='" . $_SESSION["glpiactive_entity"] . "'>";
        echo "<div class='force_left input_right'><table class='tab_cadre'>";
        echo "<tr><th colspan='1'>" . $LANG['job'][11] . "&nbsp;: </th></tr>";
        echo "<tr><th colspan='1'>";
        if (Session::isMultiEntitiesMode()) {
            echo "&nbsp;(" . Dropdown::getDropdownName("glpi_entities", $_SESSION["glpiactive_entity"]) . ")";
        }
        echo "</th></tr>";
        //Requerente
        if ($cont != "1" && $profile != "1") {
            echo "<tr class='tab_bg_1'>";
            echo "<td>" . $LANG['job'][4] . "&nbsp;: </td></tr>";
            echo "<tr class='tab_bg_1'>";
            echo "<td >";
            // Dropdown::show('ITILCategories', array('value' => $user,'condition'=>'is_deleted=0'));
            //Dropdown::showFromArray("user_id", $user);
            echo "\n\n<script>\nfunction getComboA(sel) {\n    var id = sel.options[sel.selectedIndex].value; \n    //var name = sel.options[sel.selectedIndex].id;\n    //document.getElementById('user').innerHTML = id;\n    window.location.assign('" . $CFG_GLPI['root_doc'] . "/plugins/mobile/front/helpdesk.php?id='+id+'&session=" . $IDO . "');    \n}\n</script> ";
            echo "<select id='sel_user' onchange='getComboA(this)'>";
            echo '<option value=" "> -- Selecione -- </option>';
            while ($user = $DB->fetch_array($result_user)) {
                echo "<option value=" . $user['id'] . " id= \"" . $user['name'] . " " . $user['sname'] . " \">" . $user['name'] . " " . $user['sname'] . "</option>";
            }
            echo "</select>";
            echo "</td></tr>";
            echo "<tr class='tab_bg_1'>";
            echo "<td>" . $LANG['job'][4] . "&nbsp;: </td></tr>";
            echo "<tr class='center tab_bg_1'>";
            echo "<td >" . $user_name . $user_sname . "</td></tr>";
            echo "<input type='hidden' name='logged' value='" . $logged . "'>";
        }
        if ($CFG_GLPI['urgency_mask'] != 1 << 3) {
            echo "<tr class='tab_bg_1'>";
            echo "<td>" . $LANG['joblist'][29] . "&nbsp;: </td></tr>";
            echo "<tr class='tab_bg_1'>";
            echo "<td>";
            //Ticket::dropdownUrgency("urgency",$urgency);
            Ticket::dropdownUrgency(array('value' => $values["urgency"]));
            echo "</td></tr>";
        }
        if (NotificationTargetTicket::isAuthorMailingActivatedForHelpdesk()) {
            echo "<tr class='tab_bg_1'>";
            echo "<td>" . $LANG['help'][8] . "&nbsp;:</td></tr>";
            echo "<tr class='tab_bg_1'>";
            echo "<td >";
            Dropdown::showYesNo('use_email_notification', $use_email_notification);
            echo "</td></tr>";
            echo "<tr class='tab_bg_1'>";
            echo "<td>" . $LANG['plugin_mobile']["email"] . "&nbsp;:</td></tr>";
            echo "<tr class='tab_bg_1'>";
            echo "<td ><input type='text' id='user_email' name='user_email' value=\"{$email}\" size='40' onchange=\"use_email_notification.value='1'\">";
            echo "</td></tr>";
        }
        if ($_SESSION["glpiactiveprofile"]["helpdesk_hardware"] != 0) {
            echo "<tr class='tab_bg_1'>";
            echo "<td>" . $LANG['help'][24] . "&nbsp;: </td></tr>";
            echo "<tr class='tab_bg_1'>";
            echo "<td >";
            Item_Ticket::dropdownMyDevices(Session::getLoginUserID(), $_SESSION["glpiactive_entity"]);
            //Ticket::dropdownMyDevices($ID,$_SESSION["glpiactive_entity"]);
            echo "</td></tr>";
        }
        //Stevenes Donato
        echo "<tr class='tab_bg_1'>";
        echo "<td class='force_left'>" . $LANG['common'][36] . "&nbsp;:</td></tr>";
        echo "<tr class='tab_bg_1'><td>";
        //Dropdown::show('TicketCategory', array('value' => $itilcategories_id,'condition'=>'`is_helpdeskvisible`=1'));
        //Dropdown::show('ITILCategory', array('value' => $itilcategories_id,'condition'=>'`is_helpdeskvisible`=1'));
        //Dropdown::getDropdownName("glpi_itilcategories", $this->fields["itilcategories_id"]);
        //Dropdown::showFromArray("completename", $itilcategories_id);
        echo "<script>\n\t\tfunction getCat(sel) {\n\t\t    //var x = document.getElementById('sel_cat').value;\n\t\t    var cat = sel.options[sel.selectedIndex].value; \n\t\t    //document.getElementById('demo').innerHTML = 'Categoria: ' + cat;\n\t\t    //document.getElementById('demo').innerHTML = '<input type=\\'text\\' name=\\'itilcategories_id\\' value=\\' +cat+ \\'/>';\n\t\t    document.getElementById('categoria').value = cat;\t\t   \n\t\t}\n\t\t</script>";
        echo "<select id='sel_cat' onchange='getCat(this)'>";
        echo '<option value=" "> -- ' . $LANG['dropdown'][35] . '-- </option>';
        while ($cat = $DB->fetch_array($result_cat)) {
            echo "<option value=" . $cat['id'] . " id= \"" . $cat['completename'] . " \">" . $cat['completename'] . " </option>";
        }
        echo "</select>" . "\n";
        echo "</td></tr>";
        echo "<tr><td>";
        //echo '<label for="itilcategories_id" id="demo"></label>';
        //echo "<span id='demo'></span>";
        echo "<input id='categoria' type='hidden' name='itilcategories_id' value='' />";
        echo "</td></tr>";
        echo "<tr class='tab_bg_1'>";
        echo "<td>" . $LANG['common'][57] . "&nbsp;:</td></tr>";
        echo "<tr class='tab_bg_1'>";
        echo "<td ><input type='text' maxlength='250' size='50' name='name' value=\"{$title}\" required ></td></tr>";
        echo "<tr class='tab_bg_1'>";
        echo "<td>" . $LANG['joblist'][6] . "&nbsp;:</td></tr>";
        echo "<tr class='tab_bg_1'>";
        echo "<td  colspan='1'><textarea name='content' cols='78' rows='14' required >{$content}</textarea>";
        echo "</td></tr>";
        echo "<tr class='tab_bg_1'><td>" . $LANG['document'][2] . " (" . Document::getMaxUploadSize() . ")&nbsp;:";
        /*
         * we hide the picture (aide.png) to prevent the form openning in other window,
         * outside the mobile plugin layout.
               echo "<img src=\"".$CFG_GLPI["root_doc"]."/pics/aide.png\" class='pointer' alt=\"".
                      $LANG['central'][7]."\" onclick=\"window.open('".$CFG_GLPI["root_doc"].
                      "/front/documenttype.list.php','Help','scrollbars=1,resizable=1,width=1000,height=800')\">";
        */
        echo "<input type='hidden' name='ido' value='" . $IDO . "'>";
        ?>

<script>
function getID() {
    var ido = document.getElementById('ido').value; 
    document.getElementById('session').innerHTML = "$_SESSION['logged']="+ido;
    //window.location.assign('".$CFG_GLPI['root_doc']."/plugins/mobile/front/helpdesk.php?id='+id+'&session=".$IDO."');    
}
</script>
<div id="session" style="display:none;"></div>

<?php 
        echo "</td></tr>";
        echo "<tr class='tab_bg_1'>";
        echo "<td><input type='file' class='ui-input-text ui-body-null ui-corner-all ui-shadow-inset ui-body-c' name='filename' value=\"\" size='25'></td></tr>";
        echo "<tr class='tab_bg_1'>";
        echo "<td colspan='1' class='center'>";
        echo "<input type='submit' value=\"" . $LANG['help'][14] . "\" class='submit' >";
        echo "</td></tr>";
        echo "</table></div>";
        //</form>";
        Html::closeForm();
    }
Example #12
0
/** @file
* @brief
*/
include '../inc/includes.php';
Session::checkLoginUser();
$item = new Item_Ticket();
if (isset($_POST["add"])) {
    if (isset($_POST['my_items']) && !empty($_POST['my_items'])) {
        list($_POST['itemtype'], $_POST['items_id']) = explode('_', $_POST['my_items']);
    }
    if (isset($_POST['add_items_id'])) {
        $_POST['items_id'] = $_POST['add_items_id'];
    }
    if (!isset($_POST['items_id']) || empty($_POST['items_id'])) {
        $message = sprintf(__('Mandatory fields are not filled. Please correct: %s'), _n('Associated element', 'Associated elements', 1));
        Session::addMessageAfterRedirect($message, false, ERROR);
        Html::back();
    }
    $item->check(-1, CREATE, $_POST);
    if ($item->add($_POST)) {
        Event::log($_POST["tickets_id"], "ticket", 4, "tracking", sprintf(__('%s adds a link with an item'), $_SESSION["glpiname"]));
    }
    Html::back();
} else {
    if (isset($_POST["delete"])) {
        $item_ticket = new Item_Ticket();
        $deleted = $item_ticket->deleteByCriteria(array('tickets_id' => $_POST['tickets_id'], 'items_id' => $_POST['items_id'], 'itemtype' => $_POST['itemtype']));
        Html::back();
    }
}
Html::displayErrorAndDie("lost");
Example #13
0
GLPI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with GLPI. If not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------
*/
$AJAX_INCLUDE = 1;
include '../inc/includes.php';
header("Content-Type: text/html; charset=UTF-8");
Html::header_nocache();
Session::checkLoginUser();
$item_ticket = new Item_Ticket();
switch ($_GET['action']) {
    case 'add':
        if (isset($_GET['my_items']) && !empty($_GET['my_items'])) {
            list($_GET['itemtype'], $_GET['items_id']) = explode('_', $_GET['my_items']);
        }
        if (isset($_GET['items_id']) && isset($_GET['itemtype']) && !empty($_GET['items_id'])) {
            $added = true;
            if ($added) {
                $_GET['params']['items_id'][$_GET['itemtype']][$_GET['items_id']] = $_GET['items_id'];
            }
        }
        Item_Ticket::itemAddForm(new Ticket(), $_GET['params']);
        break;
    case 'delete':
        if (isset($_GET['items_id']) && isset($_GET['itemtype']) && !empty($_GET['items_id'])) {