/** function buildTicket - Builds,and returns, the major structure of the ticket to be entered.
  *
  * @param $i mail ID
  * @param $options array options
  *
  * @return ticket fields array
  */
 function buildTicket($i, $options = array())
 {
     $play_rules = isset($options['play_rules']) && $options['play_rules'];
     $head = $this->getHeaders($i);
     // Get Header Info Return Array Of Headers
     // **Key Are (subject,to,toOth,toNameOth,from,fromName)
     $tkt = array();
     $tkt['_blacklisted'] = false;
     // Detect if it is a mail reply
     $glpi_message_match = "/GLPI-([0-9]+)\\.[0-9]+\\.[0-9]+@\\w*/";
     // Check if email not send by GLPI : if yes -> blacklist
     if (preg_match($glpi_message_match, $head['message_id'], $match)) {
         $tkt['_blacklisted'] = true;
         return $tkt;
     }
     // max size = 0 : no import attachments
     if ($this->fields['filesize_max'] > 0) {
         if (is_writable(GLPI_DOC_DIR . "/_tmp/")) {
             $_FILES = $this->getAttached($i, GLPI_DOC_DIR . "/_tmp/", $this->fields['filesize_max']);
         } else {
             logInFile('mailgate', GLPI_DOC_DIR . "/_tmp/ is not writable");
         }
     }
     //  Who is the user ?
     $tkt['_users_id_requester'] = User::getOrImportByEmail($head['from']);
     $tkt["_users_id_requester_notif"]['use_notification'] = 1;
     if (!$tkt['_users_id_requester']) {
         $tkt["_users_id_requester_notif"]['alternative_email'] = $head['from'];
     }
     // Add to and cc as additional observer if user found
     if (count($head['ccs'])) {
         foreach ($head['ccs'] as $cc) {
             if ($cc != $head['from'] && strcasecmp($cc, $this->fields['name']) && ($tmp = User::getOrImportByEmail($cc)) > 0) {
                 $tkt['_additional_observers'][] = array('users_id' => $tmp, 'use_notification' => 1);
             }
         }
     }
     if (count($head['tos'])) {
         foreach ($head['tos'] as $to) {
             if ($to != $head['from'] && strcasecmp($to, $this->fields['name']) && ($tmp = User::getOrImportByEmail($to, false)) > 0) {
                 $tkt['_additional_observers'][] = array('users_id' => $tmp, 'use_notification' => 1);
             }
         }
     }
     // Auto_import
     $tkt['_auto_import'] = 1;
     // For followup : do not check users_id = login user
     $tkt['_do_not_check_users_id'] = 1;
     $body = $this->getBody($i);
     // Do it before using charset variable
     $head['subject'] = $this->decodeMimeString($head['subject']);
     $tkt['_head'] = $head;
     if (!empty($this->charset) && !$this->body_converted) {
         $body = encodeInUtf8($body, $this->charset);
         $this->body_converted = true;
     }
     if (!seems_utf8($body)) {
         $tkt['content'] = encodeInUtf8($body);
     } else {
         $tkt['content'] = $body;
     }
     // Add message from getAttached
     if ($this->addtobody) {
         $tkt['content'] .= $this->addtobody;
     }
     // See In-Reply-To field
     if (isset($head['in_reply_to'])) {
         if (preg_match($glpi_message_match, $head['in_reply_to'], $match)) {
             $tkt['tickets_id'] = intval($match[1]);
         }
     }
     // See in References
     if (!isset($tkt['tickets_id']) && isset($head['references'])) {
         if (preg_match($glpi_message_match, $head['references'], $match)) {
             $tkt['tickets_id'] = intval($match[1]);
         }
     }
     // See in title
     if (!isset($tkt['tickets_id']) && preg_match('/\\[GLPI #(\\d+)\\]/', $head['subject'], $match)) {
         $tkt['tickets_id'] = intval($match[1]);
     }
     // Found ticket link
     if (isset($tkt['tickets_id'])) {
         // it's a reply to a previous ticket
         $job = new Ticket();
         // Check if ticket  exists and users_id exists in GLPI
         /// TODO check if users_id have right to add a followup to the ticket
         if ($job->getFromDB($tkt['tickets_id']) && $job->fields['status'] != 'closed' && ($tkt['_users_id_requester'] > 0 || Ticket_User::isAlternateEmailForTicket($tkt['tickets_id'], $head['from']))) {
             $content = explode("\n", $tkt['content']);
             $tkt['content'] = "";
             $first_comment = true;
             $to_keep = array();
             foreach ($content as $ID => $val) {
                 if (isset($val[0]) && $val[0] == '>') {
                     // Delete line at the top of the first comment
                     if ($first_comment) {
                         $first_comment = false;
                         if (isset($to_keep[$ID - 1])) {
                             unset($to_keep[$ID - 1]);
                         }
                     }
                 } else {
                     $to_keep[$ID] = $ID;
                 }
             }
             foreach ($to_keep as $ID) {
                 $tkt['content'] .= $content[$ID] . "\n";
             }
             // Do not play rules for followups : WRONG : play rules only for refuse options
             //$play_rules = false;
         } else {
             // => to handle link in Ticket->post_addItem()
             $tkt['_linkedto'] = $tkt['tickets_id'];
             unset($tkt['tickets_id']);
         }
     }
     $tkt['name'] = $this->textCleaner($head['subject']);
     if (!isset($tkt['tickets_id'])) {
         // Which entity ?
         //$tkt['entities_id']=$this->fields['entities_id'];
         //$tkt['Subject']= $head['subject'];   // not use for the moment
         // Medium
         $tkt['urgency'] = "3";
         // No hardware associated
         $tkt['itemtype'] = "";
         // Mail request type
     } else {
         // Reopen if needed
         $tkt['add_reopen'] = 1;
     }
     $tkt['requesttypes_id'] = RequestType::getDefault('mail');
     $tkt['content'] = clean_cross_side_scripting_deep(html_clean($tkt['content']));
     if ($play_rules) {
         $rule_options['ticket'] = $tkt;
         $rule_options['headers'] = $head;
         $rule_options['mailcollector'] = $options['mailgates_id'];
         $rule_options['_users_id_requester'] = $tkt['_users_id_requester'];
         $rulecollection = new RuleMailCollectorCollection();
         $output = $rulecollection->processAllRules(array(), array(), $rule_options);
         // New ticket : compute all
         if (!isset($tkt['tickets_id'])) {
             foreach ($output as $key => $value) {
                 $tkt[$key] = $value;
             }
         } else {
             // Followup only copy refuse data
             $tobecopied = array('_refuse_email_no_response', '_refuse_email_with_response');
             foreach ($tobecopied as $val) {
                 if (isset($output[$val])) {
                     $tkt[$val] = $output[$val];
                 }
             }
         }
     }
     $tkt = addslashes_deep($tkt);
     return $tkt;
 }