function createTicket($mid)
 {
     global $ost;
     if (!($mailinfo = $this->getHeaderInfo($mid))) {
         return false;
     }
     // TODO: If the content-type of the message is 'message/rfc822',
     // then this is a message with the forwarded message as the
     // attachment. Download the body and pass it along to the mail
     // parsing engine.
     $info = Mail_Parse::splitHeaders($mailinfo['header']);
     if (strtolower($info['Content-Type']) == 'message/rfc822') {
         if ($wrapped = $this->getPart($mid, 'message/rfc822')) {
             require_once INCLUDE_DIR . 'api.tickets.php';
             // Simulate piping the contents into the system
             $api = new TicketApiController();
             $parser = new EmailDataParser();
             if ($data = $parser->parse($wrapped)) {
                 return $api->processEmail($data);
             }
         }
         // If any of this fails, create the ticket as usual
     }
     //Is the email address banned?
     if ($mailinfo['email'] && TicketFilter::isBanned($mailinfo['email'])) {
         //We need to let admin know...
         $ost->logWarning(_S('Ticket denied'), sprintf(_S('Banned email — %s'), $mailinfo['email']), false);
         return true;
         //Report success (moved or delete)
     }
     // Parse MS TNEF emails
     if (($struct = imap_fetchstructure($this->mbox, $mid)) && ($attachments = $this->getAttachments($struct))) {
         foreach ($attachments as $i => $info) {
             if (0 === strcasecmp('application/ms-tnef', $info['type'])) {
                 try {
                     $data = $this->decode(imap_fetchbody($this->mbox, $mid, $info['index']), $info['encoding']);
                     $tnef = new TnefStreamParser($data);
                     $this->tnef = $tnef->getMessage();
                     // No longer considered an attachment
                     unset($attachments[$i]);
                     // There should only be one of these
                     break;
                 } catch (TnefException $ex) {
                     // Noop -- winmail.dat remains an attachment
                 }
             }
         }
     }
     $vars = $mailinfo;
     $vars['name'] = $mailinfo['name'];
     $vars['subject'] = $mailinfo['subject'] ?: '[No Subject]';
     $vars['emailId'] = $mailinfo['emailId'] ?: $this->getEmailId();
     $vars['to-email-id'] = $mailinfo['emailId'] ?: 0;
     $vars['flags'] = new ArrayObject();
     if ($this->isBounceNotice($mid)) {
         // Fetch the original References and assign to 'references'
         if ($headers = $this->getOriginalMessageHeaders($mid)) {
             $vars['references'] = $headers['references'];
             $vars['in-reply-to'] = @$headers['in-reply-to'] ?: null;
         }
         // Fetch deliver status report
         $vars['message'] = $this->getDeliveryStatusMessage($mid) ?: $this->getBody($mid);
         $vars['thread-type'] = 'N';
         $vars['flags']['bounce'] = true;
     } else {
         $vars['message'] = $this->getBody($mid);
         $vars['flags']['bounce'] = TicketFilter::isBounce($info);
     }
     //Missing FROM name  - use email address.
     if (!$vars['name']) {
         list($vars['name']) = explode('@', $vars['email']);
     }
     if ($ost->getConfig()->useEmailPriority()) {
         $vars['priorityId'] = $this->getPriority($mid);
     }
     $ticket = null;
     $newticket = true;
     $errors = array();
     $seen = false;
     // Use the settings on the thread entry on the ticket details
     // form to validate the attachments in the email
     $tform = TicketForm::objects()->one()->getForm();
     $messageField = $tform->getField('message');
     $fileField = $messageField->getWidget()->getAttachments();
     // Fetch attachments if any.
     if ($messageField->isAttachmentsEnabled()) {
         // Include TNEF attachments in the attachments list
         if ($this->tnef) {
             foreach ($this->tnef->attachments as $at) {
                 $attachments[] = array('cid' => @$at->AttachContentId ?: false, 'data' => $at, 'size' => @$at->DataSize ?: null, 'type' => @$at->AttachMimeTag ?: false, 'name' => $at->getName());
             }
         }
         $vars['attachments'] = array();
         foreach ($attachments as $a) {
             $file = array('name' => $a['name'], 'type' => $a['type']);
             if (@$a['data'] instanceof TnefAttachment) {
                 $file['data'] = $a['data']->getData();
             } else {
                 // only fetch the body if necessary
                 $self = $this;
                 $file['data'] = function () use($self, $mid, $a) {
                     return $self->decode(imap_fetchbody($self->mbox, $mid, $a['index']), $a['encoding']);
                 };
             }
             // Include the Content-Id if specified (for inline images)
             $file['cid'] = isset($a['cid']) ? $a['cid'] : false;
             // Validate and save immediately
             try {
                 $file['id'] = $fileField->uploadAttachment($file);
             } catch (FileUploadError $ex) {
                 $file['error'] = $file['name'] . ': ' . $ex->getMessage();
             }
             $vars['attachments'][] = $file;
         }
     }
     // Allow signal handlers to interact with the message decoding
     Signal::send('mail.processed', $this, $vars);
     $seen = false;
     if (($thread = ThreadEntry::lookupByEmailHeaders($vars, $seen)) && ($t = $thread->getTicket()) && ($vars['staffId'] || !$t->isClosed() || $t->isReopenable()) && ($message = $thread->postEmail($vars))) {
         if (!$message instanceof ThreadEntry) {
             // Email has been processed previously
             return $message;
         }
         $ticket = $message->getTicket();
     } elseif ($seen) {
         // Already processed, but for some reason (like rejection), no
         // thread item was created. Ignore the email
         return true;
     } elseif ($ticket = Ticket::create($vars, $errors, 'Email')) {
         $message = $ticket->getLastMessage();
     } else {
         //Report success if the email was absolutely rejected.
         if (isset($errors['errno']) && $errors['errno'] == 403) {
             // Never process this email again!
             ThreadEntry::logEmailHeaders(0, $vars['mid']);
             return true;
         }
         // Log an error to the system logs
         $mailbox = Email::lookup($vars['emailId']);
         $ost->logError(_S('Mail Processing Exception'), sprintf(_S("Mailbox: %s | Error(s): %s"), $mailbox->getEmail(), print_r($errors, true)), false);
         // Indicate failure of mail processing
         return null;
     }
     return $ticket;
 }
