static function geTimelineItems(Ticket $ticket, $rand)
 {
     global $DB, $CFG_GLPI;
     $timeline = array();
     $user = new User();
     $group = new Group();
     $followup_obj = new TicketFollowup();
     $task_obj = new TicketTask();
     $document_item_obj = new Document_Item();
     $ticket_valitation_obj = new TicketValidation();
     //checks rights
     $showpublic = Session::haveRightsOr("followup", array(TicketFollowup::SEEPUBLIC, TicketFollowup::SEEPRIVATE)) && Session::haveRightsOr("task", array(TicketTask::SEEPUBLIC, TicketTask::SEEPRIVATE));
     $restrict_fup = $restrict_task = "";
     if (!Session::haveRight("ticket", TicketFollowup::SEEPRIVATE)) {
         $restrict_fup = " AND (`is_private` = '0'\n                            OR `users_id` ='" . Session::getLoginUserID() . "') ";
     }
     if (!Session::haveRight("ticket", TicketTask::SEEPRIVATE)) {
         $restrict_task = " AND (`is_private` = '0'\n                            OR `users_id` ='" . Session::getLoginUserID() . "') ";
     }
     if (!$showpublic) {
         $restrict = " AND 1 = 0";
     }
     //add ticket followups to timeline
     $followups = $followup_obj->find("tickets_id = " . $ticket->getID() . " {$restrict_fup}", 'date DESC');
     foreach ($followups as $followups_id => $followup) {
         $followup_obj->getFromDB($followups_id);
         $can_edit = $followup_obj->canUpdateItem();
         $followup['can_edit'] = $can_edit;
         $timeline[$followup['date'] . "_followup_" . $followups_id] = array('type' => 'TicketFollowup', 'item' => $followup);
     }
     //add ticket tasks to timeline
     $tasks = $task_obj->find("tickets_id = " . $ticket->getID() . " {$restrict_task}", 'date DESC');
     foreach ($tasks as $tasks_id => $task) {
         $task_obj->getFromDB($tasks_id);
         $can_edit = $task_obj->canUpdateItem();
         $task['can_edit'] = $can_edit;
         $timeline[$task['date'] . "_task_" . $tasks_id] = array('type' => 'TicketTask', 'item' => $task);
     }
     //add ticket documents to timeline
     $document_obj = new Document();
     $document_items = $document_item_obj->find("itemtype = 'Ticket' AND items_id = " . $ticket->getID());
     foreach ($document_items as $document_item) {
         $document_obj->getFromDB($document_item['documents_id']);
         $timeline[$document_obj->fields['date_mod'] . "_document_" . $document_item['documents_id']] = array('type' => 'Document_Item', 'item' => $document_obj->fields);
     }
     //add assign changes
     /*$log_obj = new Log;
           $gassign_items = $log_obj->find("itemtype = 'Ticket' AND items_id = ".$ticket->getID()." 
                                            AND itemtype_link = 'Group' AND linked_action = '15'");
     
           foreach ($gassign_items as $logs_id => $gassign) {
              //find group
              $group_name = preg_replace("#(.*)\s\([0-9]*\)#", "$1", $gassign['new_value']);
              $groups = $group->find("name = '$group_name'");
              $first_group = array_shift($groups);
              $group->getFromDB($first_group['id']);
              $content = __("Assigned to")." : ".
                         "<img src='".$CFG_GLPI['root_doc']."/plugins/talk/pics/group.png' class='group_assign' />".
                         "&nbsp;<strong>".$group->getLink()."</strong>";
     
              //find user
              $user_name = preg_replace("#(.*)\s\([0-9]*\)#", "$1", $gassign['user_name']);
              $users = $user->find("CONCAT(firstname, ' ', realname) = '$user_name'");
              $first_user = array_shift($users);
              if ($first_user == NULL) {
                 $first_user['id'] = false;
              }
     
              $timeline[$gassign['date_mod']."_assign_".$logs_id] = array('type' => 'Assign', 
                                                                          'item' => array(
                                                                             'date'     => $gassign['date_mod'],
                                                                             'content'  => $content,
                                                                             'can_edit' => false,
                                                                             'users_id' => $first_user['id']
                                                                          ));
           }*/
     //add existing solution
     if (!empty($ticket->fields['solution'])) {
         $users_id = 0;
         $solution_date = $ticket->fields['solvedate'];
         //search date and user of last solution in glpi_logs
         if ($res_solution = $DB->query("SELECT date_mod AS solution_date, user_name FROM glpi_logs\n                                     WHERE itemtype = 'Ticket' \n                                     AND items_id = " . $ticket->getID() . "\n                                     AND id_search_option = 24\n                                     ORDER BY id DESC\n                                     LIMIT 1")) {
             $data_solution = $DB->fetch_assoc($res_solution);
             if (!empty($data_solution['solution_date'])) {
                 $solution_date = $data_solution['solution_date'];
             }
             // find user
             if (!empty($data_solution['user_name'])) {
                 $users_id = addslashes(trim(preg_replace("/.*\\(([0-9]+)\\)/", "\$1", $data_solution['user_name'])));
             }
         }
         // fix trouble with html_entity_decode who skip accented characters (on windows browser)
         $solution_content = preg_replace_callback("/(&#[0-9]+;)/", function ($m) {
             return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES");
         }, $ticket->fields['solution']);
         $timeline[$solution_date . "_solution"] = array('type' => 'Solution', 'item' => array('id' => 0, 'content' => Html::clean(html_entity_decode($solution_content)), 'date' => $solution_date, 'users_id' => $users_id, 'solutiontypes_id' => $ticket->fields['solutiontypes_id'], 'can_edit' => Ticket::canUpdate() && $ticket->canSolve()));
     }
     // add ticket validation to timeline
     if ($ticket->fields['type'] == Ticket::DEMAND_TYPE && (Session::haveRight('ticketvalidation', TicketValidation::VALIDATEREQUEST) || Session::haveRight('ticketvalidation', TicketValidation::CREATEREQUEST)) || $ticket->fields['type'] == Ticket::INCIDENT_TYPE && (Session::haveRight('ticketvalidation', TicketValidation::VALIDATEINCIDENT) || Session::haveRight('ticketvalidation', TicketValidation::CREATEINCIDENT))) {
         $ticket_validations = $ticket_valitation_obj->find('tickets_id = ' . $ticket->getID());
         foreach ($ticket_validations as $validations_id => $validation) {
             $canedit = $ticket_valitation_obj->can($validations_id, UPDATE);
             $user->getFromDB($validation['users_id_validate']);
             $timeline[$validation['submission_date'] . "_validation_" . $validations_id] = array('type' => 'TicketValidation', 'item' => array('id' => $validations_id, 'date' => $validation['submission_date'], 'content' => __('Validation request') . " => " . $user->getlink() . "<br>" . $validation['comment_submission'], 'users_id' => $validation['users_id'], 'can_edit' => $canedit));
             if (!empty($validation['validation_date'])) {
                 $timeline[$validation['validation_date'] . "_validation_" . $validations_id] = array('type' => 'TicketValidation', 'item' => array('id' => $validations_id, 'date' => $validation['validation_date'], 'content' => __('Validation request answer') . " : " . _sx('status', ucfirst(TicketValidation::getStatus($validation['status']))) . "<br>" . $validation['comment_validation'], 'users_id' => $validation['users_id_validate'], 'status' => "status_" . $validation['status'], 'can_edit' => $canedit));
             }
         }
     }
     //reverse sort timeline items by key (date)
     krsort($timeline);
     return $timeline;
 }
예제 #2
0
 static function pdfForTicket(PluginPdfSimplePDF $pdf, Ticket $job, $private)
 {
     global $CFG_GLPI, $DB;
     $ID = $job->getField('id');
     //////////////Tasks///////////
     $RESTRICT = "";
     if (!$private) {
         // Don't show private'
         $RESTRICT = " AND `is_private` = '0' ";
     } else {
         if (!Session::haveRight("show_full_ticket", "1")) {
             // No right, only show connected user private one
             $RESTRICT = " AND (`is_private` = '0'\n                          OR `users_id` ='" . Session::getLoginUserID() . "' ) ";
         }
     }
     $query = "SELECT *\n                FROM `glpi_tickettasks`\n                WHERE `tickets_id` = '{$ID}'\n                      {$RESTRICT}\n                ORDER BY `date` DESC";
     $result = $DB->query($query);
     if (!$DB->numrows($result)) {
         $pdf->setColumnsSize(100);
         $pdf->displayLine(__('No task found.'));
     } else {
         $pdf->displayTitle("<b>" . TicketTask::getTypeName($DB->numrows($result) . "</b>"));
         $pdf->setColumnsSize(20, 20, 20, 20, 20);
         $pdf->displayTitle("<b><i>" . __('Type') . "</i></b>", "<b><i>" . __('Date') . "</i></b>", "<b><i>" . __('Duration') . "</i></b>", "<b><i>" . __('Writer') . "</i></b>", "<b><i>" . __('Planning') . "</i></b>");
         while ($data = $DB->fetch_array($result)) {
             $actiontime = Html::timestampToString($data['actiontime'], false);
             $planification = '';
             if (empty($data['begin'])) {
                 if (isset($data["state"])) {
                     $planification = Planning::getState($data["state"]) . "<br>";
                 }
                 $planification .= _e('None');
             } else {
                 if (isset($data["state"])) {
                     $planification = sprintf(__('%1$s: %2$s'), _x('item', 'State'), Planning::getState($data["state"]));
                 }
                 $planificiation = sprintf(__('%1$s - %2$s'), $planification, Html::convDateTime($data["begin"]) . " -> " . Html::convDateTime($data["end"]));
                 $planificiation = sprintf(__('%1$s - %2$s'), $planification, sprintf(__('%1$s  %2$s'), __('By'), getUserName($data["users_id_tech"])));
             }
             if ($data['taskcategories_id']) {
                 $lib = Dropdown::getDropdownName('glpi_taskcategories', $data['taskcategories_id']);
             } else {
                 $lib = '';
             }
             if ($data['is_private']) {
                 $lib = sprintf(__('%1$s (%2$s)'), $lib, __('Private'));
             }
             toolbox::logdebug("lib", $data);
             $pdf->displayLine(Html::clean($lib), Html::convDateTime($data["date"]), Html::timestampToString($data["actiontime"], 0), Html::clean(getUserName($data["users_id"])), Html::clean($planification), 1);
             $pdf->displayText("<b><i>" . sprintf(__('%1$s: %2$s'), __('Description') . "</i></b>", Html::clean($data["content"]), 1));
         }
     }
     $pdf->displaySpace();
 }
 function __construct($entity = '', $event = '', $object = null, $options = array())
 {
     parent::__construct($entity, $event, $object, $options);
     $this->options['sendprivate'] = false;
     if (isset($options['followup_id'])) {
         $fup = new TicketFollowup();
         if ($fup->getFromDB($options['followup_id'])) {
             if ($fup->fields['is_private']) {
                 $this->options['sendprivate'] = true;
             }
         }
     }
     if (isset($options['task_id'])) {
         $fup = new TicketTask();
         if ($fup->getFromDB($options['task_id'])) {
             if ($fup->fields['is_private']) {
                 $this->options['sendprivate'] = true;
             }
         }
     }
 }