Exemple #2
0
function createTicketByWebService($xml)
{
    global $logFilePath;
    try {
        if (!empty($xml)) {
            $nodes = $xml->xpath('/contacts/contact');
        } else {
            logErrors("The xml file can not be loaded ");
        }
        for ($i = 0; $i < count($nodes); $i++) {
            // echo json_encode($nodes[$i]);
            $data = array();
            // $data['recipients'] = array();
            $data['subject'] = removeLineBreaker($nodes[$i]->title);
            if (empty(removeLineBreaker($nodes[$i]->title))) {
                if (!empty(removeLineBreaker($nodes[$i]->crmsubject2_text))) {
                    $data['subject'] = removeLineBreaker($nodes[$i]->crmsubject2_text);
                } else {
                    $data['subject'] = "no title";
                }
            }
            $data['header'] = "";
            // $data['mid'] = 1;
            $data['source'] = "Web";
            $data['topicId'] = 2;
            $data['priorityId'] = 2;
            $data['crm_contact_id'] = $nodes[$i]->attributes()->id;
            // $data['flags'] = new ArrayObject();
            $data['email'] = trim(removeLineBreaker($nodes[$i]->email));
            if (empty($data['email'])) {
                $data['email'] = "*****@*****.**";
            }
            $data['phone'] = removeLineBreaker($nodes[$i]->phone);
            if (empty($data['phone'])) {
                $data['phone'] = "";
            }
            $data['name'] = trim(removeLineBreaker($nodes[$i]->name));
            if (empty($data['name'])) {
                $data['name'] = "Anonymous User";
            }
            $data['orderNumber'] = trim(removeLineBreaker($nodes[$i]->ordernumber));
            $data['ordernumber'] = trim(removeLineBreaker($nodes[$i]->ordernumber));
            $data['filenumber'] = trim(removeLineBreaker($nodes[$i]->filenumber));
            $data['cvr'] = trim(removeLineBreaker($nodes[$i]->cvr));
            $data['CVR'] = trim(removeLineBreaker($nodes[$i]->cvr));
            $data['message'] = removeLineBreaker($nodes[$i]->content);
            $data['companyName'] = removeLineBreaker($nodes[$i]->companyname);
            $data['company'] = removeLineBreaker($nodes[$i]->companyname);
            $data['business_form_id'] = removeLineBreaker($nodes[$i]->business_form_id);
            $data['activityCode'] = removeLineBreaker($nodes[$i]->activitycode);
            $data['activityDescription'] = removeLineBreaker($nodes[$i]->activitydescription);
            $data['useragent'] = removeLineBreaker($nodes[$i]->useragent);
            $crmsubject1_id = trim(removeLineBreaker($nodes[$i]->crmsubject_id));
            if (is_numeric($crmsubject1_id)) {
                $data['CRM_filter_subject1'] = removeLineBreaker($nodes[$i]->crmsubject_text);
                $data['crmsubject1_id'] = intval($crmsubject1_id);
                $data['crmsubject1_text'] = removeLineBreaker($nodes[$i]->crmsubject_text);
            } else {
                die("crmsubject1_id is not numeric");
            }
            $crmsubject2_id = trim(removeLineBreaker($nodes[$i]->crmsubject2_id));
            if (is_numeric($crmsubject2_id)) {
                $data['CRM_filter_subject2'] = removeLineBreaker($nodes[$i]->crmsubject2_text);
                $data['crmsubject2_id'] = intval($crmsubject2_id);
                $data['crmsubject2_text'] = removeLineBreaker($nodes[$i]->crmsubject2_text);
            } else {
                die("crmsubject2_id is not numeric");
            }
            // $data['flags']['bounce'] = true;
            $user = null;
            $acct = null;
            if (!$user && $data['email']) {
                $user = User::lookupByEmail($data['email']);
            }
            if (!$user) {
                $user_form = UserForm::getUserForm()->getForm($data);
                if (!($user = User::fromVars($user_form->getClean()))) {
                    echo 'Unable to register account.';
                }
                if (!($acct = ClientAccount::createForUser($user))) {
                    echo 'Internal error. Unable to create new account';
                }
            }
            $fileContent = $nodes[$i]->files->file;
            $data['fileContent'] = $fileContent;
            $tform = TicketForm::objects()->one()->getForm();
            $messageField = $tform->getField('message');
            $fileField = $messageField->getWidget()->getAttachments();
            for ($j = 0; $j < count($fileContent); $j++) {
                $fileId = $fileContent[$j]->attributes()->id;
                $file['name'] = $fileContent[$j]->name;
                $file['type'] = $fileContent[$j]->mime;
                $file['encoding'] = 'base64';
                // $file['cid'] = false;
                $url = "https://w2l.dk" . $fileContent[$j]->url;
                // logErrors("A test");
                // $url = $fileContent[$j]->url;
                // $file['data'] = base64_encode(file_get_contents($url));
                if ($file['data'] = getFileContentsSSL($url)) {
                    $timestamp = date("Y-m-d_H:i:s");
                    // if(!file_put_contents(CLIENTINC_DIR.'erstFile/'.$timestamp.$file['name'], $file['data']))
                    //     logErrors("not able to store the file");
                    try {
                        $storeCRMFile = "/var/www/html/erstFile/" . $timestamp . $file['name'];
                        echo $storeCRMFile;
                        file_put_contents("/var/www/html/erstFile/" . $timestamp . $file['name'], $file['data']);
                    } catch (Exception $e) {
                        logErrors('Caught exception: ', $e->getMessage(), "\n");
                    }
                } else {
                    logErrors("The file url is not valid");
                }
                // try {
                //     $file['id'] = $fileField->uploadAttachment($file);
                // }
                // catch (FileUploadError $ex) {
                //     $file['error'] = $file['name'] . ': ' . $ex->getMessage();
                //     echo $file['error'];
                // }
                $data['attachments'][] = $file;
                // echo $file['data'];
                // echo "<br/>";
            }
            // echo "22222";
            // echo json_encode($data);
            if (Ticket::lookupForContactId($data['crm_contact_id'])) {
                $api = new TicketApiController();
                $api->createTicket($data);
                echo "ticket has been generated successfully <br/>";
                if (DELETE_ERST_SERVICE_QUEUE) {
                    deleteContactsFromQueue($data['crm_contact_id']);
                } else {
                    logErrors("please go to include/ost-config to make the DELETE_ERST_SERVICE_QUEUE to true");
                }
            } else {
                logErrors("ticket with id " . $data['crm_contact_id'] . " has already exists");
            }
        }
    } catch (Exception $e) {
        echo 'Caught exception: ', $e->getMessage(), "\n";
    }
}