예제 #4
0
/**
 * Update from 0.80.3 to 0.83
 *
 * @return bool for success (will die for most error)
**/
function update0803to083()
{
    global $DB, $migration;
    $updateresult = true;
    $ADDTODISPLAYPREF = array();
    //TRANS: %s is the number of new version
    $migration->displayTitle(sprintf(__('Update to %s'), '0.83'));
    $migration->setVersion('0.83');
    $backup_tables = false;
    $newtables = array('glpi_entities_knowbaseitems', 'glpi_entities_reminders', 'glpi_groups_problems', 'glpi_groups_knowbaseitems', 'glpi_groups_reminders', 'glpi_knowbaseitems_profiles', 'glpi_knowbaseitems_users', 'glpi_items_problems', 'glpi_problems', 'glpi_problemtasks', 'glpi_problems_ticket', 'glpi_problems_users', 'glpi_profiles_reminders', 'glpi_reminders_users', 'glpi_ticketrecurrents', 'glpi_tickettemplates', 'glpi_tickettemplatehiddenfields', 'glpi_tickettemplatemandatoryfields', 'glpi_tickettemplatepredefinedfields', 'glpi_useremails');
    foreach ($newtables as $new_table) {
        // rename new tables if exists ?
        if (TableExists($new_table)) {
            $migration->dropTable("backup_{$new_table}");
            $migration->displayWarning("{$new_table} table already exists. " . "A backup have been done to backup_{$new_table}.");
            $backup_tables = true;
            $query = $migration->renameTable("{$new_table}", "backup_{$new_table}");
        }
    }
    if ($backup_tables) {
        $migration->displayWarning("You can delete backup tables if you have no need of them.", true);
    }
    //TRANS: %s is the table or item implied
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Problems'));
    // Clean ticket validations : already done in 0.80
    $query = "DELETE\n             FROM `glpi_ticketvalidations`\n             WHERE `glpi_ticketvalidations`.`tickets_id` NOT IN (SELECT `glpi_tickets`.`id`\n                                                                 FROM `glpi_tickets`)";
    $DB->queryOrDie($query, "0.83 clean glpi_ticketvalidations");
    // Problems management
    if (!TableExists('glpi_problems')) {
        $query = "CREATE TABLE `glpi_problems` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `name` varchar(255) DEFAULT NULL,\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n                  `is_deleted` tinyint(1) NOT NULL DEFAULT '0',\n                  `status` varchar(255) DEFAULT NULL,\n                  `content` longtext DEFAULT NULL,\n                  `date_mod` DATETIME DEFAULT NULL,\n                  `date` DATETIME DEFAULT NULL,\n                  `solvedate` DATETIME DEFAULT NULL,\n                  `closedate` DATETIME DEFAULT NULL,\n                  `due_date` DATETIME DEFAULT NULL,\n                  `users_id_recipient` int(11) NOT NULL DEFAULT '0',\n                  `users_id_lastupdater` int(11) NOT NULL DEFAULT '0',\n                  `suppliers_id_assign` int(11) NOT NULL DEFAULT '0',\n                  `urgency` int(11) NOT NULL DEFAULT '1',\n                  `impact` int(11) NOT NULL DEFAULT '1',\n                  `priority` int(11) NOT NULL DEFAULT '1',\n                  `itilcategories_id` int(11) NOT NULL DEFAULT '0',\n                  `impactcontent` longtext DEFAULT NULL,\n                  `causecontent` longtext DEFAULT NULL,\n                  `symptomcontent` longtext DEFAULT NULL,\n                  `solutiontypes_id` int(11) NOT NULL DEFAULT '0',\n                  `solution` text COLLATE utf8_unicode_ci,\n                  `actiontime` int(11) NOT NULL DEFAULT '0',\n                  `begin_waiting_date` datetime DEFAULT NULL,\n                  `waiting_duration` int(11) NOT NULL DEFAULT '0',\n                  `close_delay_stat` int(11) NOT NULL DEFAULT '0',\n                  `solve_delay_stat` int(11) NOT NULL DEFAULT '0',\n                  `notepad` LONGTEXT NULL,\n                  PRIMARY KEY (`id`),\n                  KEY `name` (`name`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`),\n                  KEY `is_deleted` (`is_deleted`),\n                  KEY `date` (`date`),\n                  KEY `closedate` (`closedate`),\n                  KEY `status` (`status`(1)),\n                  KEY `priority` (`priority`),\n                  KEY `date_mod` (`date_mod`),\n                  KEY `suppliers_id_assign` (`suppliers_id_assign`),\n                  KEY `itilcategories_id` (`itilcategories_id`),\n                  KEY `users_id_recipient` (`users_id_recipient`),\n                  KEY `solvedate` (`solvedate`),\n                  KEY `solutiontypes_id` (`solutiontypes_id`),\n                  KEY `urgency` (`urgency`),\n                  KEY `impact` (`impact`),\n                  KEY `due_date` (`due_date`),\n                  KEY `users_id_lastupdater` (`users_id_lastupdater`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 create glpi_problems");
        $ADDTODISPLAYPREF['Problem'] = array(21, 12, 19, 15, 3, 7, 18);
    }
    if (FieldExists('glpi_tickets', 'ticket_waiting_duration', false)) {
        $migration->changeField('glpi_tickets', 'ticket_waiting_duration', 'waiting_duration', 'integer');
    }
    if (!TableExists('glpi_problems_users')) {
        $query = "CREATE TABLE `glpi_problems_users` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `problems_id` int(11) NOT NULL DEFAULT '0',\n                  `users_id` int(11) NOT NULL DEFAULT '0',\n                  `type` int(11) NOT NULL DEFAULT '1',\n                  `use_notification` tinyint(1) NOT NULL DEFAULT '0',\n                  `alternative_email` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`problems_id`,`type`,`users_id`,`alternative_email`),\n                  KEY `user` (`users_id`,`type`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_problems_users");
    }
    if (!TableExists('glpi_groups_problems')) {
        $query = "CREATE TABLE `glpi_groups_problems` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `problems_id` int(11) NOT NULL DEFAULT '0',\n                  `groups_id` int(11) NOT NULL DEFAULT '0',\n                  `type` int(11) NOT NULL DEFAULT '1',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`problems_id`,`type`,`groups_id`),\n                  KEY `group` (`groups_id`,`type`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_groups_problems");
    }
    if (!TableExists('glpi_items_problems')) {
        $query = "CREATE TABLE `glpi_items_problems` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `problems_id` int(11) NOT NULL DEFAULT '0',\n                  `itemtype` varchar(100) default NULL,\n                  `items_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`problems_id`,`itemtype`,`items_id`),\n                  KEY `item` (`itemtype`,`items_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_items_problems");
    }
    if (!TableExists('glpi_problems_tickets')) {
        $query = "CREATE TABLE `glpi_problems_tickets` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `problems_id` int(11) NOT NULL DEFAULT '0',\n                  `tickets_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`problems_id`,`tickets_id`),\n                  KEY `tickets_id` (`tickets_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_problems_tickets");
    }
    if (!TableExists('glpi_problemtasks')) {
        $query = "CREATE TABLE `glpi_problemtasks` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `problems_id` int(11) NOT NULL DEFAULT '0',\n                  `taskcategories_id` int(11) NOT NULL DEFAULT '0',\n                  `date` datetime DEFAULT NULL,\n                  `begin` datetime DEFAULT NULL,\n                  `end` datetime DEFAULT NULL,\n                  `users_id` int(11) NOT NULL DEFAULT '0',\n                  `users_id_tech` int(11) NOT NULL DEFAULT '0',\n                  `content` longtext COLLATE utf8_unicode_ci,\n                  `actiontime` int(11) NOT NULL DEFAULT '0',\n                  `state` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  KEY `problems_id` (`problems_id`),\n                  KEY `users_id` (`users_id`),\n                  KEY `users_id_tech` (`users_id_tech`),\n                  KEY `date` (`date`),\n                  KEY `begin` (`begin`),\n                  KEY `end` (`end`),\n                  KEY `state` (`state`),\n                  KEY `taskcategories_id` (taskcategories_id)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_problemtasks");
    }
    $migration->addField("glpi_profiles", "show_my_problem", "char", array('update' => "1", 'condition' => " WHERE `own_ticket` = 1"));
    $migration->addField("glpi_profiles", "show_all_problem", "char", array('update' => "1", 'condition' => " WHERE `show_all_ticket` = 1"));
    $migration->addField("glpi_profiles", "edit_all_problem", "char", array('update' => "1", 'condition' => " WHERE `update_ticket` = 1"));
    $migration->changeField("glpi_profiles", 'helpdesk_status', 'ticket_status', "text", array('comment' => "json encoded array of from/dest allowed status change"));
    $migration->addField('glpi_profiles', 'problem_status', "text", array('comment' => "json encoded array of from/dest allowed status change"));
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Changes'));
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'TicketPlanning'));
    // Merge tickettasks and ticket planning
    if (TableExists('glpi_ticketplannings')) {
        $migration->addField("glpi_tickettasks", "begin", "datetime");
        $migration->addField("glpi_tickettasks", "end", "datetime");
        $migration->addField("glpi_tickettasks", "state", "integer", array('value' => '1'));
        $migration->addField("glpi_tickettasks", "users_id_tech", "integer");
        $migration->migrationOneTable('glpi_tickettasks');
        // migrate DATA
        $task = new TicketTask();
        foreach ($DB->request('glpi_ticketplannings') as $data) {
            if ($task->getFromDB($data['tickettasks_id'])) {
                $query = "UPDATE `glpi_tickettasks`\n                      SET `begin` = " . ($data['begin'] == 'NULL' || is_null($data['begin']) ? 'NULL' : "'" . $data['begin'] . "'") . ",\n                          `end` = " . ($data['end'] == 'NULL' || is_null($data['end']) ? 'NULL' : "'" . $data['end'] . "'") . ",\n                          `users_id_tech` = '" . $data['users_id'] . "',\n                          `state` = '" . $data['state'] . "'\n                      WHERE `id` = '" . $data['tickettasks_id'] . "'";
                $DB->queryOrDie($query, "0.83 migrate planning to glpi_tickettasks");
            }
        }
        $migration->dropTable("glpi_ticketplannings");
        $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Notification'));
        // Migrate templates
        $from = array('task.planning.user##', 'task.planning.begin##', 'task.planning.end##', 'task.planning.status##');
        $to = array('task.user##', 'task.begin##', 'task.end##', 'task.status##');
        $query = "SELECT `glpi_notificationtemplatetranslations`.*\n                FROM `glpi_notificationtemplatetranslations`\n                INNER JOIN `glpi_notificationtemplates`\n                     ON (`glpi_notificationtemplates`.`id`\n                           = `glpi_notificationtemplatetranslations`.`notificationtemplates_id`)\n                WHERE `glpi_notificationtemplates`.`itemtype` = 'Ticket'";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result)) {
                while ($data = $DB->fetch_assoc($result)) {
                    $query = "UPDATE `glpi_notificationtemplatetranslations`\n                         SET `subject` = '" . addslashes(str_replace($from, $to, $data['subject'])) . "',\n                             `content_text` = '" . addslashes(str_replace($from, $to, $data['content_text'])) . "',\n                             `content_html` = '" . addslashes(str_replace($from, $to, $data['content_html'])) . "'\n                         WHERE `id` = " . $data['id'] . "";
                    $DB->queryOrDie($query, "0.83 fix tags usage for multi users");
                }
            }
        }
    }
    $query = "SELECT *\n             FROM `glpi_notificationtemplates`\n             WHERE `name` = 'Problems'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) == 0) {
            $query = "INSERT INTO `glpi_notificationtemplates`\n                          (`name`, `itemtype`, `date_mod`)\n                   VALUES ('Problems', 'Problem', NOW())";
            $DB->queryOrDie($query, "0.83 add problem notification");
            $notid = $DB->insert_id();
            $query = "INSERT INTO `glpi_notificationtemplatetranslations`\n                          (`notificationtemplates_id`, `language`, `subject`,\n                           `content_text`,\n                           `content_html`)\n                   VALUES ({$notid}, '', '##problem.action## ##problem.title##',\n                          '##IFproblem.storestatus=solved##\n ##lang.problem.url## : ##problem.urlapprove##\n ##lang.problem.solvedate## : ##problem.solvedate##\n ##lang.problem.solution.type## : ##problem.solution.type##\n ##lang.problem.solution.description## : ##problem.solution.description## ##ENDIFproblem.storestatus##\n ##ELSEproblem.storestatus## ##lang.problem.url## : ##problem.url## ##ENDELSEproblem.storestatus##\n\n ##lang.problem.description##\n\n ##lang.problem.title## &#160;:##problem.title##\n ##lang.problem.authors## &#160;:##IFproblem.authors## ##problem.authors## ##ENDIFproblem.authors## ##ELSEproblem.authors##--##ENDELSEproblem.authors##\n ##lang.problem.creationdate## &#160;:##problem.creationdate##\n ##IFproblem.assigntousers## ##lang.problem.assigntousers## &#160;: ##problem.assigntousers## ##ENDIFproblem.assigntousers##\n ##lang.problem.status## &#160;: ##problem.status##\n ##IFproblem.assigntogroups## ##lang.problem.assigntogroups## &#160;: ##problem.assigntogroups## ##ENDIFproblem.assigntogroups##\n ##lang.problem.urgency## &#160;: ##problem.urgency##\n ##lang.problem.impact## &#160;: ##problem.impact##\n ##lang.problem.priority## : ##problem.priority##\n##IFproblem.category## ##lang.problem.category## &#160;:##problem.category## ##ENDIFproblem.category## ##ELSEproblem.category## ##lang.problem.nocategoryassigned## ##ENDELSEproblem.category##\n ##lang.problem.content## &#160;: ##problem.content##\n\n##IFproblem.storestatus=closed##\n ##lang.problem.solvedate## : ##problem.solvedate##\n ##lang.problem.solution.type## : ##problem.solution.type##\n ##lang.problem.solution.description## : ##problem.solution.description##\n##ENDIFproblem.storestatus##\n ##lang.problem.numberoftickets##&#160;: ##problem.numberoftickets##\n\n##FOREACHtickets##\n [##ticket.date##] ##lang.problem.title## : ##ticket.title##\n ##lang.problem.content## ##ticket.content##\n\n##ENDFOREACHtickets##\n ##lang.problem.numberoftasks##&#160;: ##problem.numberoftasks##\n\n##FOREACHtasks##\n [##task.date##]\n ##lang.task.author## ##task.author##\n ##lang.task.description## ##task.description##\n ##lang.task.time## ##task.time##\n ##lang.task.category## ##task.category##\n\n##ENDFOREACHtasks##\n',\n                          '&lt;p&gt;##IFproblem.storestatus=solved##&lt;/p&gt;\n&lt;div&gt;##lang.problem.url## : &lt;a href=\"##problem.urlapprove##\"&gt;##problem.urlapprove##&lt;/a&gt;&lt;/div&gt;\n&lt;div&gt;&lt;span style=\"color: #888888;\"&gt;&lt;strong&gt;&lt;span style=\"text-decoration: underline;\"&gt;##lang.problem.solvedate##&lt;/span&gt;&lt;/strong&gt;&lt;/span&gt; : ##problem.solvedate##&lt;br /&gt;&lt;span style=\"text-decoration: underline; color: #888888;\"&gt;&lt;strong&gt;##lang.problem.solution.type##&lt;/strong&gt;&lt;/span&gt; : ##problem.solution.type##&lt;br /&gt;&lt;span style=\"text-decoration: underline; color: #888888;\"&gt;&lt;strong&gt;##lang.problem.solution.description##&lt;/strong&gt;&lt;/span&gt; : ##problem.solution.description## ##ENDIFproblem.storestatus##&lt;/div&gt;\n&lt;div&gt;##ELSEproblem.storestatus## ##lang.problem.url## : &lt;a href=\"##problem.url##\"&gt;##problem.url##&lt;/a&gt; ##ENDELSEproblem.storestatus##&lt;/div&gt;\n&lt;p class=\"description b\"&gt;&lt;strong&gt;##lang.problem.description##&lt;/strong&gt;&lt;/p&gt;\n&lt;p&gt;&lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.problem.title##&lt;/span&gt;&#160;:##problem.title## &lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.problem.authors##&lt;/span&gt;&#160;:##IFproblem.authors## ##problem.authors## ##ENDIFproblem.authors##    ##ELSEproblem.authors##--##ENDELSEproblem.authors## &lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.problem.creationdate##&lt;/span&gt;&#160;:##problem.creationdate## &lt;br /&gt; ##IFproblem.assigntousers## &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.problem.assigntousers##&lt;/span&gt;&#160;: ##problem.assigntousers## ##ENDIFproblem.assigntousers##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;##lang.problem.status## &lt;/span&gt;&#160;: ##problem.status##&lt;br /&gt; ##IFproblem.assigntogroups## &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.problem.assigntogroups##&lt;/span&gt;&#160;: ##problem.assigntogroups## ##ENDIFproblem.assigntogroups##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.problem.urgency##&lt;/span&gt;&#160;: ##problem.urgency##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.problem.impact##&lt;/span&gt;&#160;: ##problem.impact##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.problem.priority##&lt;/span&gt; : ##problem.priority## &lt;br /&gt;##IFproblem.category##&lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;##lang.problem.category## &lt;/span&gt;&#160;:##problem.category##  ##ENDIFproblem.category## ##ELSEproblem.category##  ##lang.problem.nocategoryassigned## ##ENDELSEproblem.category##    &lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.problem.content##&lt;/span&gt;&#160;: ##problem.content##&lt;/p&gt;\n&lt;p&gt;##IFproblem.storestatus=closed##&lt;br /&gt;&lt;span style=\"text-decoration: underline;\"&gt;&lt;strong&gt;&lt;span style=\"color: #888888;\"&gt;##lang.problem.solvedate##&lt;/span&gt;&lt;/strong&gt;&lt;/span&gt; : ##problem.solvedate##&lt;br /&gt;&lt;span style=\"color: #888888;\"&gt;&lt;strong&gt;&lt;span style=\"text-decoration: underline;\"&gt;##lang.problem.solution.type##&lt;/span&gt;&lt;/strong&gt;&lt;/span&gt; : ##problem.solution.type##&lt;br /&gt;&lt;span style=\"text-decoration: underline; color: #888888;\"&gt;&lt;strong&gt;##lang.problem.solution.description##&lt;/strong&gt;&lt;/span&gt; : ##problem.solution.description##&lt;br /&gt;##ENDIFproblem.storestatus##&lt;/p&gt;\n&lt;div class=\"description b\"&gt;##lang.problem.numberoftickets##&#160;: ##problem.numberoftickets##&lt;/div&gt;\n&lt;p&gt;##FOREACHtickets##&lt;/p&gt;\n&lt;div&gt;&lt;strong&gt; [##ticket.date##] &lt;em&gt;##lang.problem.title## : &lt;a href=\"##ticket.url##\"&gt;##ticket.title## &lt;/a&gt;&lt;/em&gt;&lt;/strong&gt;&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; &lt;/span&gt;&lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;##lang.problem.content## &lt;/span&gt; ##ticket.content##\n&lt;p&gt;##ENDFOREACHtickets##&lt;/p&gt;\n&lt;div class=\"description b\"&gt;##lang.problem.numberoftasks##&#160;: ##problem.numberoftasks##&lt;/div&gt;\n&lt;p&gt;##FOREACHtasks##&lt;/p&gt;\n&lt;div class=\"description b\"&gt;&lt;strong&gt;[##task.date##] &lt;/strong&gt;&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.task.author##&lt;/span&gt; ##task.author##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.task.description##&lt;/span&gt; ##task.description##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.task.time##&lt;/span&gt; ##task.time##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.task.category##&lt;/span&gt; ##task.category##&lt;/div&gt;\n&lt;p&gt;##ENDFOREACHtasks##&lt;/p&gt;\n&lt;/div&gt;')";
            $DB->queryOrDie($query, "0.83 add problem notification translation");
            $notifications = array('new' => array(), 'update' => array(Notification::ASSIGN_TECH, Notification::OLD_TECH_IN_CHARGE), 'solved' => array(), 'add_task' => array(), 'update_task' => array(), 'delete_task' => array(), 'closed' => array(), 'delete' => array());
            $notif_names = array('new' => 'New Problem', 'update' => 'Update Problem', 'solved' => 'Resolve Problem', 'add_task' => 'Add Task', 'update_task' => 'Update Task', 'delete_task' => 'Delete Task', 'closed' => 'Close Problem', 'delete' => 'Delete Problem');
            foreach ($notifications as $key => $val) {
                $notifications[$key][] = Notification::AUTHOR;
                $notifications[$key][] = Notification::GLOBAL_ADMINISTRATOR;
                $notifications[$key][] = Notification::OBSERVER;
            }
            foreach ($notifications as $type => $targets) {
                $query = "INSERT INTO `glpi_notifications`\n                             (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n                              `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n                              `date_mod`)\n                      VALUES ('" . $notif_names[$type] . "', 0, 'Problem', '{$type}', 'mail',\n                              {$notid}, '', 1, 1, NOW())";
                $DB->queryOrDie($query, "0.83 add problem {$type} notification");
                $notifid = $DB->insert_id();
                foreach ($targets as $target) {
                    $query = "INSERT INTO `glpi_notificationtargets`\n                                (`id`, `notifications_id`, `type`, `items_id`)\n                         VALUES (NULL, {$notifid}, " . Notification::USER_TYPE . ", {$target});";
                    $DB->queryOrDie($query, "0.83 add problem {$type} notification target");
                }
            }
        }
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'Clean Vlans'));
    // Clean `glpi_networkports_vlans` datas (`networkports_id` whithout networkports)
    $query = "DELETE\n             FROM `glpi_networkports_vlans`\n             WHERE `networkports_id` NOT IN (SELECT `id`\n                                             FROM `glpi_networkports`)";
    $DB->queryOrDie($query, "0.83 clean networkports_vlans datas");
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Rename Solution objects'));
    // rename glpi_ticketsolutiontypes to glpi_solutiontypes
    $migration->renameTable('glpi_ticketsolutiontypes', 'glpi_solutiontypes');
    // rename glpi_ticketsolutiontemplates to glpi_solutiontemplates
    $migration->renameTable('glpi_ticketsolutiontemplates', 'glpi_solutiontemplates');
    $migration->changeField('glpi_tickets', 'ticketsolutiontypes_id', 'solutiontypes_id', 'integer');
    $migration->changeField('glpi_solutiontemplates', 'ticketsolutiontypes_id', 'solutiontypes_id', 'integer');
    $migration->changeField('glpi_tickets_users', 'use_notification', 'use_notification', 'bool', array('value' => '1'));
    // to have correct name of key
    $migration->dropKey('glpi_tickets', 'ticketsolutiontypes_id');
    $migration->migrationOneTable('glpi_tickets');
    $migration->addKey('glpi_tickets', 'solutiontypes_id');
    $migration->dropKey('glpi_solutiontemplates', 'ticketsolutiontypes_id');
    $migration->migrationOneTable('glpi_solutiontemplates');
    $migration->addKey('glpi_solutiontemplates', 'solutiontypes_id');
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Rename Category objects'));
    $migration->renameTable('glpi_ticketcategories', 'glpi_itilcategories');
    $migration->dropKey('glpi_itilcategories', 'ticketcategories_id');
    $migration->changeField('glpi_itilcategories', 'ticketcategories_id', 'itilcategories_id', 'integer');
    $migration->migrationOneTable('glpi_itilcategories');
    $migration->addKey('glpi_itilcategories', 'itilcategories_id');
    $migration->dropKey('glpi_tickets', 'ticketcategories_id');
    $migration->changeField('glpi_tickets', 'ticketcategories_id', 'itilcategories_id', 'integer');
    $migration->migrationOneTable('glpi_tickets');
    $migration->addKey('glpi_tickets', 'itilcategories_id');
    // Update Itemtype datas in tables
    $itemtype_tables = array("glpi_bookmarks", "glpi_bookmarks_users", "glpi_displaypreferences");
    $typestochange = array('TicketSolutionTemplate' => 'SolutionTemplate', 'TicketSolutionType' => 'SolutionType', 'TicketCategory' => 'ITILCategory');
    foreach ($itemtype_tables as $table) {
        foreach ($typestochange as $key => $val) {
            $query = "UPDATE `{$table}`\n                   SET `itemtype` = '{$val}'\n                   WHERE `itemtype` = '{$key}'";
            $DB->queryOrDie($query, "0.83 update itemtype of table {$table} for {$val}");
        }
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Add various fields'));
    $migration->addField("glpi_states", 'states_id', "integer");
    $migration->addField("glpi_states", 'completename', "text");
    $migration->addField("glpi_states", 'level', "integer");
    $migration->addField("glpi_states", 'ancestors_cache', "longtext");
    $migration->addField("glpi_states", 'sons_cache', "longtext");
    $migration->migrationOneTable('glpi_states');
    $migration->addKey("glpi_states", array('states_id', 'name'), 'unicity');
    regenerateTreeCompleteName("glpi_states");
    $migration->addField("glpi_knowbaseitemcategories", 'ancestors_cache', "longtext");
    $migration->addField("glpi_knowbaseitemcategories", 'sons_cache', "longtext");
    $migration->changeField("glpi_authldaps", 'group_condition', 'group_condition', "text");
    $migration->dropKey("glpi_groups", 'ldap_value');
    $migration->changeField("glpi_groups", 'ldap_value', 'ldap_value', "text");
    $migration->dropKey("glpi_groups", 'ldap_group_dn');
    $migration->changeField("glpi_groups", 'ldap_group_dn', 'ldap_group_dn', "text");
    $migration->addField("glpi_groups", 'groups_id', "integer");
    $migration->addField("glpi_groups", 'completename', "text");
    $migration->addField("glpi_groups", 'level', "integer");
    $migration->addField("glpi_groups", 'ancestors_cache', "longtext");
    $migration->addField("glpi_groups", 'sons_cache', "longtext");
    $migration->migrationOneTable('glpi_groups');
    $migration->addKey("glpi_groups", 'ldap_value', '', 'INDEX', 200);
    $migration->addKey("glpi_groups", 'ldap_group_dn', '', 'INDEX', 200);
    $migration->addKey("glpi_groups", 'groups_id');
    regenerateTreeCompleteName("glpi_groups");
    $migration->addField("glpi_entitydatas", 'notification_subject_tag', "string", array('after' => 'admin_reply_name'));
    $migration->addField("glpi_vlans", 'tag', "integer");
    $ADDTODISPLAYPREF['Vlan'] = array(11);
    $migration->addField("glpi_profiles", 'create_ticket_on_login', "bool");
    $migration->addField("glpi_reminders", 'begin_view_date', "datetime");
    $migration->addField("glpi_reminders", 'end_view_date', "datetime");
    // only to change latin1 to utf-8 if not done in update 0.68.3 to 0.71
    // because there is an index fulltext based on 2 fields (perhaps both are not in same encoding)
    $migration->changeField("glpi_knowbaseitems", 'answer', 'answer', "longtext");
    $migration->changeField("glpi_knowbaseitems", 'question', 'name', "text");
    $migration->addField("glpi_configs", "ajax_min_textsearch_load", "integer", array('after' => 'use_ajax'));
    $migration->addField("glpi_configs", "use_anonymous_followups", "bool", array('after' => 'use_anonymous_helpdesk'));
    $migration->addField("glpi_configs", "show_count_on_tabs", "bool", array('value' => '1'));
    $migration->addField("glpi_users", "show_count_on_tabs", "tinyint(1) NULL DEFAULT NULL");
    $migration->addField("glpi_configs", "refresh_ticket_list", "integer");
    $migration->addField("glpi_users", "refresh_ticket_list", "int(11) NULL DEFAULT NULL");
    $migration->addField("glpi_configs", "set_default_tech", "bool", array('value' => '1'));
    $migration->addField("glpi_users", "set_default_tech", "tinyint(1) NULL DEFAULT NULL");
    $migration->addField("glpi_reservations", "group", "integer");
    $migration->addKey("glpi_reservations", array('reservationitems_id', 'group'), "resagroup");
    /// Add document types
    $types = array('csv' => array('name' => 'Comma-Separated Values', 'icon' => 'csv-dist.png'), 'svg' => array('name' => 'Scalable Vector Graphics', 'icon' => 'svg-dist.png'));
    foreach ($types as $ext => $data) {
        $query = "SELECT *\n                FROM `glpi_documenttypes`\n                WHERE `ext` = '{$ext}'";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) == 0) {
                $query = "INSERT INTO `glpi_documenttypes`\n                             (`name`, `ext`, `icon`, `is_uploadable`, `date_mod`)\n                      VALUES ('" . $data['name'] . "', '{$ext}', '" . $data['icon'] . "', '1', NOW())";
                $DB->queryOrDie($query, "0.83 add document type {$ext}");
            }
        }
    }
    /// Update icons
    $types = array('c' => 'c-dist.png', 'h' => 'h-dist.png', 'swf' => 'swf-dist.png', 'pas' => 'pas-dist.png', 'wmv' => 'wmv-dist.png', 'zip' => 'zip-dist.png');
    foreach ($types as $ext => $icon) {
        $query = "SELECT `id`\n                FROM `glpi_documenttypes`\n                WHERE `ext` = '{$ext}'";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) == 1) {
                $query = "UPDATE `glpi_documenttypes`\n                      SET `icon` = '{$icon}', `date_mod` = NOW()\n                      WHERE `id` = '" . $DB->result($result, 0, 0) . "'";
                $DB->queryOrDie($query, "0.83 update icon for doc type {$ext}");
            }
        }
    }
    /// add missing indexes  for fields
    $migration->addKey("glpi_authldaps", "is_active");
    $migration->addKey("glpi_authmails", "is_active");
    $migration->addKey("glpi_ocsservers", "is_active");
    $migration->changeField("glpi_users", 'token', 'password_forget_token', "char(40) NULL DEFAULT NULL");
    $migration->changeField("glpi_users", 'tokendate', 'password_forget_token_date', "datetime");
    $migration->addField("glpi_users", "personal_token", 'string');
    $migration->addField("glpi_users", "personal_token_date", "datetime");
    $migration->addField("glpi_tickets", "is_deleted", "bool");
    $migration->addKey("glpi_tickets", "is_deleted");
    $migration->addField("glpi_contracts", "template_name", 'string');
    $migration->addField("glpi_contracts", "is_template", 'bool');
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Give consumable to groups'));
    if ($migration->addField("glpi_consumables", "itemtype", "VARCHAR(100) DEFAULT NULL", array("after" => "date_out", "update" => "'User'"))) {
        $migration->dropKey("glpi_consumables", 'users_id');
        $migration->changeField("glpi_consumables", 'users_id', 'items_id', 'integer');
        $migration->addKey("glpi_consumables", array('itemtype', 'items_id'), 'item');
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Several emails for users'));
    // Several email per users
    if (!TableExists('glpi_useremails')) {
        $query = "CREATE TABLE `glpi_useremails` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `users_id` int(11) NOT NULL DEFAULT '0',\n                  `is_default` TINYINT( 1 ) NOT NULL DEFAULT 0,\n                  `is_dynamic` TINYINT( 1 ) NOT NULL DEFAULT 0,\n                  `email` varchar( 255 ) NULL DEFAULT NULL,\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`users_id`,`email`),\n                  KEY `email` (`email`),\n                  KEY `is_default` (`is_default`),\n                  KEY `is_dynamic` (`is_dynamic`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_useremails");
    }
    // Manage migration : populate is_default=1
    // and is_dynamic depending of authldap config / authtype / auths_id
    if (FieldExists("glpi_users", 'email', false)) {
        $query = "SELECT *\n                FROM `glpi_users`\n                WHERE `email` <> '' AND `email` IS NOT NULL";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                while ($data = $DB->fetch_assoc($result)) {
                    $is_dynamic = 0;
                    $ldap_servers = array();
                    // manage is_dynamic :
                    if ($data['authtype'] == Auth::MAIL) {
                        $is_dynamic = 1;
                    } else {
                        if (Auth::isAlternateAuth($data["authtype"]) && $data['auths_id'] > 0 || $data['authtype'] == Auth::LDAP) {
                            if (!isset($ldap_servers[$data['auths_id']])) {
                                $ldap_servers[$data['auths_id']] = 0;
                                $ldap = new AuthLDAP();
                                if ($ldap->getFromDB($data['auths_id'])) {
                                    if (!empty($ldap->fields['email_field'])) {
                                        $ldap_servers[$data['auths_id']] = 1;
                                    }
                                }
                            }
                            $is_dynamic = $ldap_servers[$data['auths_id']];
                        }
                    }
                    $query2 = "INSERT INTO `glpi_useremails`\n                                 (`users_id`, `is_default`, `is_dynamic`, `email`)\n                          VALUES ('" . $data['id'] . "','1','{$is_dynamic}','" . addslashes($data['email']) . "')";
                    $DB->queryOrDie($query2, "0.83 move emails to  glpi_useremails");
                }
            }
        }
        // Drop email field from glpi_users
        $migration->dropField("glpi_users", 'email');
    }
    // check unicity for users email : unset rule and display warning
    foreach ($DB->request("glpi_fieldunicities", "`itemtype` = 'User' AND `fields` LIKE '%email%'") as $data) {
        $query = "UPDATE `glpi_fieldunicities`\n                SET `is_active` = '0'\n                WHERE `id` = '" . $data['id'] . "'";
        $DB->query($query);
        echo "<div class='red'><p>A unicity check use email for users. ";
        echo "Due to new feature permit several email per users, this rule have been disabled.</p></div>";
    }
    // multiple manager in groups
    $migration->changeField("glpi_authldaps", 'email_field', 'email1_field', 'string');
    $migration->addField("glpi_authldaps", 'email2_field', 'string');
    $migration->addField("glpi_authldaps", 'email3_field', 'string');
    $migration->addField("glpi_authldaps", 'email4_field', 'string');
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Multiple managers for groups'));
    /// migration : multiple group managers
    $migration->addField("glpi_groups_users", "is_manager", 'bool');
    $migration->addKey("glpi_groups_users", "is_manager");
    $migration->migrationOneTable('glpi_groups_users');
    if (FieldExists("glpi_groups", 'users_id', false)) {
        $query = "SELECT *\n                FROM `glpi_groups`\n                WHERE `users_id` > 0";
        $user = new User();
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                while ($data = $DB->fetch_assoc($result)) {
                    if ($user->getFromDB($data['users_id'])) {
                        $query = "SELECT `id`\n                            FROM `glpi_groups_users`\n                            WHERE `groups_id` = '" . $data['id'] . "'\n                                 AND `users_id` = '" . $data['users_id'] . "'";
                        if ($result2 = $DB->query($query)) {
                            // add manager to groups_users setting if not present
                            if ($DB->numrows($result2) == 0) {
                                $query2 = "INSERT INTO`glpi_groups_users`\n                                          (`users_id`, `groups_id`, `is_manager`)\n                                   VALUES ('" . $data['users_id'] . "' ,'" . $data['id'] . "', '1')";
                                $DB->queryOrDie($query2, "0.83 insert manager of groups");
                            } else {
                                // Update user as manager if presnet in groups_users
                                $query2 = "UPDATE `glpi_groups_users`\n                                   SET `is_manager` = '1'\n                                   WHERE `groups_id` = '" . $data['id'] . "'\n                                         AND `users_id` = '" . $data['users_id'] . "'";
                                $DB->queryOrDie($query2, "0.83 set manager of groups");
                            }
                        }
                    }
                }
            }
        }
        // Drop field glpi_groups
        $migration->dropField("glpi_groups", 'users_id');
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Add entities information on document links'));
    if ($migration->addField("glpi_documents_items", "entities_id", "integer")) {
        $migration->addField("glpi_documents_items", "is_recursive", "bool");
        $migration->migrationOneTable('glpi_documents_items');
        $query_doc_i = "UPDATE `glpi_documents_items` as `doc_i`\n                      INNER JOIN `glpi_documents` as `doc`\n                        ON  `doc`.`id` = `doc_i`.`documents_id`\n                      SET `doc_i`.`entities_id` = `doc`.`entities_id`,\n                         `doc_i`.`is_recursive` = `doc`.`is_recursive`";
        $DB->queryOrDie($query_doc_i, "0.83 update entities_id and is_recursive in glpi_documents_items");
        /// create index for search count on tab
        $migration->dropKey("glpi_documents_items", "item");
        $migration->migrationOneTable('glpi_documents_items');
        $migration->addKey("glpi_documents_items", array('itemtype', 'items_id', 'entities_id', 'is_recursive'), 'item');
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'RuleTicket'));
    $changes['RuleTicket'] = array('ticketcategories_id' => 'itilcategories_id');
    $DB->query("SET SESSION group_concat_max_len = 4194304;");
    foreach ($changes as $ruletype => $tab) {
        // Get rules
        $query = "SELECT GROUP_CONCAT(`id`)\n                FROM `glpi_rules`\n                WHERE `sub_type` = '" . $ruletype . "'\n                GROUP BY `sub_type`";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                // Get rule string
                $rules = $DB->result($result, 0, 0);
                // Update actions
                foreach ($tab as $old => $new) {
                    $query = "UPDATE `glpi_ruleactions`\n                         SET `field` = '{$new}'\n                         WHERE `field` = '{$old}'\n                               AND `rules_id` IN ({$rules})";
                    $DB->queryOrDie($query, "0.83 update datas for rules actions");
                }
                // Update criteria
                foreach ($tab as $old => $new) {
                    $query = "UPDATE `glpi_rulecriterias`\n                         SET `criteria` = '{$new}'\n                         WHERE `criteria` = '{$old}'\n                               AND `rules_id` IN ({$rules})";
                    $DB->queryOrDie($query, "0.83 update datas for rules criteria");
                }
            }
        }
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'Ticket templates'));
    $default_ticket_template = 0;
    if (!TableExists('glpi_tickettemplates')) {
        $query = "CREATE TABLE `glpi_tickettemplates` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `name` varchar( 255 ) NULL DEFAULT NULL,\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n                  `comment` TEXT DEFAULT NULL,\n                  PRIMARY KEY (`id`),\n                  KEY `name` (`name`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_tickettemplates");
        $query = "INSERT INTO `glpi_tickettemplates`\n                       (`name`, `is_recursive`)\n                VALUES ('Default', 1)";
        $DB->queryOrDie($query, "0.83 add default ticket template");
        $default_ticket_template = $DB->insert_id();
    }
    $migration->addField('glpi_itilcategories', 'tickettemplates_id_incident', "integer");
    $migration->addKey('glpi_itilcategories', 'tickettemplates_id_incident');
    $migration->addField('glpi_itilcategories', 'tickettemplates_id_demand', "integer");
    $migration->addKey('glpi_itilcategories', 'tickettemplates_id_demand');
    $migration->addField('glpi_itilcategories', 'is_incident', "integer", array('value' => 1));
    $migration->addKey('glpi_itilcategories', 'is_incident');
    $migration->addField('glpi_itilcategories', 'is_request', "integer", array('value' => 1));
    $migration->addKey('glpi_itilcategories', 'is_request');
    $migration->addField('glpi_itilcategories', 'is_problem', "integer", array('value' => 1));
    $migration->addKey('glpi_itilcategories', 'is_problem');
    if (!TableExists('glpi_tickettemplatehiddenfields')) {
        $query = "CREATE TABLE `glpi_tickettemplatehiddenfields` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `tickettemplates_id` int(11) NOT NULL DEFAULT '0',\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n                  `num` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`),\n                  KEY `unicity` (`tickettemplates_id`,`num`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_tickettemplatehiddenfields");
    }
    if (!TableExists('glpi_tickettemplatepredefinedfields')) {
        $query = "CREATE TABLE `glpi_tickettemplatepredefinedfields` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `tickettemplates_id` int(11) NOT NULL DEFAULT '0',\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n                  `num` int(11) NOT NULL DEFAULT '0',\n                  `value` TEXT DEFAULT NULL,\n                  PRIMARY KEY (`id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`),\n                  KEY `unicity` (`tickettemplates_id`,`num`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_tickettemplatepredefinedfields");
    }
    if (!TableExists('glpi_tickettemplatemandatoryfields')) {
        $query = "CREATE TABLE `glpi_tickettemplatemandatoryfields` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `tickettemplates_id` int(11) NOT NULL DEFAULT '0',\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n                  `num` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`),\n                  KEY `unicity` (`tickettemplates_id`,`num`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_tickettemplatemandatoryfields");
        /// Add mandatory fields to default template
        if ($default_ticket_template > 0) {
            foreach ($DB->request('glpi_configs') as $data) {
                if (isset($data['is_ticket_title_mandatory']) && $data['is_ticket_title_mandatory']) {
                    $query = "INSERT INTO `glpi_tickettemplatemandatoryfields`\n                                (`tickettemplates_id`, `num`)\n                         VALUES ('{$default_ticket_template}', 1)";
                    $DB->queryOrDie($query, "0.83 add mandatory field for default ticket template");
                }
                if (isset($data['is_ticket_content_mandatory']) && $data['is_ticket_content_mandatory']) {
                    $query = "INSERT INTO `glpi_tickettemplatemandatoryfields`\n                                (`tickettemplates_id`, `num`)\n                         VALUES ('{$default_ticket_template}', 21)";
                    $DB->queryOrDie($query, "0.83 add mandatory field for default ticket template");
                }
                if (isset($data['is_ticket_category_mandatory']) && $data['is_ticket_category_mandatory']) {
                    $query = "INSERT INTO `glpi_tickettemplatemandatoryfields`\n                                (`tickettemplates_id`, `num`)\n                         VALUES ('{$default_ticket_template}', 7)";
                    $DB->queryOrDie($query, "0.83 add mandatory field for default ticket template");
                }
            }
            // Update itil categories
            $migration->migrationOneTable('glpi_itilcategories');
            $query = "UPDATE `glpi_itilcategories`\n                   SET `tickettemplates_id_incident` = '{$default_ticket_template}',\n                       `tickettemplates_id_demand` = '{$default_ticket_template}'";
            $DB->queryOrDie($query, "0.83 update default templates used by itil categories");
        }
    }
    // Drop global mandatory config
    $migration->dropField('glpi_configs', 'is_ticket_title_mandatory');
    $migration->dropField('glpi_configs', 'is_ticket_content_mandatory');
    $migration->dropField('glpi_configs', 'is_ticket_category_mandatory');
    $migration->addField('glpi_profiles', 'tickettemplate', "char", array('update' => '`sla`'));
    $migration->addField("glpi_entitydatas", "tickettemplates_id", 'integer', array('value' => '-2'));
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'Tech Groups on items'));
    // Group of technicians in charge of Helpdesk items
    $migration->addField('glpi_computers', 'groups_id_tech', "integer", array('after' => "users_id_tech"));
    $migration->addKey('glpi_computers', 'groups_id_tech');
    $migration->addField('glpi_monitors', 'groups_id_tech', "integer", array('after' => "users_id_tech"));
    $migration->addKey('glpi_monitors', 'groups_id_tech');
    $migration->addField('glpi_networkequipments', 'groups_id_tech', "integer", array('after' => "users_id_tech"));
    $migration->addKey('glpi_networkequipments', 'groups_id_tech');
    $migration->addField('glpi_peripherals', 'groups_id_tech', "integer", array('after' => "users_id_tech"));
    $migration->addKey('glpi_peripherals', 'groups_id_tech');
    $migration->addField('glpi_phones', 'groups_id_tech', "integer", array('after' => "users_id_tech"));
    $migration->addKey('glpi_phones', 'groups_id_tech');
    $migration->addField('glpi_printers', 'groups_id_tech', "integer", array('after' => "users_id_tech"));
    $migration->addKey('glpi_printers', 'groups_id_tech');
    $migration->addField('glpi_softwares', 'groups_id_tech', "integer", array('after' => "users_id_tech"));
    $migration->addKey('glpi_softwares', 'groups_id_tech');
    $migration->addField('glpi_cartridgeitems', 'groups_id_tech', "integer", array('after' => "users_id_tech"));
    $migration->addKey('glpi_cartridgeitems', 'groups_id_tech');
    $migration->addField('glpi_consumableitems', 'groups_id_tech', "integer", array('after' => "users_id_tech"));
    $migration->addKey('glpi_consumableitems', 'groups_id_tech');
    $migration->addField('glpi_printers', 'last_pages_counter', 'integer', array('after' => 'init_pages_counter'));
    $migration->addKey('glpi_printers', 'last_pages_counter');
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'various cleaning DB'));
    // Clean ticket satisfactions
    $query = "DELETE\n             FROM `glpi_ticketsatisfactions`\n             WHERE `glpi_ticketsatisfactions`.`tickets_id` NOT IN (SELECT `glpi_tickets`.`id`\n                                                                   FROM `glpi_tickets`)";
    $DB->queryOrDie($query, "0.83 clean glpi_ticketsatisfactions");
    // Clean unused slalevels
    $query = "DELETE\n             FROM `glpi_slalevels_tickets`\n             WHERE (`glpi_slalevels_tickets`.`tickets_id`, `glpi_slalevels_tickets`.`slalevels_id`)\n                  NOT IN (SELECT `glpi_tickets`.`id`, `glpi_tickets`.`slalevels_id`\n                          FROM `glpi_tickets`)";
    $DB->queryOrDie($query, "0.83 clean glpi_slalevels_tickets");
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'recurrent tickets'));
    if (!TableExists('glpi_ticketrecurrents')) {
        $query = "CREATE TABLE `glpi_ticketrecurrents` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `name` varchar( 255 ) NULL DEFAULT NULL,\n                  `comment` TEXT DEFAULT NULL,\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n                  `is_active` TINYINT( 1 ) NOT NULL DEFAULT 0,\n                  `tickettemplates_id` int(11) NOT NULL DEFAULT '0',\n                  `begin_date` datetime DEFAULT NULL,\n                  `periodicity` int(11) NOT NULL DEFAULT '0',\n                  `create_before` int(11) NOT NULL DEFAULT '0',\n                  `next_creation_date` datetime DEFAULT NULL,\n                  PRIMARY KEY (`id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`),\n                  KEY `is_active` (`is_active`),\n                  KEY `tickettemplates_id` (`tickettemplates_id`),\n                  KEY `next_creation_date` (`next_creation_date`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_ticketrecurrents");
        $ADDTODISPLAYPREF['TicketRecurrent'] = array(11, 12, 13, 15, 14);
    }
    if (!countElementsInTable('glpi_crontasks', "`itemtype`='TicketRecurrent' AND `name`='ticketrecurrent'")) {
        $query = "INSERT INTO `glpi_crontasks`\n                       (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n                        `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n                VALUES ('TicketRecurrent', 'ticketrecurrent', 3600, NULL, 1, 1, 3,\n                        0, 24, 30, NULL, NULL, NULL)";
        $DB->queryOrDie($query, "0.83 populate glpi_crontasks for ticketrecurrent");
    }
    $migration->addField('glpi_profiles', 'ticketrecurrent', "char", array('update' => '`sla`'));
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'various fields add'));
    // Ticket delegation
    $migration->addField('glpi_groups_users', 'is_userdelegate', 'bool');
    $migration->addKey('glpi_groups_users', 'is_userdelegate');
    //Software dictionary update
    $migration->addField("glpi_rulecachesoftwares", "entities_id", "string");
    $migration->addField("glpi_rulecachesoftwares", "new_entities_id", "string");
    $migration->addField("glpi_entitydatas", "entities_id_software", 'integer', array('value' => '-2'));
    // Groups perm
    $migration->addField('glpi_groups', 'is_requester', 'bool', array('value' => '1'));
    $migration->addField('glpi_groups', 'is_assign', 'bool', array('value' => '1'));
    $migration->addField('glpi_groups', 'is_notify', 'bool', array('value' => '1'));
    $migration->addField('glpi_groups', 'is_itemgroup', 'bool', array('value' => '1'));
    $migration->addField('glpi_groups', 'is_usergroup', 'bool', array('value' => '1'));
    $migration->addKey('glpi_groups', 'is_requester');
    $migration->addKey('glpi_groups', 'is_assign');
    $migration->addKey('glpi_groups', 'is_notify');
    $migration->addKey('glpi_groups', 'is_itemgroup');
    $migration->addKey('glpi_groups', 'is_usergroup');
    // Ticket solution by entity
    $migration->addfield('glpi_solutiontypes', 'entities_id', 'integer');
    $migration->addfield('glpi_solutiontypes', 'is_recursive', 'bool', array('value' => '1'));
    $migration->addKey('glpi_solutiontypes', 'entities_id');
    $migration->addKey('glpi_solutiontypes', 'is_recursive');
    // Fix solution template index
    $migration->dropKey('glpi_solutiontemplates', 'unicity');
    $migration->addKey('glpi_solutiontemplates', 'entities_id');
    // New index for count on tab
    $migration->addKey('glpi_ruleactions', array('field', 'value'), '', 'INDEX', 50);
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'Create new default profiles'));
    $profiles = array('hotliner' => array('name' => 'Hotliner', 'interface' => 'central', 'user' => 'r', 'import_externalauth_users' => 'w', 'create_ticket' => '1', 'assign_ticket' => '1', 'global_add_followups' => '1', 'add_followups' => '1', 'update_ticket' => '1', 'observe_ticket' => '1', 'show_all_ticket' => '1', 'show_full_ticket' => '1', 'show_all_problem' => '1', 'show_planning' => '1', 'statistic' => '1', 'tickettemplate' => 'r', 'password_update' => '1', 'helpdesk_hardware' => '3', 'helpdesk_item_type' => addslashes('["Computer", "Monitor", "NetworkEquipment",' . '"Peripheral", "Phone", "Printer",' . '"Software"]'), 'create_validation' => '1', 'update_own_followups' => '1', 'create_ticket_on_login' => '1'), 'technician' => array('name' => 'Technician', 'interface' => 'central', 'password_update' => '1', 'computer' => 'w', 'monitor' => 'w', 'software' => 'w', 'networking' => 'w', 'printer' => 'w', 'peripheral' => 'w', 'cartridge' => 'w', 'consumable' => 'w', 'phone' => 'w', 'notes' => 'w', 'document' => 'w', 'knowbase' => 'w', 'faq' => 'w', 'reservation_helpdesk' => '1', 'reservation_central' => 'w', 'reports' => 'r', 'view_ocsng' => 'r', 'sync_ocsng' => 'w', 'user' => 'w', 'group' => 'r', 'entity' => 'r', 'transfer' => 'r', 'reminder_public' => 'w', 'create_ticket' => '1', 'add_followups' => '1', 'global_add_followups' => '1', 'global_add_tasks' => '1', 'update_ticket' => '1', 'own_ticket' => '1', 'show_all_ticket' => '1', 'show_assign_ticket' => '1', 'show_full_ticket' => '1', 'observe_ticket' => '1', 'update_followups' => '1', 'update_tasks' => '1', 'show_planning' => '1', 'statistic' => '1', 'helpdesk_hardware' => '3', 'helpdesk_item_type' => addslashes('["Computer", "Monitor", "NetworkEquipment",' . '"Peripheral", "Phone", "Printer",' . '"Software"]'), 'import_externalauth_users' => 'w', 'create_validation' => '1', 'sla' => 'r', 'update_own_followups' => '1', 'show_my_problem' => '1', 'show_all_problem' => '1', 'tickettemplate' => 'r', 'ticketrecurrent' => 'r'), 'supervisor' => array('name' => 'Supervisor', 'interface' => 'central', 'password_update' => '1', 'computer' => 'w', 'monitor' => 'w', 'software' => 'w', 'networking' => 'w', 'printer' => 'w', 'peripheral' => 'w', 'cartridge' => 'w', 'consumable' => 'w', 'phone' => 'w', 'notes' => 'w', 'document' => 'w', 'knowbase' => 'w', 'faq' => 'w', 'reservation_helpdesk' => '1', 'reservation_central' => 'w', 'reports' => 'r', 'view_ocsng' => 'r', 'sync_ocsng' => 'w', 'entity_dropdown' => 'w', 'rule_ticket' => 'r', 'entity_rule_ticket' => 'w', 'user' => 'w', 'group' => 'r', 'entity' => 'r', 'transfer' => 'r', 'logs' => 'r', 'reminder_public' => 'w', 'create_ticket' => '1', 'delete_ticket' => '1', 'add_followups' => '1', 'global_add_followups' => '1', 'global_add_tasks' => '1', 'update_ticket' => '1', 'update_priority' => '1', 'own_ticket' => '1', 'steal_ticket' => '1', 'assign_ticket' => '1', 'show_all_ticket' => '1', 'show_assign_ticket' => '1', 'show_full_ticket' => '1', 'observe_ticket' => '1', 'update_followups' => '1', 'update_tasks' => '1', 'show_planning' => '1', 'show_all_planning' => '1', 'statistic' => '1', 'helpdesk_hardware' => '3', 'helpdesk_item_type' => addslashes('["Computer", "Monitor", "NetworkEquipment",' . '"Peripheral", "Phone", "Printer",' . '"Software"]'), 'import_externalauth_users' => 'w', 'rule_mailcollector' => 'w', 'validate_ticket' => '1', 'create_validation' => '1', 'calendar' => 'w', 'sla' => 'w', 'update_own_followups' => '1', 'delete_followups' => '1', 'show_my_problem' => '1', 'show_all_problem' => '1', 'edit_all_problem' => '1', 'tickettemplate' => 'w', 'ticketrecurrent' => 'w'));
    foreach ($profiles as $profile => $data) {
        $query = "INSERT INTO `glpi_profiles`\n                         (`" . implode("`, `", array_keys($data)) . "`)\n                  VALUES ('" . implode("', '", $data) . "')";
        $DB->queryOrDie($query, "0.83 create new profile {$profile}");
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'Reminder visibility'));
    if (!TableExists('glpi_reminders_users')) {
        $query = "CREATE TABLE `glpi_reminders_users` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `reminders_id` int(11) NOT NULL DEFAULT '0',\n                  `users_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  KEY `reminders_id` (`reminders_id`),\n                  KEY `users_id` (`users_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_reminders_users");
    }
    if (!TableExists('glpi_groups_reminders')) {
        $query = "CREATE TABLE `glpi_groups_reminders` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `reminders_id` int(11) NOT NULL DEFAULT '0',\n                  `groups_id` int(11) NOT NULL DEFAULT '0',\n                  `entities_id` int(11) NOT NULL DEFAULT '-1',\n                  `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n                  PRIMARY KEY (`id`),\n                  KEY `reminders_id` (`reminders_id`),\n                  KEY `groups_id` (`groups_id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`)\n\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_groups_reminders");
    }
    if (!TableExists('glpi_profiles_reminders')) {
        $query = "CREATE TABLE `glpi_profiles_reminders` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `reminders_id` int(11) NOT NULL DEFAULT '0',\n                  `profiles_id` int(11) NOT NULL DEFAULT '0',\n                  `entities_id` int(11) NOT NULL DEFAULT '-1',\n                  `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n                  PRIMARY KEY (`id`),\n                  KEY `reminders_id` (`reminders_id`),\n                  KEY `profiles_id` (`profiles_id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_profiles_reminders");
    }
    if (!TableExists('glpi_entities_reminders')) {
        $query = "CREATE TABLE `glpi_entities_reminders` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `reminders_id` int(11) NOT NULL DEFAULT '0',\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n                  PRIMARY KEY (`id`),\n                  KEY `reminders_id` (`reminders_id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_entities_reminders");
    }
    /// Migrate datas for is_helpdesk_visible : add all helpdesk profiles / drop field is_helpdesk_visible
    if (FieldExists("glpi_reminders", 'is_helpdesk_visible', false)) {
        $query = "SELECT `id`\n                FROM `glpi_reminders`\n                WHERE `is_helpdesk_visible` = 1";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                // Grab helpdesk profiles
                $helpdesk_profiles = array();
                foreach ($DB->request("glpi_profiles", "`interface` = 'helpdesk' AND `reminder_public` = 'r'") as $data2) {
                    $helpdesk_profiles[$data2['id']] = $data2['id'];
                }
                if (count($helpdesk_profiles)) {
                    while ($data = $DB->fetch_assoc($result)) {
                        foreach ($helpdesk_profiles as $pid) {
                            $query = "INSERT INTO `glpi_profiles_reminders`\n                                      (`reminders_id`, `profiles_id`)\n                               VALUES ('" . $data['id'] . "', '{$pid}');";
                            $DB->queryOrDie($query, "0.83 migrate data for is_helpdesk_visible drop on glpi_reminders");
                        }
                    }
                }
            }
        }
        $migration->dropField("glpi_reminders", 'is_helpdesk_visible');
    }
    // Migrate datas for entities + drop fields : is_private / entities_id / is_recursive
    if (FieldExists("glpi_reminders", 'is_private', false)) {
        $query = "SELECT *\n                FROM `glpi_reminders`\n                WHERE `is_private` = 0";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                while ($data = $DB->fetch_assoc($result)) {
                    $query = "INSERT INTO `glpi_entities_reminders`\n                                (`reminders_id`, `entities_id`, `is_recursive`)\n                         VALUES ('" . $data['id'] . "', '" . $data['entities_id'] . "',\n                                 '" . $data['is_recursive'] . "');";
                    $DB->queryOrDie($query, "0.83 migrate data for public reminders");
                }
            }
        }
        $migration->dropField("glpi_reminders", 'is_private');
        $migration->dropField("glpi_reminders", 'entities_id');
        $migration->dropField("glpi_reminders", 'is_recursive');
    }
    $ADDTODISPLAYPREF['Reminder'] = array(2, 3, 4, 5, 6, 7);
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'KnowbaseItem visibility'));
    if (!TableExists('glpi_knowbaseitems_users')) {
        $query = "CREATE TABLE `glpi_knowbaseitems_users` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `knowbaseitems_id` int(11) NOT NULL DEFAULT '0',\n                  `users_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  KEY `knowbaseitems_id` (`knowbaseitems_id`),\n                  KEY `users_id` (`users_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_knowbaseitems_users");
    }
    if (!TableExists('glpi_groups_knowbaseitems')) {
        $query = "CREATE TABLE `glpi_groups_knowbaseitems` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `knowbaseitems_id` int(11) NOT NULL DEFAULT '0',\n                  `groups_id` int(11) NOT NULL DEFAULT '0',\n                  `entities_id` int(11) NOT NULL DEFAULT '-1',\n                  `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n                  PRIMARY KEY (`id`),\n                  KEY `knowbaseitems_id` (`knowbaseitems_id`),\n                  KEY `groups_id` (`groups_id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`)\n\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_groups_knowbaseitems");
    }
    if (!TableExists('glpi_knowbaseitems_profiles')) {
        $query = "CREATE TABLE `glpi_knowbaseitems_profiles` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `knowbaseitems_id` int(11) NOT NULL DEFAULT '0',\n                  `profiles_id` int(11) NOT NULL DEFAULT '0',\n                  `entities_id` int(11) NOT NULL DEFAULT '-1',\n                  `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n                  PRIMARY KEY (`id`),\n                  KEY `knowbaseitems_id` (`knowbaseitems_id`),\n                  KEY `profiles_id` (`profiles_id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_knowbaseitems_profiles");
    }
    if (!TableExists('glpi_entities_knowbaseitems')) {
        $query = "CREATE TABLE `glpi_entities_knowbaseitems` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `knowbaseitems_id` int(11) NOT NULL DEFAULT '0',\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n                  PRIMARY KEY (`id`),\n                  KEY `knowbaseitems_id` (`knowbaseitems_id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_entities_knowbaseitems");
    }
    /// Migrate datas for entities_id / is_recursive
    if (FieldExists("glpi_knowbaseitems", 'entities_id', false)) {
        $query = "SELECT *\n                FROM `glpi_knowbaseitems`";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                while ($data = $DB->fetch_assoc($result)) {
                    $query = "INSERT INTO `glpi_entities_knowbaseitems`\n                                (`knowbaseitems_id`, `entities_id`, `is_recursive`)\n                         VALUES ('" . $data['id'] . "', '" . $data['entities_id'] . "',\n                                 '" . $data['is_recursive'] . "');";
                    $DB->queryOrDie($query, "0.83 migrate data for entities on glpi_entities_knowbaseitems");
                }
            }
        }
        $migration->dropField("glpi_knowbaseitems", 'entities_id');
        $migration->dropField("glpi_knowbaseitems", 'is_recursive');
    }
    // Plugins
    $migration->addField('glpi_plugins', 'license', 'string');
    $migration->migrationOneTable('glpi_entitydatas');
    $restore_root_entity_value = false;
    // create root entity if not exist with old default values
    if (countElementsInTable('glpi_entitydatas', 'entities_id=0') == 0) {
        $query = "INSERT INTO `glpi_entitydatas`\n                       (`entities_id`, `entities_id_software`,\n                        `autofill_order_date`, `autofill_delivery_date`, `autofill_buy_date`,\n                        `autofill_use_date`, `autofill_warranty_date`,\n                        `inquest_config`, `inquest_rate`, `inquest_delay`,\n                        `tickettype`, `calendars_id`, `tickettemplates_id`,\n                        `autoclose_delay`, `auto_assign_mode`,\n                        `cartridges_alert_repeat`, `consumables_alert_repeat`,\n                        `use_licenses_alert`, `use_infocoms_alert`, `notclosed_delay`,\n                        `use_contracts_alert`, `use_reservations_alert`)\n                VALUES (0, -10,\n                        0, 0, 0,\n                        0, 0,\n                        1, 0, 0,\n                        1, 0, '{$default_ticket_template}',\n                        -1, -1,\n                        -1, -1,\n                        -1, -1, -1,\n                        -1, -1)";
        // -1 to keep config value - see 1647
        $DB->queryOrDie($query, "0.83 add entities_id 0 in glpi_entitydatas");
        $restore_root_entity_value = true;
    } else {
        $query = "UPDATE `glpi_entitydatas`\n                SET `tickettemplates_id` = '{$default_ticket_template}'\n                WHERE `entities_id` = 0\n                      AND `tickettemplates_id` = -2";
        $DB->queryOrDie($query, "0.83 update tickettemplates_id for root entity in glpi_entitydatas");
        $query = "UPDATE `glpi_entitydatas`\n                SET `entities_id_software` = -10\n                WHERE `entities_id` = 0\n                      AND `entities_id_software` = -2";
        $DB->queryOrDie($query, "0.83 update entities_id_software for root entity in glpi_entitydatas");
        // For root entity already exists in entitydatas in 0.78
        $query = "UPDATE `glpi_entitydatas`\n                SET `tickettype` = 1\n                WHERE `entities_id` = 0\n                      AND `tickettype` = 0";
        $DB->queryOrDie($query, "0.83 update tickettype for root entity in glpi_entitydatas");
        $query = "UPDATE `glpi_entitydatas`\n                SET `inquest_config` = 1\n                WHERE `entities_id` = 0\n                      AND `inquest_config` = 0";
        $DB->queryOrDie($query, "0.83 update inquest_config for root entity in glpi_entitydatas ");
        $query = "UPDATE `glpi_entitydatas`\n                SET `inquest_rate` = 0\n                WHERE `entities_id` = 0\n                      AND `inquest_rate` = '-1'";
        $DB->queryOrDie($query, "0.83 update inquest_rate for root entity in glpi_entitydatas ");
        $query = "UPDATE `glpi_entitydatas`\n                SET `inquest_delay` = 0\n                WHERE `entities_id` = 0\n                      AND `inquest_delay` = '-1'";
        $DB->queryOrDie($query, "0.83 update inquest_delay for root entity in glpi_entitydatas ");
    }
    // migration to new values for inherit parent (0 => -2)
    $field0 = array('calendars_id', 'tickettype', 'inquest_config');
    foreach ($field0 as $field_0) {
        if (FieldExists("glpi_entitydatas", $field_0, false)) {
            $query = "UPDATE `glpi_entitydatas`\n                   SET `{$field_0}` = '-2'\n                   WHERE `{$field_0}` = '0'\n                         AND `entities_id` > 0";
            $DB->queryOrDie($query, "0.83 new value for inherit parent 0 in glpi_entitydatas");
        }
    }
    // new default value
    $migration->changeField("glpi_entitydatas", "calendars_id", "calendars_id", "int(11) NOT NULL DEFAULT '-2'");
    $migration->changeField("glpi_entitydatas", "tickettype", "tickettype", "int(11) NOT NULL DEFAULT '-2'");
    $migration->changeField("glpi_entitydatas", "inquest_config", "inquest_config", "int(11) NOT NULL DEFAULT '-2'");
    $migration->changeField("glpi_entitydatas", "inquest_rate", "inquest_rate", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField("glpi_entitydatas", "inquest_delay", "inquest_delay", "int(11) NOT NULL DEFAULT '-10'");
    // migration to new values for inherit parent (-1 => -2)
    $fieldparent = array('autofill_buy_date', 'autofill_delivery_date', 'autofill_warranty_date', 'autofill_order_date', 'autofill_use_date');
    foreach ($fieldparent as $field_parent) {
        if (FieldExists("glpi_entitydatas", $field_parent, false)) {
            $query = "UPDATE `glpi_entitydatas`\n                   SET `{$field_parent}` = '-2'\n                   WHERE `{$field_parent}` = '-1'";
            $DB->queryOrDie($query, "0.83 new value for inherit parent -1 in glpi_entitydatas");
        }
    }
    // new default value
    $migration->changeField("glpi_entitydatas", "autofill_buy_date", "autofill_buy_date", 'string', array('value' => '-2'));
    $migration->changeField("glpi_entitydatas", "autofill_delivery_date", "autofill_delivery_date", 'string', array('value' => '-2'));
    $migration->changeField("glpi_entitydatas", "autofill_warranty_date", "autofill_warranty_date", 'string', array('value' => '-2'));
    $migration->changeField("glpi_entitydatas", "autofill_order_date", "autofill_order_date", 'string', array('value' => '-2'));
    $migration->changeField("glpi_entitydatas", "autofill_use_date", "autofill_use_date", 'string', array('value' => '-2'));
    // migration to new values for inherit config
    $fieldconfig = array('auto_assign_mode', 'autoclose_delay', 'cartridges_alert_repeat', 'consumables_alert_repeat', 'notclosed_delay', 'use_contracts_alert', 'use_infocoms_alert', 'use_licenses_alert', 'use_reservations_alert');
    $query = "SELECT *\n             FROM `glpi_configs`";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) > 0) {
            if ($data = $DB->fetch_assoc($result)) {
                foreach ($fieldconfig as $field_config) {
                    if (FieldExists("glpi_entitydatas", $field_config, false) && FieldExists("glpi_configs", $field_config, false)) {
                        // value of general config
                        $query = "UPDATE `glpi_entitydatas`\n                            SET `{$field_config}` = '" . $data[$field_config] . "'\n                            WHERE `{$field_config}` = -1";
                        $DB->queryOrDie($query, "0.83 migrate data from config to glpi_entitydatas");
                        $migration->changeField("glpi_entitydatas", "{$field_config}", "{$field_config}", "int(11) NOT NULL DEFAULT '-2'");
                        $migration->dropField("glpi_configs", $field_config);
                    }
                }
                if (FieldExists("glpi_entitydatas", "auto_assign_mode", false)) {
                    // new value for never
                    $query = "UPDATE `glpi_entitydatas`\n                         SET `auto_assign_mode` = -10\n                         WHERE `auto_assign_mode` = 0";
                    $DB->queryOrDie($query, "0.83 change value Never in glpi_entitydatas for auto_assign_mode");
                }
            }
        }
    }
    // value of config in each entity
    $fieldconfig = array('default_contract_alert', 'default_infocom_alert', 'default_alarm_threshold');
    $query = "SELECT *\n             FROM `glpi_configs`";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) > 0) {
            if ($data = $DB->fetch_assoc($result)) {
                foreach ($fieldconfig as $field_config) {
                    if (FieldExists("glpi_configs", $field_config, false) && !FieldExists("glpi_entitydatas", $field_config, false)) {
                        // add config fields in entitydatas
                        $migration->addField("glpi_entitydatas", $field_config, 'integer', array('update' => $data[$field_config], 'value' => $field_config == "default_alarm_threshold" ? 10 : 0));
                        $migration->dropField("glpi_configs", $field_config);
                    }
                }
            }
        }
    }
    if ($restore_root_entity_value) {
        $query = "UPDATE `glpi_entitydatas`\n                SET `calendars_id` = 0\n                WHERE `entities_id` = 0;";
        $DB->queryOrDie($query, "0.83 restore root entity default value");
    }
    $migration->addKey('glpi_computervirtualmachines', 'computers_id');
    $migration->addKey('glpi_computervirtualmachines', 'entities_id');
    $migration->addKey('glpi_computervirtualmachines', 'name');
    $migration->addKey('glpi_computervirtualmachines', 'virtualmachinestates_id');
    $migration->addKey('glpi_computervirtualmachines', 'virtualmachinesystems_id');
    $migration->addKey('glpi_computervirtualmachines', 'vcpu');
    $migration->addKey('glpi_computervirtualmachines', 'ram');
    //   $ADDTODISPLAYPREF['KnowbaseItem'] = array(2,3,4,5,6,7);
    $renametables = array('TicketSolutionType' => 'SolutionType', 'TicketSolutionTemplate' => 'SolutionTemplate', 'TicketCategory' => 'ITILCategory');
    $itemtype_tables = array("glpi_bookmarks" => 'itemtype', "glpi_bookmarks_users" => 'itemtype', "glpi_displaypreferences" => 'itemtype', "glpi_logs" => 'itemtype', "glpi_events" => 'type');
    foreach ($itemtype_tables as $table => $field) {
        foreach ($renametables as $key => $val) {
            $query = "UPDATE `{$table}`\n                      SET `{$field}` = '" . $val . "'\n                      WHERE `{$field}` = '" . $key . "'";
            $DB->queryOrDie($query, "0.83 update itemtype of table {$table} for {$val}");
        }
    }
    // ************ Keep it at the end **************
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_displaypreferences'));
    // Change is_recursive index
    $query = "UPDATE `glpi_displaypreferences`\n              SET `num` = '86'\n              WHERE `itemtype` = 'Group'\n                    AND `num` = '6'";
    $DB->query($query);
    foreach ($ADDTODISPLAYPREF as $type => $tab) {
        $query = "SELECT DISTINCT `users_id`\n                FROM `glpi_displaypreferences`\n                WHERE `itemtype` = '{$type}'";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                while ($data = $DB->fetch_assoc($result)) {
                    $query = "SELECT MAX(`rank`)\n                         FROM `glpi_displaypreferences`\n                         WHERE `users_id` = '" . $data['users_id'] . "'\n                               AND `itemtype` = '{$type}'";
                    $result = $DB->query($query);
                    $rank = $DB->result($result, 0, 0);
                    $rank++;
                    foreach ($tab as $newval) {
                        $query = "SELECT *\n                            FROM `glpi_displaypreferences`\n                            WHERE `users_id` = '" . $data['users_id'] . "'\n                                  AND `num` = '{$newval}'\n                                  AND `itemtype` = '{$type}'";
                        if ($result2 = $DB->query($query)) {
                            if ($DB->numrows($result2) == 0) {
                                $query = "INSERT INTO `glpi_displaypreferences`\n                                         (`itemtype` ,`num` ,`rank` ,`users_id`)\n                                  VALUES ('{$type}', '{$newval}', '" . $rank++ . "',\n                                          '" . $data['users_id'] . "')";
                                $DB->query($query);
                            }
                        }
                    }
                }
            } else {
                // Add for default user
                $rank = 1;
                foreach ($tab as $newval) {
                    $query = "INSERT INTO `glpi_displaypreferences`\n                                (`itemtype` ,`num` ,`rank` ,`users_id`)\n                         VALUES ('{$type}', '{$newval}', '" . $rank++ . "', '0')";
                    $DB->query($query);
                }
            }
        }
    }
    // must always be at the end
    $migration->executeMigration();
    return $updateresult;
}
예제 #5
0
 /**
  * @since version 0.90
  *
  * @param $rand
  **/
 function showTimelineForm($rand)
 {
     global $CFG_GLPI;
     //check global rights
     if (!Session::haveRight("ticket", Ticket::READMY) && !Session::haveRightsOr("followup", array(TicketFollowup::SEEPUBLIC, TicketFollowup::SEEPRIVATE))) {
         return false;
     }
     // javascript function for add and edit items
     echo "<script type='text/javascript' >\n";
     echo "function viewAddSubitem" . $this->fields['id'] . "{$rand}(itemtype) {\n";
     $params = array('type' => 'itemtype', 'parenttype' => 'Ticket', 'tickets_id' => $this->fields['id'], 'id' => -1);
     if (isset($_GET['load_kb_sol'])) {
         $params['load_kb_sol'] = $_GET['load_kb_sol'];
     }
     $out = Ajax::updateItemJsCode("viewitem" . $this->fields['id'] . "{$rand}", $CFG_GLPI["root_doc"] . "/ajax/timeline_viewsubitem.php", $params, "", false);
     echo str_replace("\"itemtype\"", "itemtype", $out);
     echo "\$('#approbation_form{$rand}').remove()";
     echo "};";
     $out = "function viewEditSubitem" . $this->fields['id'] . "{$rand}(e, itemtype, items_id, o) {\n\n               var target = e.target || window.event.srcElement;\n               if (target.nodeName == 'a') return;\n               if (target.className == 'read_more_button') return;";
     $params = array('type' => 'itemtype', 'parenttype' => 'Ticket', 'tickets_id' => $this->fields['id'], 'id' => 'items_id');
     $out .= Ajax::updateItemJsCode("viewitem" . $this->fields['id'] . "{$rand}", $CFG_GLPI["root_doc"] . "/ajax/timeline_viewsubitem.php", $params, "", false);
     $out = str_replace("\"itemtype\"", "itemtype", $out);
     $out = str_replace("\"items_id\"", "items_id", $out);
     echo $out;
     //scroll to edit form
     echo "\$('body').scrollTop(0);";
     echo "\$('.ui-tabs-panel').scrollTop(0);";
     // add a mark to currently edited element
     echo "var found_active = \$('.talk_active');\n            i = found_active.length;\n            while(i--) {\n               var classes = found_active[i].className.replace( /(?:^|\\s)talk_active(?!\\S)/ , '' );\n               found_active[i].className = classes;\n            }\n            o.className = o.className + ' talk_active';\n\n            \$('#approbation_form{$rand}').remove();\n      };";
     if (isset($_GET['load_kb_sol'])) {
         echo "viewAddSubitem" . $this->fields['id'] . "{$rand}('Solution');";
     }
     echo "</script>\n";
     //check sub-items rights
     $tmp = array('tickets_id' => $this->getID());
     $fup = new TicketFollowup();
     $ttask = new TicketTask();
     $doc = new Document();
     $canadd_fup = $fup->can(-1, CREATE, $tmp);
     $canadd_task = $ttask->can(-1, CREATE, $tmp);
     $canadd_document = $doc->can(-1, CREATE, $tmp) && $this->canAddItem('Document');
     $canadd_solution = Ticket::canUpdate() && $this->canSolve();
     if (!$canadd_fup && !$canadd_task && !$canadd_document && !$canadd_solution) {
         return false;
     }
     //show choices
     echo "<h2>" . _sx('button', 'Add') . " : </h2>";
     echo "<div class='timeline_form'>";
     echo "<ul class='timeline_choices'>";
     if ($canadd_fup) {
         echo "<li class='followup' onclick='" . "javascript:viewAddSubitem" . $this->fields['id'] . "{$rand}(\"TicketFollowup\");'>" . __("Followup") . "</li>";
     }
     if ($canadd_task) {
         echo "<li class='task' onclick='" . "javascript:viewAddSubitem" . $this->fields['id'] . "{$rand}(\"TicketTask\");'>" . __("Task") . "</li>";
     }
     if ($canadd_document) {
         echo "<li class='document' onclick='" . "javascript:viewAddSubitem" . $this->fields['id'] . "{$rand}(\"Document_Item\");'>" . __("Document") . "</li>";
     }
     if ($canadd_solution) {
         echo "<li class='solution' onclick='" . "javascript:viewAddSubitem" . $this->fields['id'] . "{$rand}(\"Solution\");'>" . __("Solution") . "</li>";
     }
     echo "</ul>";
     // timeline_choices
     echo "<div class='clear'>&nbsp;</div>";
     echo "</div>";
     //end timeline_form
     echo "<div class='ajax_box' id='viewitem" . $this->fields['id'] . "{$rand}'></div>\n";
 }
예제 #6
0
         }
     }
     break;
 case "submit_validation":
     $valid = new TicketValidation();
     foreach ($_POST["item"] as $key => $val) {
         if ($val == 1) {
             $input = array('tickets_id' => $key, 'users_id_validate' => $_POST['users_id_validate'], 'comment_submission' => $_POST['comment_submission']);
             if ($valid->can(-1, 'w', $input)) {
                 $valid->add($input);
             }
         }
     }
     break;
 case "add_task":
     $task = new TicketTask();
     foreach ($_POST["item"] as $key => $val) {
         if ($val == 1) {
             $input = array('tickets_id' => $key, 'taskcategories_id' => $_POST['taskcategories_id'], 'content' => $_POST['content']);
             if ($task->can(-1, 'w', $input)) {
                 $task->add($input);
             }
         }
     }
     break;
 case "add_actor":
     $ticket = new Ticket();
     foreach ($_POST["item"] as $key => $val) {
         if ($val == 1) {
             $input = array('id' => $key);
             if (isset($_POST['_ticket_requester'])) {
     echo "<option value='after' selected>" . $LANG['buttons'][47] . "</option>";
     echo "<option value='before'>" . $LANG['buttons'][46] . "</option>";
     echo "</select>&nbsp;";
     if (isset($_POST['entity_restrict'])) {
         $condition = $_POST['entity_restrict'];
     } else {
         $condition = "";
     }
     Rule::dropdown(array('sub_type' => $_POST['sub_type'], 'name' => "ranking", 'entity_restrict' => $condition));
     echo "<input type='submit' name='massiveaction' class='submit' value='" . $LANG['buttons'][2] . "'>\n";
     break;
 case "add_followup":
     TicketFollowup::showFormMassiveAction();
     break;
 case "add_task":
     TicketTask::showFormMassiveAction();
     break;
 case "add_actor":
     $types = array(0 => DROPDOWN_EMPTY_VALUE, Ticket::REQUESTER => $LANG['job'][4], Ticket::OBSERVER => $LANG['common'][104], Ticket::ASSIGN => $LANG['job'][5]);
     $rand = Dropdown::showFromArray('actortype', $types);
     $paramsmassaction = array('actortype' => '__VALUE__');
     ajaxUpdateItemOnSelectEvent("dropdown_actortype{$rand}", "show_massiveaction_field", $CFG_GLPI["root_doc"] . "/ajax/dropdownMassiveActionAddActor.php", $paramsmassaction);
     echo "<span id='show_massiveaction_field'>&nbsp;</span>\n";
     break;
 case "link_ticket":
     $rand = Ticket_Ticket::dropdownLinks('link');
     echo "&nbsp;" . $LANG['job'][38] . "&nbsp;" . $LANG['common'][2] . "&nbsp;:&nbsp;";
     echo "<input type='text' name='tickets_id_1' value='' size='10'>\n";
     echo "<input type='submit' name='massiveaction' class='submit' value='" . $LANG['buttons'][2] . "'>";
     break;
 case "submit_validation":
예제 #8
0
 /**
  * @since version 0.90
  *
  * @param $rand
  **/
 function showTimelineForm($rand)
 {
     global $CFG_GLPI;
     //check global rights
     if (!Session::haveRight("ticket", Ticket::READMY) && !Session::haveRightsOr("followup", array(TicketFollowup::SEEPUBLIC, TicketFollowup::SEEPRIVATE))) {
         return false;
     }
     // javascript function for add and edit items
     echo "<script type='text/javascript' >\n";
     echo "function viewAddSubitem" . $this->fields['id'] . "{$rand}(itemtype) {\n";
     $params = array('action' => 'viewsubitem', 'type' => 'itemtype', 'parenttype' => 'Ticket', 'tickets_id' => $this->fields['id'], 'id' => -1);
     if (isset($_GET['load_kb_sol'])) {
         $params['load_kb_sol'] = $_GET['load_kb_sol'];
     }
     $out = Ajax::updateItemJsCode("viewitem" . $this->fields['id'] . "{$rand}", $CFG_GLPI["root_doc"] . "/ajax/timeline.php", $params, "", false);
     echo str_replace("\"itemtype\"", "itemtype", $out);
     echo "\$('#approbation_form{$rand}').remove()";
     echo "};";
     echo "\n\n      function change_task_state(tasks_id, target) {\n         \$.post('" . $CFG_GLPI["root_doc"] . "/ajax/timeline.php',\n                {'action':     'change_task_state',\n                  'tasks_id':   tasks_id,\n                  'tickets_id': " . $this->fields['id'] . "\n                })\n                .done(function(new_state) {\n                  \$(target).removeClass('state_1 state_2')\n                           .addClass('state_'+new_state);\n                });\n      }\n\n      function viewEditSubitem" . $this->fields['id'] . "{$rand}(e, itemtype, items_id, o, domid) {\n               domid = (typeof domid === 'undefined')\n                         ? 'viewitem" . $this->fields['id'] . $rand . "'\n                         : domid;\n               var target = e.target || window.event.srcElement;\n               if (target.nodeName == 'a') return;\n               if (target.className == 'read_more_button') return;\n               \$('#'+domid).addClass('edited');\n               \$('#'+domid+' .displayed_content').hide();\n               \$('#'+domid+' .cancel_edit_item_content').show()\n                                                        .click(function() {\n                                                            \$(this).hide();\n                                                            \$('#'+domid).removeClass('edited');\n                                                            \$('#'+domid+' .edit_item_content').empty().hide();\n                                                            \$('#'+domid+' .displayed_content').show();\n                                                        });\n               \$('#'+domid+' .edit_item_content').show()\n                                                 .load('" . $CFG_GLPI["root_doc"] . "/ajax/timeline.php',\n                                                       {'action'    : 'viewsubitem',\n                                                        'type'      : itemtype,\n                                                        'parenttype': 'Ticket',\n                                                        'tickets_id': " . $this->fields['id'] . ",\n                                                        'id'        : items_id\n                                                       });\n\n\n      };";
     if (isset($_GET['load_kb_sol'])) {
         echo "viewAddSubitem" . $this->fields['id'] . "{$rand}('Solution');";
     }
     echo "</script>\n";
     //check sub-items rights
     $tmp = array('tickets_id' => $this->getID());
     $fup = new TicketFollowup();
     $ttask = new TicketTask();
     $doc = new Document();
     $canadd_fup = $fup->can(-1, CREATE, $tmp);
     $canadd_task = $ttask->can(-1, CREATE, $tmp);
     $canadd_document = $doc->can(-1, CREATE, $tmp) && $this->canAddItem('Document');
     $canadd_solution = Ticket::canUpdate() && $this->canSolve();
     if (!$canadd_fup && !$canadd_task && !$canadd_document && !$canadd_solution) {
         return false;
     }
     //show choices
     echo "<h2>" . _sx('button', 'Add') . " : </h2>";
     echo "<div class='timeline_form'>";
     echo "<ul class='timeline_choices'>";
     if ($canadd_fup) {
         echo "<li class='followup' onclick='" . "javascript:viewAddSubitem" . $this->fields['id'] . "{$rand}(\"TicketFollowup\");'>" . __("Followup") . "</li>";
     }
     if ($canadd_task) {
         echo "<li class='task' onclick='" . "javascript:viewAddSubitem" . $this->fields['id'] . "{$rand}(\"TicketTask\");'>" . __("Task") . "</li>";
     }
     if ($canadd_document) {
         echo "<li class='document' onclick='" . "javascript:viewAddSubitem" . $this->fields['id'] . "{$rand}(\"Document_Item\");'>" . __("Document") . "</li>";
     }
     if ($canadd_solution) {
         echo "<li class='solution' onclick='" . "javascript:viewAddSubitem" . $this->fields['id'] . "{$rand}(\"Solution\");'>" . __("Solution") . "</li>";
     }
     echo "</ul>";
     // timeline_choices
     echo "<div class='clear'>&nbsp;</div>";
     echo "</div>";
     //end timeline_form
     echo "<div class='ajax_box' id='viewitem" . $this->fields['id'] . "{$rand}'></div>\n";
 }
예제 #9
0
 function post_addItem()
 {
     global $LANG, $CFG_GLPI;
     // Add document if needed
     $this->addFiles($this->fields['id']);
     if (isset($this->input["_followup"]) && is_array($this->input["_followup"]) && strlen($this->input["_followup"]['content']) > 0) {
         $fup = new TicketFollowup();
         $type = "new";
         if (isset($this->fields["status"]) && $this->fields["status"] == "solved") {
             $type = "solved";
         }
         $toadd = array("type" => $type, "tickets_id" => $this->fields['id']);
         if (isset($this->input["_followup"]['content']) && strlen($this->input["_followup"]['content']) > 0) {
             $toadd["content"] = $this->input["_followup"]['content'];
         }
         if (isset($this->input["_followup"]['is_private'])) {
             $toadd["is_private"] = $this->input["_followup"]['is_private'];
         }
         $toadd['_no_notif'] = true;
         $fup->add($toadd);
     }
     if (isset($this->input["plan"]) || isset($this->input["_hour"]) && isset($this->input["_minute"]) && isset($this->input["realtime"]) && $this->input["realtime"] > 0) {
         $task = new TicketTask();
         $type = "new";
         if (isset($this->fields["status"]) && $this->fields["status"] == "solved") {
             $type = "solved";
         }
         $toadd = array("type" => $type, "tickets_id" => $this->fields['id']);
         if (isset($this->input["_hour"])) {
             $toadd["hour"] = $this->input["_hour"];
         }
         if (isset($this->input["_minute"])) {
             $toadd["minute"] = $this->input["_minute"];
         }
         if (isset($this->input["plan"])) {
             $toadd["plan"] = $this->input["plan"];
         }
         $toadd['_no_notif'] = true;
         $task->add($toadd);
     }
     $ticket_ticket = new Ticket_Ticket();
     // From interface
     if (isset($this->input['_link'])) {
         $this->input['_link']['tickets_id_1'] = $this->fields['id'];
         if ($ticket_ticket->can(-1, 'w', $this->input['_link'])) {
             $ticket_ticket->add($this->input['_link']);
         }
     }
     // From mailcollector : do not check rights
     if (isset($this->input["_linkedto"])) {
         $input2['tickets_id_1'] = $this->fields['id'];
         $input2['tickets_id_2'] = $this->input["_linkedto"];
         $input2['link'] = Ticket_Ticket::LINK_TO;
         $ticket_ticket->add($input2);
     }
     // Manage SLA Level : add actions
     if (isset($this->input["slas_id"]) && $this->input["slas_id"] > 0 && isset($this->input["slalevels_id"]) && $this->input["slalevels_id"] > 0) {
         $sla = new SLA();
         if ($sla->getFromDB($this->input["slas_id"])) {
             // Add first level in working table
             if ($this->input["slalevels_id"] > 0) {
                 $sla->addLevelToDo($this);
             }
         }
     }
     // Add user groups linked to tickets
     $ticket_user = new Ticket_User();
     $group_ticket = new Group_Ticket();
     if (isset($this->input["_users_id_requester"]) && ($this->input["_users_id_requester"] > 0 || isset($this->input["_users_id_requester_notif"]['alternative_email']) && !empty($this->input["_users_id_requester_notif"]['alternative_email']))) {
         $input2 = array('tickets_id' => $this->fields['id'], 'users_id' => $this->input["_users_id_requester"], 'type' => self::REQUESTER);
         if (isset($this->input["_users_id_requester_notif"])) {
             foreach ($this->input["_users_id_requester_notif"] as $key => $val) {
                 $input2[$key] = $val;
             }
         }
         $ticket_user->add($input2);
     }
     if (isset($this->input["_users_id_observer"]) && ($this->input["_users_id_observer"] > 0 || isset($this->input["_users_id_observer_notif"]['alternative_email']) && !empty($this->input["_users_id_observer_notif"]['alternative_email']))) {
         $input2 = array('tickets_id' => $this->fields['id'], 'users_id' => $this->input["_users_id_observer"], 'type' => self::OBSERVER);
         if (isset($this->input["_users_id_observer_notif"])) {
             foreach ($this->input["_users_id_observer_notif"] as $key => $val) {
                 $input2[$key] = $val;
             }
         }
         $ticket_user->add($input2);
     }
     if (isset($this->input["_users_id_assign"]) && $this->input["_users_id_assign"] > 0) {
         $input2 = array('tickets_id' => $this->fields['id'], 'users_id' => $this->input["_users_id_assign"], 'type' => self::ASSIGN);
         if (isset($this->input["_users_id_assign_notif"])) {
             foreach ($this->input["_users_id_assign_notif"] as $key => $val) {
                 $input2[$key] = $val;
             }
         }
         $ticket_user->add($input2);
     }
     if (isset($this->input["_groups_id_requester"]) && $this->input["_groups_id_requester"] > 0) {
         $group_ticket->add(array('tickets_id' => $this->fields['id'], 'groups_id' => $this->input["_groups_id_requester"], 'type' => self::REQUESTER));
     }
     if (isset($this->input["_groups_id_assign"]) && $this->input["_groups_id_assign"] > 0) {
         $group_ticket->add(array('tickets_id' => $this->fields['id'], 'groups_id' => $this->input["_groups_id_assign"], 'type' => self::ASSIGN));
     }
     if (isset($this->input["_groups_id_observer"]) && $this->input["_groups_id_observer"] > 0) {
         $group_ticket->add(array('tickets_id' => $this->fields['id'], 'groups_id' => $this->input["_groups_id_observer"], 'type' => self::OBSERVER));
     }
     // Additional actors : using default notification parameters
     // Observers : for mailcollector
     if (isset($this->input["_additional_observers"]) && is_array($this->input["_additional_observers"]) && count($this->input["_additional_observers"])) {
         $input2 = array('tickets_id' => $this->fields['id'], 'type' => self::OBSERVER);
         foreach ($this->input["_additional_observers"] as $tmp) {
             if (isset($tmp['users_id'])) {
                 foreach ($tmp as $key => $val) {
                     $input2[$key] = $val;
                 }
                 $ticket_user->add($input2);
             }
         }
     }
     if (isset($this->input["_additional_assigns"]) && is_array($this->input["_additional_assigns"]) && count($this->input["_additional_assigns"])) {
         $input2 = array('tickets_id' => $this->fields['id'], 'type' => self::ASSIGN);
         foreach ($this->input["_additional_assigns"] as $tmp) {
             if (isset($tmp['users_id'])) {
                 foreach ($tmp as $key => $val) {
                     $input2[$key] = $val;
                 }
                 $ticket_user->add($input2);
             }
         }
     }
     if (isset($this->input["_additional_requesters"]) && is_array($this->input["_additional_requesters"]) && count($this->input["_additional_requesters"])) {
         $input2 = array('tickets_id' => $this->fields['id'], 'type' => self::REQUESTER);
         foreach ($this->input["_additional_requesters"] as $tmp) {
             if (isset($tmp['users_id'])) {
                 foreach ($tmp as $key => $val) {
                     $input2[$key] = $val;
                 }
                 $ticket_user->add($input2);
             }
         }
     }
     //Action for send_validation rule
     if (isset($this->input["_add_validation"]) && $this->input["_add_validation"] > 0) {
         $validation = new Ticketvalidation();
         $values['tickets_id'] = $this->fields['id'];
         $values['users_id_validate'] = $this->input["_add_validation"];
         if ($validation->can(-1, 'w', $values)) {
             $validation->add($values);
             Event::log($this->fields['id'], "ticket", 4, "tracking", $_SESSION["glpiname"] . "  " . $LANG['log'][21]);
         }
     }
     // Processing Email
     if ($CFG_GLPI["use_mailing"]) {
         // Clean reload of the ticket
         $this->getFromDB($this->fields['id']);
         $type = "new";
         if (isset($this->fields["status"]) && $this->fields["status"] == "solved") {
             $type = "solved";
         }
         NotificationEvent::raiseEvent($type, $this);
     }
     if (isset($_SESSION['glpiis_ids_visible']) && !$_SESSION['glpiis_ids_visible']) {
         addMessageAfterRedirect($LANG['help'][18] . " (" . $LANG['job'][38] . "&nbsp;" . "<a href='" . $CFG_GLPI["root_doc"] . "/front/ticket.form.php?id=" . $this->fields['id'] . "'>" . $this->fields['id'] . "</a>)");
     }
 }
예제 #10
0
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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
--------------------------------------------------------------------------
*/
// ----------------------------------------------------------------------
// Original Author of file:
// Purpose of file:
// ----------------------------------------------------------------------
define('GLPI_ROOT', '..');
include GLPI_ROOT . "/inc/includes.php";
checkCentralAccess();
$task = new TicketTask();
if (isset($_POST["add"])) {
    $task->check(-1, 'w', $_POST);
    $task->add($_POST);
    Event::log($task->getField('tickets_id'), "ticket", 4, "tracking", $_SESSION["glpiname"] . "  " . $LANG['log'][21]);
    glpi_header(getItemTypeFormURL('Ticket') . "?id=" . $task->getField('tickets_id'));
} else {
    if (isset($_POST["delete"])) {
        $task->check($_POST['id'], 'd');
        $task->delete($_POST);
        Event::log($task->getField('tickets_id'), "ticket", 4, "tracking", $_SESSION["glpiname"] . " " . $LANG['log'][21]);
        glpi_header(getItemTypeFormURL('Ticket') . "?id=" . $task->getField('tickets_id'));
    } else {
        if (isset($_POST["update"])) {
            $task->check($_POST["id"], 'w');
            $task->update($_POST);
<?php

include '../../../inc/includes.php';
Session::checkLoginUser();
//add followup
if (isset($_REQUEST['ticketfollowup'])) {
    $fup = new TicketFollowup();
    if (isset($_POST["add"])) {
        $fup->check(-1, 'w', $_POST);
        $fup->add($_POST);
        Event::log($fup->getField('tickets_id'), "ticket", 4, "tracking", sprintf(__('%s adds a followup'), $_SESSION["glpiname"]));
    }
}
//add task
if (isset($_REQUEST['tickettask'])) {
    $ttask = new TicketTask();
    if (isset($_POST["add"])) {
        $ttask->check(-1, 'w', $_POST);
        $ttask->add($_POST);
        Event::log($ttask->getField('tickets_id'), "ticket", 4, "tracking", sprintf(__('%s adds a task'), $_SESSION["glpiname"]));
    }
}
//add document
if (isset($_REQUEST['filename']) && !empty($_REQUEST['filename'])) {
    $doc = new Document();
    if (isset($_POST["add"])) {
        $doc->check(-1, 'w', $_POST);
        if ($newID = $doc->add($_POST)) {
            Event::log($newID, "documents", 4, "login", sprintf(__('%1$s adds the item %2$s'), $_SESSION["glpiname"], $doc->fields["name"]));
        }
    }
예제 #12
0
 /**
  * Dropdown of actions for massive action
  *
  * @param $itemtype item type
  * @param $is_deleted massive action for deleted items ?
  * @param $extraparams array of extra parameters
  **/
 static function showForMassiveAction($itemtype, $is_deleted = 0, $extraparams = array())
 {
     global $LANG, $CFG_GLPI, $PLUGIN_HOOKS;
     /// TODO include in CommonDBTM defining only getAdditionalMassiveAction in sub classes
     /// for specific actions (return a array of action name and title)
     if (!class_exists($itemtype)) {
         return false;
     }
     if ($itemtype == 'NetworkPort') {
         echo "<select name='massiveaction' id='massiveaction'>";
         echo "<option value='-1' selected>" . DROPDOWN_EMPTY_VALUE . "</option>";
         echo "<option value='delete'>" . $LANG['buttons'][6] . "</option>";
         echo "<option value='assign_vlan'>" . $LANG['networking'][55] . "</option>";
         echo "<option value='unassign_vlan'>" . $LANG['networking'][58] . "</option>";
         // Interest of this massive action ?
         //          echo "<option value='move'>".$LANG['buttons'][20]."</option>";
         echo "</select>";
         $params = array('action' => '__VALUE__', 'itemtype' => $itemtype);
         ajaxUpdateItemOnSelectEvent("massiveaction", "show_massiveaction", $CFG_GLPI["root_doc"] . "/ajax/dropdownMassiveActionPorts.php", $params);
         echo "<span id='show_massiveaction'>&nbsp;</span>\n";
     } else {
         $item = new $itemtype();
         $infocom = new Infocom();
         $isadmin = $item->canUpdate();
         echo "<select name='massiveaction' id='massiveaction'>";
         echo "<option value='-1' selected>" . DROPDOWN_EMPTY_VALUE . "</option>";
         if (!in_array($itemtype, $CFG_GLPI["massiveaction_noupdate_types"]) && ($isadmin && $itemtype != 'Ticket' || in_array($itemtype, $CFG_GLPI["infocom_types"]) && $infocom->canUpdate() || $itemtype == 'Ticket' && haveRight('update_ticket', 1))) {
             echo "<option value='update'>" . $LANG['buttons'][14] . "</option>";
         }
         if (in_array($itemtype, $CFG_GLPI["infocom_types"]) && $infocom->canCreate()) {
             echo "<option value='activate_infocoms'>" . $LANG['financial'][68] . "</option>";
         }
         if ($is_deleted && !in_array($itemtype, $CFG_GLPI["massiveaction_nodelete_types"])) {
             if ($isadmin) {
                 echo "<option value='purge'>" . $LANG['buttons'][22] . "</option>";
                 echo "<option value='restore'>" . $LANG['buttons'][21] . "</option>";
             }
         } else {
             // No delete for entities and tracking of not have right
             if (!in_array($itemtype, $CFG_GLPI["massiveaction_nodelete_types"]) && ($isadmin && $itemtype != 'Ticket' || $itemtype == 'Ticket' && haveRight('delete_ticket', 1))) {
                 if ($item->maybeDeleted()) {
                     echo "<option value='delete'>" . $LANG['buttons'][6] . "</option>";
                 } else {
                     echo "<option value='purge'>" . $LANG['buttons'][22] . "</option>";
                 }
             }
             if ($isadmin && in_array($itemtype, array('Phone', 'Printer', 'Peripheral', 'Monitor'))) {
                 echo "<option value='connect'>" . $LANG['buttons'][9] . "</option>";
                 echo "<option value='disconnect'>" . $LANG['buttons'][10] . "</option>";
             }
             if (in_array($itemtype, $CFG_GLPI["document_types"])) {
                 $doc = new Document();
                 if ($doc->canView()) {
                     echo "<option value='add_document'>" . $LANG['document'][16] . "</option>";
                 }
             }
             if (in_array($itemtype, $CFG_GLPI["contract_types"])) {
                 $contract = new Contract();
                 if ($contract->canUpdate()) {
                     echo "<option value='add_contract'>" . $LANG['financial'][36] . "</option>";
                 }
             }
             if (haveRight('transfer', 'r') && isMultiEntitiesMode() && in_array($itemtype, array('CartridgeItem', 'Computer', 'ConsumableItem', 'Contact', 'Contract', 'Supplier', 'Monitor', 'NetworkEquipment', 'Peripheral', 'Phone', 'Printer', 'Software', 'SoftwareLicense', 'Ticket', 'Document', 'Group', 'Link')) && $isadmin) {
                 echo "<option value='add_transfer_list'>" . $LANG['buttons'][48] . "</option>";
             }
             switch ($itemtype) {
                 case 'Software':
                     if ($isadmin && countElementsInTable("glpi_rules", "sub_type='RuleSoftwareCategory'") > 0) {
                         echo "<option value='compute_software_category'>" . $LANG['rulesengine'][38] . " " . $LANG['rulesengine'][40] . "</option>";
                     }
                     if (haveRight("rule_dictionnary_software", "w") && countElementsInTable("glpi_rules", "sub_type='RuleDictionnarySoftware'") > 0) {
                         echo "<option value='replay_dictionnary'>" . $LANG['rulesengine'][76] . "</option>";
                     }
                     break;
                 case 'Computer':
                     if ($isadmin) {
                         echo "<option value='connect_to_computer'>" . $LANG['buttons'][9] . "</option>";
                         echo "<option value='install'>" . $LANG['buttons'][4] . "</option>";
                         if ($CFG_GLPI['use_ocs_mode']) {
                             if (haveRight("ocsng", "w") || haveRight("sync_ocsng", "w")) {
                                 echo "<option value='force_ocsng_update'>" . $LANG['ocsng'][24] . "</option>";
                             }
                             echo "<option value='unlock_ocsng_field'>" . $LANG['buttons'][38] . " " . $LANG['Menu'][33] . " - " . $LANG['ocsng'][16] . "</option>";
                             echo "<option value='unlock_ocsng_monitor'>" . $LANG['buttons'][38] . " " . $LANG['Menu'][33] . " - " . $LANG['ocsng'][30] . "</option>";
                             echo "<option value='unlock_ocsng_peripheral'>" . $LANG['buttons'][38] . " " . $LANG['Menu'][33] . " - " . $LANG['ocsng'][32] . "</option>";
                             echo "<option value='unlock_ocsng_printer'>" . $LANG['buttons'][38] . " " . $LANG['Menu'][33] . " - " . $LANG['ocsng'][34] . "</option>";
                             echo "<option value='unlock_ocsng_software'>" . $LANG['buttons'][38] . " " . $LANG['Menu'][33] . " - " . $LANG['ocsng'][52] . "</option>";
                             echo "<option value='unlock_ocsng_ip'>" . $LANG['buttons'][38] . " " . $LANG['Menu'][33] . " - " . $LANG['ocsng'][50] . "</option>";
                             echo "<option value='unlock_ocsng_disk'>" . $LANG['buttons'][38] . " " . $LANG['Menu'][33] . " - " . $LANG['ocsng'][55] . "</option>";
                         }
                     }
                     break;
                 case 'Supplier':
                     if ($isadmin) {
                         echo "<option value='add_contact'>" . $LANG['financial'][24] . "</option>";
                     }
                     break;
                 case 'Calendar':
                     echo "<option value='duplicate'>" . $LANG['buttons'][54] . "</option>";
                     break;
                 case 'Contact':
                     if ($isadmin) {
                         echo "<option value='add_enterprise'>" . $LANG['financial'][25] . "</option>";
                     }
                     break;
                 case 'User':
                     if ($isadmin) {
                         echo "<option value='add_group'>" . $LANG['setup'][604] . "</option>";
                         echo "<option value='add_userprofile'>" . $LANG['setup'][607] . "</option>";
                     }
                     if (haveRight("user_authtype", "w")) {
                         echo "<option value='change_authtype'>" . $LANG['login'][30] . "</option>";
                         echo "<option value='force_user_ldap_update'>" . $LANG['ocsng'][24] . "</option>";
                     }
                     break;
                 case 'Ticket':
                     $tmp = new TicketFollowup();
                     if ($tmp->canCreate()) {
                         echo "<option value='add_followup'>" . $LANG['job'][29] . "</option>";
                     }
                     $tmp = new TicketTask();
                     if ($tmp->canCreate()) {
                         echo "<option value='add_task'>" . $LANG['job'][30] . "</option>";
                     }
                     $tmp = new TicketValidation();
                     if ($tmp->canCreate()) {
                         echo "<option value='submit_validation'>" . $LANG['validation'][26] . "</option>";
                     }
                     if (haveRight("update_ticket", "1")) {
                         echo "<option value='add_actor'>" . $LANG['job'][27] . "</option>";
                         echo "<option value='link_ticket'>" . $LANG['job'][56] . "</option>";
                     }
                     break;
                 case 'CronTask':
                     echo "<option value='reset'>" . $LANG['buttons'][16] . " (" . $LANG['crontask'][40] . ")";
                     echo "</option>";
                     break;
                 case 'NotImportedEmail':
                     echo "<option value='delete_email'>" . $LANG['mailing'][133] . "</option>";
                     echo "<option value='import_email'>" . $LANG['buttons'][37] . "</option>";
                     break;
             }
             if ($item instanceof CommonTreeDropdown) {
                 if ($isadmin) {
                     echo "<option value='move_under'>" . $LANG['buttons'][20] . "</option>";
                 }
             }
             if ($itemtype != 'Entity' && $itemtype != 'Calendar' && $item instanceof CommonDropdown && $item->maybeRecursive()) {
                 if ($isadmin) {
                     echo "<option value='merge'>" . $LANG['buttons'][48] . " - " . $LANG['software'][48];
                     echo "</option>";
                 }
             }
             // Plugin Specific actions
             if (isset($PLUGIN_HOOKS['use_massive_action'])) {
                 foreach ($PLUGIN_HOOKS['use_massive_action'] as $plugin => $val) {
                     $actions = doOneHook($plugin, 'MassiveActions', $itemtype);
                     if (count($actions)) {
                         foreach ($actions as $key => $val) {
                             echo "<option value = '{$key}'>{$val}</option>";
                         }
                     }
                 }
             }
         }
         echo "</select>";
         $params = array('action' => '__VALUE__', 'is_deleted' => $is_deleted, 'itemtype' => $itemtype);
         if (count($extraparams)) {
             foreach ($extraparams as $key => $val) {
                 $params['extra_' . $key] = $val;
             }
         }
         ajaxUpdateItemOnSelectEvent("massiveaction", "show_massiveaction", $CFG_GLPI["root_doc"] . "/ajax/dropdownMassiveAction.php", $params);
         echo "<span id='show_massiveaction'>&nbsp;</span>\n";
     }
 }
예제 #13
0
 /**
  *  remove old groups to a ticket when a new group assigned
  *  called by "pre_item_add" hook on Group_Ticket object
  * @param CommonDBTM $item the ticket object
  */
 static function addHistoryOnAddGroup(CommonDBTM $item)
 {
     global $DB;
     if ($_SESSION['plugins']['escalade']['config']['remove_group'] == false) {
         return true;
     }
     //if group sent is not an assign group, return
     if ($item->input['type'] != CommonITILActor::ASSIGN) {
         return;
     }
     $tickets_id = $item->input['tickets_id'];
     $groups_id = $item->input['groups_id'];
     //if group already assigned, return
     $group_ticket = new Group_Ticket();
     $condition = "tickets_id = {$tickets_id} AND groups_id = {$groups_id} AND type = 2";
     if ($group_ticket->find($condition)) {
         unset($_SESSION['plugin_escalade']['keep_users']);
         return;
     }
     $item->fields['status'] = CommonITILObject::ASSIGNED;
     //add line in history table
     $history = new PluginEscaladeHistory();
     $history->add(array('tickets_id' => $tickets_id, 'groups_id' => $groups_id));
     //remove old user(s) (pass if user added by new ticket form)
     $backtrace = debug_backtrace();
     $first_trace = array_pop($backtrace);
     if (strpos($first_trace['file'], 'ticket.form.php') === false || $first_trace['function'] != "add" || !$first_trace['object'] instanceof Ticket) {
         self::removeAssignUsers($tickets_id);
     }
     //add a task to inform the escalation (pass if solution)
     if (isset($_SESSION['plugin_escalade']['solution'])) {
         unset($_SESSION['plugin_escalade']['solution']);
         return $item;
     }
     if ($_SESSION['plugins']['escalade']['config']['task_history']) {
         $group = new Group();
         $group->getFromDB($groups_id);
         $task = new TicketTask();
         $task->add(array('tickets_id' => $tickets_id, 'is_private' => true, 'state' => 0, 'content' => __("escalated to the group", "escalade") . " " . $group->getName()));
     }
     //check if event is not triggered by behaviors plugin
     //to prevent user remove when "add technician group" option is active
     if (strpos($first_trace['file'], 'ticket.form.php') !== false && $first_trace['function'] == "add" && $first_trace['object'] instanceof Ticket) {
         return;
     }
     if ($_SESSION['plugins']['escalade']['config']['ticket_last_status'] != -1) {
         $ticket = new Ticket();
         $ticket->update(array('id' => $tickets_id, 'status' => $_SESSION['plugins']['escalade']['config']['ticket_last_status']));
     }
     return $item;
 }
예제 #14
0
 static function finishAdd($item)
 {
     if (isset($_SESSION['plugin_escalation_ticketcopy']) && count($_SESSION['plugin_escalation_ticketcopy']) > 0) {
         if (isset($_SESSION['plugin_escalation_ticketcopy']['followup'])) {
             $ticketFollowup = new TicketFollowup();
             foreach ($_SESSION['plugin_escalation_ticketcopy']['followup'] as $follows_id) {
                 $a_followups = $ticketFollowup->find("`id`='" . $follows_id . "'");
                 foreach ($a_followups as $data) {
                     unset($data['id']);
                     $data = Toolbox::addslashes_deep($data);
                     $data['tickets_id'] = $item->getID();
                     $ticketFollowup->add($data);
                 }
             }
         }
         if (isset($_SESSION['plugin_escalation_ticketcopy']['task'])) {
             $ticketTask = new TicketTask();
             foreach ($_SESSION['plugin_escalation_ticketcopy']['task'] as $tasks_id) {
                 $a_tasks = $ticketTask->find("`id`='" . $tasks_id . "'", "`id`");
                 foreach ($a_tasks as $data) {
                     unset($data['id']);
                     $data = Toolbox::addslashes_deep($data);
                     $data['tickets_id'] = $item->getID();
                     foreach ($data as $key => $value) {
                         if ($value == '') {
                             unset($data[$key]);
                         }
                     }
                     $ticketTask->add($data);
                 }
             }
         }
         unset($_SESSION['plugin_escalation_ticketcopy']);
     }
 }
예제 #15
0
/** Generate bigdump : add tickets to an item
 *
 * @param $type      item type
 * @param $ID        item ID
 * @param $ID_entity entity ID
**/
function addTracking($type, $ID, $ID_entity) {
   global $percent, $DB, $MAX, $FIRST, $LAST;

   $current_year = date("Y");

   while (mt_rand(0,100)<$percent['tracking_on_item']) {
      // ticket closed ?
      $status    = CommonITILObject::CLOSED;
      $closedate = "";
      $solvedate = "";

      $opendate  = time() - mt_rand(0, 365)*DAY_TIMESTAMP - mt_rand(0, 10)*HOUR_TIMESTAMP
                   - mt_rand(0, 60)*MINUTE_TIMESTAMP - mt_rand(0, 60);

      if (mt_rand(0,100)<$percent['closed_tracking']) {
         $rtype = mt_rand(0, 100);

         if ($rtype<20) {
            $status = CommonITILObject::SOLVED;
         } else {
            $status = CommonITILObject::CLOSED;
         }

      } else {
         $rtype = mt_rand(0, 100);

         if ($rtype<20) {
            $status = CommonITILObject::INCOMING;

         } else if ($rtype<40) {
            $status = CommonITILObject::WAITING;

         } else if ($rtype<80) {
            $status = CommonITILObject::PLANNED;
            $date3  = $opendate+mt_rand(10800, 7776000); // + entre 3 heures et 3 mois
            $date4  = $date3+10800; // + 3 heures

         } else {
            $status = CommonITILObject::ASSIGNED;
         }
      }

      // Author
      $users[0] = mt_rand($FIRST['users_normal'], $LAST['users_postonly']);

      // Assign user
      $users[1] = 0;

      if ($status != CommonITILObject::INCOMING) {
         $users[1] = mt_rand($FIRST['users_sadmin'], $LAST['users_admin']);
      }
      $enterprise = 0;

      if (mt_rand(0,100)<20) {
         $enterprise = mt_rand($FIRST["enterprises"], $LAST['enterprises']);
      }

      $firstactiontime = mt_rand(0, 10)*DAY_TIMESTAMP+mt_rand(0, 10)*HOUR_TIMESTAMP
                         +mt_rand(0, 60)*MINUTE_TIMESTAMP;
      $solvetime       = 0;
      $closetime       = 0;
      $actiontime      = 0;

      $solution        = "";
      $solutiontype    = 0;
      $due_date        = $opendate + $firstactiontime+mt_rand(0, 10)*DAY_TIMESTAMP+
                         mt_rand(0, 10)*HOUR_TIMESTAMP+mt_rand(0, 60)*MINUTE_TIMESTAMP;
      $duedatetoadd    = date("Y-m-d H:i:s", intval($due_date));


      if (($status == CommonITILObject::CLOSED) || ($status == CommonITILObject::SOLVED)) {
         $solvetime = $firstactiontime+mt_rand(0, 10)*DAY_TIMESTAMP+mt_rand(0, 10)*HOUR_TIMESTAMP+
                      mt_rand(0, 60)*MINUTE_TIMESTAMP;
         $solvedate = $opendate+$solvetime;
         $closedate = $opendate+$solvetime;
         $actiontime = mt_rand(0, 10)*HOUR_TIMESTAMP+
                      mt_rand(0, 60)*MINUTE_TIMESTAMP;
         if ($status == CommonITILObject::CLOSED) {
            $closetime = $solvetime+mt_rand(0, 5)*DAY_TIMESTAMP+mt_rand(0, 10)*HOUR_TIMESTAMP+
                         mt_rand(0, 60)*MINUTE_TIMESTAMP;
            $closedate = $opendate+$closetime;
         }
         $solutiontype = mt_rand($FIRST['solutiontypes'], $LAST['solutiontypes']);
         $solution     = "Solution '".Toolbox::getRandomString(20);
      }
      $updatedate = $opendate+max($firstactiontime, $solvetime, $closetime);
      $hour_cost  = 100;

      $closedatetoadd = 'NULL';
      if (!empty($closedate)) {
         $closedatetoadd = date("Y-m-d H:i:s", intval($closedate));
      }

      $solvedatetoadd = 'NULL';
      if (!empty($solvedate)) {
         $solvedatetoadd = date("Y-m-d H:i:s",intval($solvedate));
      }
      $t   = new Ticket();
      $tID = $t->add(toolbox::addslashes_deep(
                     array('entities_id'                 => $ID_entity,
                           'name'                        => "Title '".Toolbox::getRandomString(20),
                           'date'                        => date("Y-m-d H:i:s", intval($opendate)),
                           'closedate'                   => $closedatetoadd,
                           'solvedate'                   => $solvedatetoadd,
                           'date_mod'                    => date("Y-m-d H:i:s", intval($updatedate)),
                           'users_id_lastupdater'        => $users[0],
                           'status'                      => $status,
                           'users_id_recipient'          => $users[0],
                           'requesttypes_id'             => mt_rand(0,6),
                           '_suppliers_id_assign'        => $enterprise,
                           'itemtype'                    => $type,
                           'items_id'                    => $ID,
                           'content'                     => "tracking '".Toolbox::getRandomString(15),
                           'urgency'                     => mt_rand(1,5),
                           'impact'                      => mt_rand(1,5),
                           'priority'                    => mt_rand(1,5),
                           'itilcategories_id'           => mt_rand(0, $MAX['tracking_category']),
                           'type'                        => mt_rand(1,2),
                           'solutiontypes_id'            => $solutiontype,
                           'locations_id'                => mt_rand($FIRST['locations'],
                                                                    $LAST['locations']),
                           'solution'                    => $solution,
                           'actiontime'                  => $actiontime,
                           'due_date'                    => $duedatetoadd,
                           'close_delay_stat'            => $closetime,
                           'solve_delay_stat'            => $solvetime,
                           'takeintoaccount_delay_stat'  => $firstactiontime,
                           '_users_id_requester'         => $users[0],
                           '_users_id_assign'            => $users[1],
                           '_groups_id_assign'           => mt_rand($FIRST["techgroups"],
                                                                    $LAST['techgroups']),
                           '_groups_id_requester'        => mt_rand($FIRST["groups"], $LAST['groups']),
                     )));

      // Add followups
      $i     = 0;
      $fID   = 0;
      $first = true;
      $date  = 0;
      $tf    = new TicketFollowup();
      while (mt_rand(0,100)<$percent['followups']) {
         if ($first) {
            $date = $opendate+$firstactiontime;
            $first = false;

         } else {
            $date += mt_rand(3600, 7776000);
         }
         $tf->add(toolbox::addslashes_deep(
                  array('tickets_id'      => $tID,
                        'date'            => date("Y-m-d H:i:s", $date),
                        'users_id'        => $users[1],
                        'content'         => "followup $i '".Toolbox::getRandomString(15),
                        'requesttypes_id' => mt_rand(0, 3))));
         $i++;
      }
      $tt = new TicketTask();
      while (mt_rand(0,100)<$percent['tasks']) {
         $doplan=false;
         if ($first) {
            $date   = $opendate+$firstactiontime;
            $first  = false;
            $doplan = true;
         } else {
            $date += mt_rand(3600, 7776000);
         }

         $begin       = $end = 'NULL';
         $assign_user = 0;
         $state       = 1;
         if ($status == CommonITILObject::PLANNED && $doplan) {
            $endtask = date("Y-m-d H:i:s", $date4);
            if ($endtask < date("Y-m-d H:i:s")) {
               $state = 2; // done
            }
         }
         $params = toolbox::addslashes_deep(
                   array('tickets_id'        => $tID,
                         'taskcategories_id' => mt_rand($FIRST['taskcategory'], $LAST['taskcategory']),
                         'date'              => date("Y-m-d H:i:s",$date),
                         'users_id'          => $users[1],
                         'content'           => "task $i '".Toolbox::getRandomString(15),
                         'is_private'        => mt_rand(0,1),
                         'state'             => $state,
                         'users_id_tech'    => $users[1]));

         if ($status == CommonITILObject::PLANNED && $doplan) {
            $params['plan'] = array('begin'       => date("Y-m-d H:i:s", $date3),
                                    'end'         => $endtask);
         }
         $tt->add($params);
         $i++;
      }

      $tc = new TicketCost();
      $params = toolbox::addslashes_deep(
                array('tickets_id'        => $tID,
                     'entities_id'       => $ID_entity,
                     'begin_date'        => date("Y-m-d H:i:s", intval($opendate)),
                     'name'              => "C'ost",
                     'cost_time'         => $hour_cost,
                     'actiontime'        => floor($actiontime/2)));

      // Insert satisfaction for stats
      if ($status == CommonITILObject::CLOSED
          && mt_rand(0,100) < $percent['satisfaction']) {

         $answerdate = 'NULL';
         if (mt_rand(0,100) < $percent['answersatisfaction']) {
            $answerdate = $closedatetoadd;
         }
         $ts = new TicketSatisfaction();
         $ts->add(toolbox::addslashes_deep(
                  array('tickets_id'   => $tID,
                        'type'         => mt_rand(1,2),
                        'date_begin'   => $closedatetoadd,
                        'date_answer'  => $answerdate,
                        'satisfaction' => mt_rand(0,5),
                        'comment'      => "comment ' satisfaction $tID")));
      }

   }

}
예제 #16
0
     $validation = new Ticketvalidation();
     $validation->showSummary($ticket);
     $task = new TicketTask();
     $task->showSummary($ticket);
     $ticket->showSolutionForm();
     if ($ticket->canApprove()) {
         $fup->showApprobationForm($ticket);
     }
     $ticket->showCost($_POST['target']);
     $ticket->showStats();
     Document::showAssociated($ticket);
     Log::showForItem($ticket);
     Plugin::displayAction($ticket, $_REQUEST['glpi_tab']);
     break;
 case 2:
     $task = new TicketTask();
     $task->showSummary($ticket);
     break;
 case 3:
     $ticket->showCost($_POST['target']);
     break;
 case 4:
     if (!isset($_POST['load_kb_sol'])) {
         $_POST['load_kb_sol'] = 0;
     }
     $ticket->showSolutionForm($_POST['load_kb_sol']);
     if ($ticket->canApprove()) {
         $fup = new TicketFollowup();
         $fup->showApprobationForm($ticket);
     }
     break;
 function getSearchOptions()
 {
     $tab = array();
     $tab += $this->getSearchOptionsMain();
     $tab[14]['table'] = $this->getTable();
     $tab[14]['field'] = 'type';
     $tab[14]['name'] = __('Type');
     $tab[14]['searchtype'] = 'equals';
     $tab[14]['datatype'] = 'specific';
     $tab[13]['table'] = 'glpi_items_tickets';
     $tab[13]['field'] = 'items_id';
     $tab[13]['name'] = _n('Associated element', 'Associated elements', Session::getPluralNumber());
     $tab[13]['datatype'] = 'specific';
     $tab[13]['comments'] = true;
     $tab[13]['nosort'] = true;
     $tab[13]['nosearch'] = true;
     $tab[13]['additionalfields'] = array('itemtype');
     $tab[13]['joinparams'] = array('jointype' => 'child');
     $tab[13]['forcegroupby'] = true;
     $tab[13]['massiveaction'] = false;
     $tab[131]['table'] = 'glpi_items_tickets';
     $tab[131]['field'] = 'itemtype';
     $tab[131]['name'] = _n('Associated item type', 'Associated item types', Session::getPluralNumber());
     $tab[131]['datatype'] = 'itemtypename';
     $tab[131]['itemtype_list'] = 'ticket_types';
     $tab[131]['nosort'] = true;
     $tab[131]['additionalfields'] = array('itemtype');
     $tab[131]['joinparams'] = array('jointype' => 'child');
     $tab[131]['forcegroupby'] = true;
     $tab[131]['massiveaction'] = false;
     $tab[9]['table'] = 'glpi_requesttypes';
     $tab[9]['field'] = 'name';
     $tab[9]['name'] = __('Request source');
     $tab[9]['datatype'] = 'dropdown';
     // Can't use Location::getSearchOptionsToAdd because id conflicts
     $tab[83]['table'] = 'glpi_locations';
     $tab[83]['field'] = 'completename';
     $tab[83]['name'] = __('Location');
     $tab[83]['datatype'] = 'dropdown';
     $tab[80]['table'] = 'glpi_entities';
     $tab[80]['field'] = 'completename';
     $tab[80]['name'] = __('Entity');
     $tab[80]['massiveaction'] = false;
     $tab[80]['datatype'] = 'dropdown';
     // For ticket template
     $tab[142]['table'] = 'glpi_documents';
     $tab[142]['field'] = 'name';
     $tab[142]['name'] = _n('Document', 'Documents', Session::getPluralNumber());
     $tab[142]['forcegroupby'] = true;
     $tab[142]['usehaving'] = true;
     $tab[142]['nosearch'] = true;
     $tab[142]['nodisplay'] = true;
     $tab[142]['datatype'] = 'dropdown';
     $tab[142]['massiveaction'] = false;
     $tab[142]['joinparams'] = array('jointype' => 'items_id', 'beforejoin' => array('table' => 'glpi_documents_items', 'joinparams' => array('jointype' => 'itemtype_item')));
     $tab += $this->getSearchOptionsActors();
     $tab['sla'] = __('SLA');
     $tab[30]['table'] = 'glpi_slas';
     $tab[30]['field'] = 'name';
     $tab[30]['name'] = __('SLA');
     $tab[30]['massiveaction'] = false;
     $tab[30]['datatype'] = 'dropdown';
     $tab[32]['table'] = 'glpi_slalevels';
     $tab[32]['field'] = 'name';
     $tab[32]['name'] = __('Escalation level');
     $tab[32]['massiveaction'] = false;
     $tab[32]['datatype'] = 'dropdown';
     $tab += TicketValidation::getSearchOptionsToAdd();
     $tab['satisfaction'] = __('Satisfaction survey');
     $tab[31]['table'] = 'glpi_ticketsatisfactions';
     $tab[31]['field'] = 'type';
     $tab[31]['name'] = __('Type');
     $tab[31]['massiveaction'] = false;
     $tab[31]['searchtype'] = array('equals', 'notequals');
     $tab[31]['searchequalsonfield'] = true;
     $tab[31]['joinparams'] = array('jointype' => 'child');
     $tab[31]['datatype'] = 'specific';
     $tab[60]['table'] = 'glpi_ticketsatisfactions';
     $tab[60]['field'] = 'date_begin';
     $tab[60]['name'] = __('Creation date');
     $tab[60]['datatype'] = 'datetime';
     $tab[60]['massiveaction'] = false;
     $tab[60]['joinparams'] = array('jointype' => 'child');
     $tab[61]['table'] = 'glpi_ticketsatisfactions';
     $tab[61]['field'] = 'date_answered';
     $tab[61]['name'] = __('Response date');
     $tab[61]['datatype'] = 'datetime';
     $tab[61]['massiveaction'] = false;
     $tab[61]['joinparams'] = array('jointype' => 'child');
     $tab[62]['table'] = 'glpi_ticketsatisfactions';
     $tab[62]['field'] = 'satisfaction';
     $tab[62]['name'] = __('Satisfaction');
     $tab[62]['datatype'] = 'number';
     $tab[62]['massiveaction'] = false;
     $tab[62]['joinparams'] = array('jointype' => 'child');
     $tab[63]['table'] = 'glpi_ticketsatisfactions';
     $tab[63]['field'] = 'comment';
     $tab[63]['name'] = __('Comments');
     $tab[63]['datatype'] = 'text';
     $tab[63]['massiveaction'] = false;
     $tab[63]['joinparams'] = array('jointype' => 'child');
     $tab['followup'] = _n('Followup', 'Followups', Session::getPluralNumber());
     $followup_condition = '';
     if (!Session::haveRight('followup', TicketFollowup::SEEPRIVATE)) {
         $followup_condition = "AND (`NEWTABLE`.`is_private` = '0'\n                                     OR `NEWTABLE`.`users_id` = '" . Session::getLoginUserID() . "')";
     }
     $tab[25]['table'] = 'glpi_ticketfollowups';
     $tab[25]['field'] = 'content';
     $tab[25]['name'] = __('Description');
     $tab[25]['forcegroupby'] = true;
     $tab[25]['splititems'] = true;
     $tab[25]['massiveaction'] = false;
     $tab[25]['joinparams'] = array('jointype' => 'child', 'condition' => $followup_condition);
     $tab[25]['datatype'] = 'text';
     $tab[36]['table'] = 'glpi_ticketfollowups';
     $tab[36]['field'] = 'date';
     $tab[36]['name'] = __('Date');
     $tab[36]['datatype'] = 'datetime';
     $tab[36]['massiveaction'] = false;
     $tab[36]['forcegroupby'] = true;
     $tab[36]['joinparams'] = array('jointype' => 'child', 'condition' => $followup_condition);
     $tab[27]['table'] = 'glpi_ticketfollowups';
     $tab[27]['field'] = 'id';
     $tab[27]['name'] = _x('quantity', 'Number of followups');
     $tab[27]['forcegroupby'] = true;
     $tab[27]['usehaving'] = true;
     $tab[27]['datatype'] = 'count';
     $tab[27]['massiveaction'] = false;
     $tab[27]['joinparams'] = array('jointype' => 'child', 'condition' => $followup_condition);
     $tab[29]['table'] = 'glpi_requesttypes';
     $tab[29]['field'] = 'name';
     $tab[29]['name'] = __('Request source');
     $tab[29]['datatype'] = 'dropdown';
     $tab[29]['forcegroupby'] = true;
     $tab[29]['massiveaction'] = false;
     $tab[29]['joinparams'] = array('beforejoin' => array('table' => 'glpi_ticketfollowups', 'joinparams' => array('jointype' => 'child', 'condition' => $followup_condition)));
     $tab[91]['table'] = 'glpi_ticketfollowups';
     $tab[91]['field'] = 'is_private';
     $tab[91]['name'] = __('Private followup');
     $tab[91]['datatype'] = 'bool';
     $tab[91]['forcegroupby'] = true;
     $tab[91]['splititems'] = true;
     $tab[91]['massiveaction'] = false;
     $tab[91]['joinparams'] = array('jointype' => 'child', 'condition' => $followup_condition);
     $tab[93]['table'] = 'glpi_users';
     $tab[93]['field'] = 'name';
     $tab[93]['name'] = __('Writer');
     $tab[93]['datatype'] = 'itemlink';
     $tab[93]['right'] = 'all';
     $tab[93]['forcegroupby'] = true;
     $tab[93]['massiveaction'] = false;
     $tab[93]['joinparams'] = array('beforejoin' => array('table' => 'glpi_ticketfollowups', 'joinparams' => array('jointype' => 'child', 'condition' => $followup_condition)));
     $tab += $this->getSearchOptionsStats();
     $tab[150]['table'] = $this->getTable();
     $tab[150]['field'] = 'takeintoaccount_delay_stat';
     $tab[150]['name'] = __('Take into account time');
     $tab[150]['datatype'] = 'timestamp';
     $tab[150]['forcegroupby'] = true;
     $tab[150]['massiveaction'] = false;
     if (Session::haveRightsOr(self::$rightname, array(self::READALL, self::READASSIGN, self::OWN))) {
         $tab['linktickets'] = _n('Linked ticket', 'Linked tickets', Session::getPluralNumber());
         $tab[40]['table'] = 'glpi_tickets_tickets';
         $tab[40]['field'] = 'tickets_id_1';
         $tab[40]['name'] = __('All linked tickets');
         $tab[40]['massiveaction'] = false;
         $tab[40]['forcegroupby'] = true;
         $tab[40]['searchtype'] = 'equals';
         $tab[40]['joinparams'] = array('jointype' => 'item_item');
         $tab[40]['additionalfields'] = array('tickets_id_2');
         $tab[47]['table'] = 'glpi_tickets_tickets';
         $tab[47]['field'] = 'tickets_id_1';
         $tab[47]['name'] = __('Duplicated tickets');
         $tab[47]['massiveaction'] = false;
         $tab[47]['searchtype'] = 'equals';
         $tab[47]['joinparams'] = array('jointype' => 'item_item', 'condition' => "AND NEWTABLE.`link` = " . Ticket_Ticket::DUPLICATE_WITH);
         $tab[47]['datatype'] = 'dropdown';
         $tab[47]['forcegroupby'] = true;
         $tab[41]['table'] = 'glpi_tickets_tickets';
         $tab[41]['field'] = 'id';
         $tab[41]['name'] = __('Number of all linked tickets');
         $tab[41]['massiveaction'] = false;
         $tab[41]['datatype'] = 'count';
         $tab[41]['usehaving'] = true;
         $tab[41]['joinparams'] = array('jointype' => 'item_item');
         $tab[46]['table'] = 'glpi_tickets_tickets';
         $tab[46]['field'] = 'id';
         $tab[46]['name'] = __('Number of duplicated tickets');
         $tab[46]['massiveaction'] = false;
         $tab[46]['datatype'] = 'count';
         $tab[46]['usehaving'] = true;
         $tab[46]['joinparams'] = array('jointype' => 'item_item', 'condition' => "AND NEWTABLE.`link` = " . Ticket_Ticket::DUPLICATE_WITH);
         $tab += TicketTask::getSearchOptionsToAdd();
         $tab += $this->getSearchOptionsSolution();
         if (Session::haveRight('ticketcost', READ)) {
             $tab += TicketCost::getSearchOptionsToAdd();
         }
         $tab['problem'] = Problem::getTypeName(Session::getPluralNumber());
         $tab[141]['table'] = 'glpi_problems_tickets';
         $tab[141]['field'] = 'id';
         $tab[141]['name'] = _x('quantity', 'Number of problems');
         $tab[141]['forcegroupby'] = true;
         $tab[141]['usehaving'] = true;
         $tab[141]['datatype'] = 'count';
         $tab[141]['massiveaction'] = false;
         $tab[141]['joinparams'] = array('jointype' => 'child');
     }
     // Filter search fields for helpdesk
     if (!Session::isCron() && (!isset($_SESSION['glpiactiveprofile']['interface']) || $_SESSION['glpiactiveprofile']['interface'] == 'helpdesk')) {
         $tokeep = array('common', 'requester', 'satisfaction');
         if (Session::haveRightsOr('ticketvalidation', array_merge(TicketValidation::getValidateRights(), TicketValidation::getCreateRights()))) {
             $tokeep[] = 'validation';
         }
         $keep = false;
         foreach ($tab as $key => $val) {
             if (!is_array($val)) {
                 $keep = in_array($key, $tokeep);
             }
             if (!$keep) {
                 if (is_array($val)) {
                     $tab[$key]['nosearch'] = true;
                 }
             }
         }
         // last updater no search
         $tab[64]['nosearch'] = true;
     }
     return $tab;
 }
예제 #18
0
 /**
  * @see CommonDBTM::getSpecificMassiveActions()
  **/
 function getSpecificMassiveActions($checkitem = NULL)
 {
     $isadmin = static::canUpdate();
     $actions = parent::getSpecificMassiveActions($checkitem);
     if (TicketFollowup::canCreate() && $_SESSION['glpiactiveprofile']['interface'] == 'central') {
         $actions['add_followup'] = __('Add a new followup');
     }
     if (TicketTask::canCreate()) {
         $actions['add_task'] = __('Add a new task');
     }
     if (TicketValidation::canCreate()) {
         $actions['submit_validation'] = __('Approval request');
     }
     if (Session::haveRight("update_ticket", "1")) {
         $actions['add_actor'] = __('Add an actor');
         $actions['link_ticket'] = _x('button', 'Link tickets');
     }
     if (Session::haveRight('transfer', 'r') && Session::isMultiEntitiesMode() && Session::haveRight("update_ticket", "1")) {
         $actions['add_transfer_list'] = _x('button', 'Add to transfer list');
     }
     return $actions;
 }
예제 #19
0
파일: timeline.php 프로젝트: btry/glpi
You should have received a copy of the GNU General Public License
along with GLPI. If not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------
*/
include '../inc/includes.php';
header("Content-Type: text/html; charset=UTF-8");
Session::checkLoginUser();
if (!isset($_POST['action'])) {
    exit;
}
switch ($_POST['action']) {
    case "change_task_state":
        if (!isset($_POST['tasks_id'])) {
            exit;
        }
        $task = new TicketTask();
        $task->getFromDB(intval($_POST['tasks_id']));
        if (!in_array($task->fields['state'], array(0, Planning::INFO))) {
            echo $new_state = $task->fields['state'] == Planning::DONE ? Planning::TODO : Planning::DONE;
            $task->update(array('id' => intval($_POST['tasks_id']), 'tickets_id' => intval($_POST['tickets_id']), 'state' => $new_state));
        }
        break;
    case "viewsubitem":
        Html::header_nocache();
        if (!isset($_POST['type'])) {
            exit;
        }
        if (!isset($_POST['parenttype'])) {
            exit;
        }
        if (($item = getItemForItemtype($_POST['type'])) && ($parent = getItemForItemtype($_POST['parenttype']))) {
예제 #20
0
 /**
  * Transfer task categories for specified tickets
  *
  * @param $ID original ticket ID
  * @param $newID new ticket ID
  **/
 function transferTicketTaskCategory($ID, $newID)
 {
     global $DB;
     $task = new TicketTask();
     $query = "SELECT *\n                FROM `glpi_tickettasks`\n                WHERE `tickets_id` = '{$ID}'";
     if ($result = $DB->query($query)) {
         if ($DB->numrows($result) != 0) {
             while ($data = $DB->fetch_assoc($result)) {
                 $input = array();
                 if ($data['taskcategories_id'] > 0) {
                     $categ = new TaskCategory();
                     if ($categ->getFromDB($data['taskcategories_id'])) {
                         $inputcat['entities_id'] = $this->to;
                         $inputcat['completename'] = $categ->fields['completename'];
                         $catid = $categ->findID($inputcat);
                         if ($catid < 0) {
                             $catid = $categ->import($inputcat);
                         }
                         $input['id'] = $data['id'];
                         $input['tickets_id'] = $ID;
                         $input['taskcategories_id'] = $catid;
                         $task->update($input);
                     }
                 }
             }
         }
     }
 }
 /**
  * Populate the planning with planned ticket tasks
  *
  * @param $options options array must contains :
  *    - who ID of the user (0 = undefined)
  *    - who_group ID of the group of users (0 = undefined)
  *    - begin Date
  *    - end Date
  *
  * @return array of planning item
  **/
 static function populatePlanning($options = array())
 {
     global $DB, $CFG_GLPI;
     $interv = array();
     if (!isset($options['begin']) || !isset($options['begin']) || !isset($options['begin']) || !isset($options['end'])) {
         return $interv;
     }
     $who = $options['who'];
     $who_group = $options['who_group'];
     $begin = $options['begin'];
     $end = $options['end'];
     // Get items to print
     $ASSIGN = "";
     if ($who_group === "mine") {
         if (count($_SESSION["glpigroups"])) {
             $groups = implode("','", $_SESSION['glpigroups']);
             $ASSIGN = "`users_id` IN (SELECT DISTINCT `users_id`\n                                      FROM `glpi_groups_users`\n                                      WHERE `groups_id` IN ('{$groups}'))\n                                            AND ";
         } else {
             // Only personal ones
             $ASSIGN = "`users_id` = '{$who}'\n                       AND ";
         }
     } else {
         if ($who > 0) {
             $ASSIGN = "`users_id` = '{$who}'\n                       AND ";
         }
         if ($who_group > 0) {
             $ASSIGN = "`users_id` IN (SELECT `users_id`\n                                      FROM `glpi_groups_users`\n                                      WHERE `groups_id` = '{$who_group}')\n                                            AND ";
         }
     }
     if (empty($ASSIGN)) {
         $ASSIGN = "`users_id` IN (SELECT DISTINCT `glpi_profiles_users`.`users_id`\n                                   FROM `glpi_profiles`\n                                   LEFT JOIN `glpi_profiles_users`\n                                     ON (`glpi_profiles`.`id` = `glpi_profiles_users`.`profiles_id`)\n                                   WHERE `glpi_profiles`.`interface` = 'central' " . getEntitiesRestrictRequest("AND", "glpi_profiles_users", '', $_SESSION["glpiactive_entity"], 1);
         $ASSIGN .= ") AND ";
     }
     $query = "SELECT *\n                FROM `glpi_ticketplannings`\n                WHERE {$ASSIGN}\n                      '{$begin}' < `end`\n                      AND '{$end}' > `begin`\n                ORDER BY `begin`";
     $result = $DB->query($query);
     $fup = new TicketTask();
     $job = new Ticket();
     $interv = array();
     if ($DB->numrows($result) > 0) {
         for ($i = 0; $data = $DB->fetch_array($result); $i++) {
             if ($fup->getFromDB($data["tickettasks_id"])) {
                 if ($job->getFromDBwithData($fup->fields["tickets_id"], 0)) {
                     // Do not check entity here because webcal used non authenticated access
                     //                  if (haveAccessToEntity($job->fields["entities_id"])) {
                     $interv[$data["begin"] . "\$\$\$" . $i]["tickettasks_id"] = $data["tickettasks_id"];
                     $interv[$data["begin"] . "\$\$\$" . $i]["state"] = $data["state"];
                     $interv[$data["begin"] . "\$\$\$" . $i]["tickets_id"] = $fup->fields["tickets_id"];
                     $interv[$data["begin"] . "\$\$\$" . $i]["users_id"] = $data["users_id"];
                     $interv[$data["begin"] . "\$\$\$" . $i]["id"] = $data["id"];
                     if (strcmp($begin, $data["begin"]) > 0) {
                         $interv[$data["begin"] . "\$\$\$" . $i]["begin"] = $begin;
                     } else {
                         $interv[$data["begin"] . "\$\$\$" . $i]["begin"] = $data["begin"];
                     }
                     if (strcmp($end, $data["end"]) < 0) {
                         $interv[$data["begin"] . "\$\$\$" . $i]["end"] = $end;
                     } else {
                         $interv[$data["begin"] . "\$\$\$" . $i]["end"] = $data["end"];
                     }
                     $interv[$data["begin"] . "\$\$\$" . $i]["name"] = $job->fields["name"];
                     $interv[$data["begin"] . "\$\$\$" . $i]["content"] = resume_text($job->fields["content"], $CFG_GLPI["cut"]);
                     $interv[$data["begin"] . "\$\$\$" . $i]["device"] = $job->hardwaredatas ? $job->hardwaredatas->getName() : '';
                     $interv[$data["begin"] . "\$\$\$" . $i]["status"] = $job->fields["status"];
                     $interv[$data["begin"] . "\$\$\$" . $i]["priority"] = $job->fields["priority"];
                     //                  }
                 }
             }
         }
     }
     return $interv;
 }