Пример #1
0
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function store()
 {
     $input = Input::all();
     $validation = Validator::make($input, Ticket::$rules);
     if ($validation->passes()) {
         $this->ticket->create($input);
         return Redirect::route('tickets.index');
     }
     return Redirect::route('tickets.create')->withInput()->withErrors($validation)->with('message', 'There were validation errors.');
 }
Пример #2
0
 public function create($request)
 {
     $req = $request->getParameters();
     $response = new ViewResponse('assist/ticket');
     if (trim($req['bug']) != '') {
         if (Session::isActive()) {
             $user_id = Session::get()->id;
         } else {
             if (trim($req['email']) != '') {
                 $user_id = $req['email'];
             } else {
                 $user_id = 0;
             }
         }
         if (!empty(Ticket::find('all', ['conditions' => ['ip = ? AND timestamp < ' . (Utils::tps() + 60), $_SERVER['REMOTE_ADDR']]]))) {
             $r = $this->index($request);
             $r->addMessage(ViewMessage::error('Trop d\'envois avec la même IP en une minute, réssayez plus tard.'));
             return $r;
         }
         $ticket = Ticket::create(array('user_id' => $user_id, 'description' => $req['bug'], 'timestamp' => time(), 'ip' => $_SERVER['REMOTE_ADDR']));
         StaffNotification::createNotif('ticket', $user_id, null, $ticket->id);
         $ticket_id = $ticket->id;
         $response->addMessage(ViewMessage::success('Envoyé ! Vous serez notifié de l\'avancement par E-Mail ou Message Privé (Ticket #' . $ticket_id . ')'));
         /*$username = (Session::isActive()) ? Session::get()->username : '******';
         		$notif = new PushoverNotification();
         		$notif->setMessage('Nouveau ticket de '.$username);
         		$notif->setReceiver('all');
         		$notif->setExtraParameter('url', 'http://dreamvids.fr'.WEBROOT.'admin/tickets');
         		$notif->send();*/
     } else {
         $response->addMessage(ViewMessage::error('Merci de nous décrire votre problème.'));
     }
     return $response;
 }
Пример #3
0
 public function create($request)
 {
     $req = $request->getParameters();
     $response = new ViewResponse('assist/ticket');
     if (trim($req['bug']) != '') {
         if (Session::isActive()) {
             $user_id = Session::get()->id;
         } else {
             if (trim($req['email']) != '') {
                 $user_id = $req['email'];
             } else {
                 $user_id = 0;
             }
         }
         $ticket = Ticket::create(array('user_id' => $user_id, 'description' => $req['bug'], 'timestamp' => time(), 'ip' => $_SERVER['REMOTE_ADDR']));
         $ticket_id = $ticket->id;
         $response->addMessage(ViewMessage::success('Envoyé ! Vous serez notifié de l\'avancement par E-Mail ou Message Privé (Ticket #' . $ticket_id . ')'));
         /*$username = (Session::isActive()) ? Session::get()->username : '******';
         		$notif = new PushoverNotification();
         		$notif->setMessage('Nouveau ticket de '.$username);
         		$notif->setReceiver('all');
         		$notif->setExtraParameter('url', 'http://dreamvids.fr'.WEBROOT.'admin/tickets');
         		$notif->send();*/
     } else {
         $response->addMessage(ViewMessage::error('Merci de nous décrire votre problème.'));
     }
     return $response;
 }
Пример #4
0
 public function store(Request $request)
 {
     $input = $request->all();
     Ticket::create($input);
     Session::flash('flash_message', 'Ticket successfully added!');
     return redirect()->route('tickets.index');
 }
Пример #5
0
 function create()
 {
     if ($_POST) {
         $config['upload_path'] = './files/media/';
         $config['encrypt_name'] = TRUE;
         $config['allowed_types'] = '*';
         $this->load->library('upload', $config);
         $this->load->helper('notification');
         unset($_POST['userfile']);
         unset($_POST['file-name']);
         unset($_POST['send']);
         unset($_POST['_wysihtml5_mode']);
         unset($_POST['files']);
         $settings = Setting::first();
         $client = Client::find_by_id($this->client->id);
         $user = User::find_by_id($settings->ticket_default_owner);
         $_POST['from'] = $client->firstname . ' ' . $client->lastname . ' - ' . $client->email;
         $_POST['company_id'] = $client->company->id;
         $_POST['client_id'] = $client->id;
         $_POST['user_id'] = $settings->ticket_default_owner;
         $_POST['queue_id'] = $settings->ticket_default_queue;
         $_POST['type_id'] = $settings->ticket_default_type;
         $_POST['status'] = $settings->ticket_default_status;
         $_POST['created'] = time();
         $_POST['subject'] = htmlspecialchars($_POST['subject']);
         $ticket_reference = Setting::first();
         $_POST['reference'] = $ticket_reference->ticket_reference;
         $ticket = Ticket::create($_POST);
         $new_ticket_reference = $_POST['reference'] + 1;
         $ticket_reference->update_attributes(array('ticket_reference' => $new_ticket_reference));
         if (!$this->upload->do_upload()) {
             $error = $this->upload->display_errors('', ' ');
             $this->session->set_flashdata('message', 'error:' . $error);
         } else {
             $data = array('upload_data' => $this->upload->data());
             $attributes = array('ticket_id' => $ticket->id, 'filename' => $data['upload_data']['orig_name'], 'savename' => $data['upload_data']['file_name']);
             $attachment = TicketHasAttachment::create($attributes);
         }
         if (!$ticket) {
             $this->session->set_flashdata('message', 'error:' . $this->lang->line('messages_create_ticket_error'));
             redirect('ctickets');
         } else {
             $this->session->set_flashdata('message', 'success:' . $this->lang->line('messages_create_ticket_success'));
             if (isset($user->email) && isset($ticket->reference)) {
                 send_ticket_notification($user->email, '[Ticket#' . $ticket->reference . '] - ' . $_POST['subject'], $_POST['text'], $ticket->id);
             }
             if (isset($client->email) && isset($ticket->reference)) {
                 send_ticket_notification($client->email, '[Ticket#' . $ticket->reference . '] - ' . $_POST['subject'], $_POST['text'], $ticket->id);
             }
             redirect('ctickets/view/' . $ticket->id);
         }
     } else {
         $this->theme_view = 'modal';
         $this->view_data['title'] = $this->lang->line('application_create_ticket');
         $this->view_data['form_action'] = 'ctickets/create';
         $this->content_view = 'tickets/client_views/_ticket';
     }
 }
Пример #6
0
 function createUpgradedTicket()
 {
     global $cfg;
     $i18n = new Internationalization();
     $vars = $i18n->getTemplate('templates/ticket/upgraded.yaml')->getData();
     $vars['deptId'] = $cfg->getDefaultDeptId();
     //Create a ticket to make the system warm and happy.
     $errors = array();
     Ticket::create($vars, $errors, 'api', false, false);
 }
Пример #7
0
 public function run()
 {
     $faker = Faker::create();
     foreach (range(1, 5) as $index) {
         Ticket::create(['title' => $faker->sentence(), 'description' => $faker->sentence(), 'priority_id' => '1', 'status_id' => '1', 'owner_id' => '1', 'replies' => '0']);
     }
     foreach (range(1, 5) as $index) {
         Ticket::create(['title' => $faker->sentence(), 'description' => $faker->sentence(), 'priority_id' => '1', 'status_id' => '1', 'owner_id' => '2', 'replies' => '0']);
     }
 }
Пример #8
0
 public function run()
 {
     $faker = Faker\Factory::create();
     DB::table('tickets')->truncate();
     DB::table('departments')->truncate();
     Department::create(array('name' => 'Support'));
     Department::create(array('name' => 'Sales'));
     for ($i = 0; $i < 60; $i++) {
         Ticket::create(array('user_id' => $faker->randomNumber(1, 20), 'department_id' => $faker->randomNumber(1, 2), 'title' => $faker->sentence, 'message' => $faker->paragraph, 'status' => $faker->randomElement(array('Open', 'Closed'))));
     }
 }
Пример #9
0
 public static function updateMessage($id, $text, $ticket = false)
 {
     $msg = new Message(array('id' => $id, 'text' => $text));
     $msg->update();
     $tick_no = null;
     if ($ticket) {
         $wlticket = new Ticket(array('message_id' => $id, 'title' => 'NIEUW', 'text' => $text, 'status_id' => 1));
         $tick_no = $wlticket->create();
     }
     if ($tick_no) {
         $msg->setTicket($tick_no);
     }
     return array('id' => $msg->id);
 }
Пример #10
0
 function createTicket($data)
 {
     # Pull off some meta-data
     $alert = $data['alert'] ? $data['alert'] : true;
     $autorespond = $data['autorespond'] ? $data['autorespond'] : true;
     $data['source'] = $data['source'] ? $data['source'] : 'API';
     # Create the ticket with the data (attempt to anyway)
     $errors = array();
     $ticket = Ticket::create($data, $errors, $data['source'], $autorespond, $alert);
     # Return errors (?)
     if (count($errors)) {
         if (isset($errors['errno']) && $errors['errno'] == 403) {
             return $this->exerr(403, 'Ticket denied');
         } else {
             return $this->exerr(400, "Unable to create new ticket: validation errors:\n" . Format::array_implode(": ", "\n", $errors));
         }
     } elseif (!$ticket) {
         return $this->exerr(500, "Unable to create new ticket: unknown error");
     }
     return $ticket;
 }
Пример #11
0
 function create($format)
 {
     $this->requireApiKey();
     # Parse request body
     $data = $this->getRequest($format);
     if ($format == "xml") {
         $data = $data["ticket"];
     }
     # Pull off some meta-data
     $alert = $data['alert'] ? $data['alert'] : true;
     $autorespond = $data['autorespond'] ? $data['autorespond'] : true;
     $source = $data['source'] ? $data['source'] : 'API';
     $attachments = $data['attachments'] ? $data['attachments'] : array();
     # TODO: Handle attachment encoding (base64)
     foreach ($attachments as $filename => &$info) {
         if ($info["encoding"] == "base64") {
             # XXX: May fail on large inputs. See
             #      http://us.php.net/manual/en/function.base64-decode.php#105512
             if (!($info["data"] = base64_decode($info["data"], true))) {
                 Http::response(400, sprintf("%s: Poorly encoded base64 data", $filename));
             }
         }
         $info['size'] = strlen($info['data']);
     }
     # Create the ticket with the data (attempt to anyway)
     $errors = array();
     $ticket = Ticket::create($data, $errors, $source, $autorespond, $alert);
     # Return errors (?)
     if (count($errors)) {
         Http::response(400, "Unable to create new ticket: validation errors:\n" . Format::array_implode(": ", "\n", $errors));
     } elseif (!$ticket) {
         Http::response(500, "Unable to create new ticket: unknown error");
     }
     # Save attachment(s)
     foreach ($attachments as &$info) {
         $ticket->saveAttachment($info, $ticket->getLastMsgId(), "M");
     }
     # All done. Return HTTP/201 --> Created
     Http::response(201, $ticket->getExtId());
 }
Пример #12
0
/**
 * This function call when a post request send .If that request is a valid addTicket request, new ticket will added,
 * Else redirect user to not found page or echo error message;
 * @param WP_USER $user
 * @return string
 */
function post_request($user)
{
    if (!isset($_POST["requestType"]) || $_POST["requestType"] != "addTicket" && $_POST["requestType"] != "addTicketAnswer") {
        header("Location: " . NOT_FOUND_URL);
        exit;
    }
    $const_array = array("applicant_id" => $user->ID, "status" => 0, "attachments" => $_POST["upfile"], "title" => $_POST["title"], "content" => $_POST["message"], "department" => $_POST["department"], "other" => "priority:" . $_POST["priority"] . "|", "related_order" => get_id($_POST["order"]));
    if (isset($_POST['relatedTicket'])) {
        $related_ticket = $_POST['relatedTicket'];
        $const_array = array_merge($const_array, array("related_ticket" => get_id($related_ticket)));
    }
    if ($_POST["requestType"] == "addTicket") {
        foreach ($const_array as $key => $value) {
            if (empty($value) && $value !== 0 && $key !== "attachments" && $key !== "order" && $key !== "related_ticket") {
                return "لطفا متنی تایپ کنید!" . "<br>";
            }
        }
    } else {
        if (empty($_POST["message"])) {
            return "متن پاسخ نیم تواند خالی باشد";
        }
    }
    $ticket = new Ticket($const_array);
    if ($ticket->create()) {
        if ($_POST["requestType"] == "addTicket") {
            echo "1|ticket.php?iti=" . $ticket->get_fake_id();
            exit;
        } else {
            if (get_user_level($user->ID) == 10) {
                Ticket::change_ticket_status($ticket->get_related_ticket_id(), 1);
            } else {
                Ticket::change_ticket_status($ticket->get_related_ticket_id(), 0);
            }
            echo "پاسخ شما افزوده شد";
        }
    } else {
        return "مشکلی در ایجاد تیکت وجود دارد.لطفا مجددا تلاش کنید";
    }
}
Пример #13
0
 function create_by_staff($var, &$errors)
 {
     global $_FILES, $thisuser, $cfg;
     //check if the staff is allowed to create tickets.
     if (!$thisuser || !$thisuser->getId() || !$thisuser->isStaff() || !$thisuser->canCreateTickets()) {
         $errors['err'] = 'Permission denied';
     }
     if (!$var['issue']) {
         $errors['issue'] = 'Summary of the issue required';
     }
     if ($var['source'] && !in_array(strtolower($var['source']), array('email', 'phone', 'other'))) {
         $errors['source'] = 'Invalid source - ' . Format::htmlchars($var['source']);
     }
     $var['emailId'] = 0;
     //clean crap.
     $var['message'] = 'Ticket created by staff';
     if ($ticket = Ticket::create($var, $errors, 'staff', false, !$var['staffId'])) {
         //Staff are alerted only IF the ticket is not being assigned.
         //post issue as a response...
         $msgId = $ticket->getLastMsgId();
         $issue = $ticket->replaceTemplateVars($var['issue']);
         if ($respId = $ticket->postResponse($msgId, $issue, 'none', null, false)) {
             //Note that we're overwriting alerts.
             //Mark the ticket unanswered - postResponse marks it answered which is not the desired state.
             $ticket->markUnAnswered();
             //Send Notice to user --- if requested AND enabled!!
             if ($cfg->notifyONNewStaffTicket() && isset($var['alertuser'])) {
                 $dept = $ticket->getDept();
                 if (!$dept || !($tplId = $dept->getTemplateId())) {
                     $tplId = $cfg->getDefaultTemplateId();
                 }
                 $sql = 'SELECT ticket_notice_subj,ticket_notice_body FROM ' . EMAIL_TEMPLATE_TABLE . ' WHERE cfg_id=' . db_input($cfg->getId()) . ' AND tpl_id=' . db_input($tplId);
                 if (($resp = db_query($sql)) && db_num_rows($resp) && (list($subj, $body) = db_fetch_row($resp))) {
                     $body = $ticket->replaceTemplateVars($body);
                     $subj = $ticket->replaceTemplateVars($subj);
                     $body = str_replace('%message', $var['issue'], $body);
                     //Figure out the signature to use...if any.
                     switch (strtolower($var['signature'])) {
                         case 'mine':
                             $signature = $thisuser->getSignature();
                             break;
                         case 'dept':
                             $signature = $dept && $dept->isPublic() ? $dept->getSignature() : '';
                             //make sure it is public
                             break;
                         case 'none':
                         default:
                             $signature = '';
                             break;
                     }
                     $body = str_replace("%signature", $signature, $body);
                     //Email attachment when attached AND if emailed attachments are allowed!
                     $file = null;
                     $attachment = $_FILES['attachment'];
                     if ($attachment && is_file($attachment['tmp_name']) && $cfg->emailAttachments()) {
                         $file = array('file' => $attachment['tmp_name'], 'name' => $attachment['name'], 'type' => $attachment['type']);
                     }
                     if ($cfg->stripQuotedReply() && ($tag = trim($cfg->getReplySeparator()))) {
                         $body = "\n{$tag}\n\n" . $body;
                     }
                     if (!$dept || !($email = $dept->getEmail())) {
                         $email = $cfg->getDefaultEmail();
                     }
                     if ($email && $email->getId()) {
                         $email->send($ticket->getEmail(), $subj, $body, $file);
                     }
                 } else {
                     //We have a big problem...alert admin...
                     $msg = 'Problems fetching response template for ticket#' . $ticket->getId() . ' Possible config error - template #' . $tplId;
                     Sys::alertAdmin('System Error', $msg);
                 }
             }
             //Send send alert.
             //Upload attachment if any...
             if ($_FILES['attachment'] && $_FILES['attachment']['size']) {
                 $ticket->uploadAttachment($_FILES['attachment'], $respId, 'R');
             }
         } else {
             //end post response
             $errors['err'] = 'Internal error - message/response post error.';
         }
         //post create actions
         if ($var['staffId']) {
             //Assign ticket to staff if any. (internal note as message)
             $ticket->assignStaff($var['staffId'], $var['note'], isset($var['alertstaff']));
         } elseif ($var['note']) {
             //Not assigned...save optional note if any
             $ticket->postNote('New Ticket', $var['note'], false);
         } else {
             //Not assignment and no internal note - log activity
             $ticket->logActivity('New Ticket by Staff', 'Ticket created by staff -' . $thisuser->getName());
         }
     } else {
         $errors['err'] = $errors['err'] ? $errors['err'] : 'Unable to create the ticket. Correct the error(s) and try again';
     }
     return $ticket;
 }
Пример #14
0
 function index()
 {
     $this->load->helper('notification');
     $this->load->helper('string');
     $emailconfig = Setting::first();
     if ($emailconfig->ticket_config_active == "1") {
         $emailconfig->ticket_config_timestamp = time();
         $emailconfig->save();
         // this shows basic IMAP, no TLS required
         $config['login'] = $emailconfig->ticket_config_login;
         $config['pass'] = $emailconfig->ticket_config_pass;
         $config['host'] = $emailconfig->ticket_config_host;
         $config['port'] = $emailconfig->ticket_config_port;
         $config['mailbox'] = $emailconfig->ticket_config_mailbox;
         if ($emailconfig->ticket_config_imap == "1") {
             $flags = "/imap";
         } else {
             $flags = "/pop3";
         }
         if ($emailconfig->ticket_config_ssl == "1") {
             $flags .= "/ssl";
         }
         $config['service_flags'] = $flags . $emailconfig->ticket_config_flags;
         $this->load->library('peeker', $config);
         //attachment folder
         $bool = $this->peeker->set_attachment_dir('files/media/');
         //Search Filter
         $this->peeker->set_search($emailconfig->ticket_config_search);
         if ($this->peeker->search_and_count_messages() != "0") {
             log_message('error', 'Postmaster fetched ' . $this->peeker->search_and_count_messages() . ' new email tickets.');
             $id_array = $this->peeker->get_ids_from_search();
             //walk trough emails
             foreach ($id_array as $email_id) {
                 $ticket = false;
                 $email = $this->peeker->get_message($email_id);
                 $email->rewrite_html_transform_img_tags('files/media/');
                 $emailbody = utf8_encode(nl2br($email->get_plain()));
                 $emailaddr = $email->get_from_array();
                 $emailaddr = $emailaddr[0]->mailbox . '@' . $emailaddr[0]->host;
                 //get next ticket number
                 $settings = Setting::first();
                 $ticket_reference = $settings->ticket_reference;
                 $settings->ticket_reference = $settings->ticket_reference + 1;
                 $settings->save();
                 if (preg_match('/(?<=\\[Ticket\\#)(.+)(?=\\])/is', $email->get_subject(), $matches)) {
                     $ticket = Ticket::find_by_reference($matches[1]);
                 }
                 if ($ticket) {
                     log_message('error', 'Fetched email merged to ticket #' . $matches[1]);
                     $article_attributes = array('ticket_id' => $ticket->id, 'internal' => '0', 'from' => $email->get_from() . ' - ' . $emailaddr, 'reply_to' => $emailaddr, 'to' => $email->get_to(), 'cc' => $email->get_cc(), 'subject' => htmlspecialchars($email->get_subject()), 'message' => $emailbody, 'datetime' => time());
                     if ($ticket->status == "closed") {
                         $ticket->status = 'reopened';
                         $ticket->updated = '1';
                         $ticket->save();
                     }
                     $ticket->updated = '1';
                     $ticket->save();
                     $article = TicketHasArticle::create($article_attributes);
                     if (isset($ticket->user->email)) {
                         send_ticket_notification($ticket->user->email, '[Ticket#' . $ticket->reference . '] - ' . $ticket->subject, $emailbody, $ticket->id);
                     }
                     //Attachments
                     $parts = $email->get_parts_array();
                     if ($email->has_attachment()) {
                         foreach ($parts as $part) {
                             $savename = $email->get_fingerprint() . random_string('alnum', 8) . $part->get_filename();
                             $orgname = $part->get_filename();
                             $part->filename = $savename;
                             $attributes = array('article_id' => $article->id, 'filename' => $orgname, 'savename' => $savename);
                             $attachment = ArticleHasAttachment::create($attributes);
                         }
                         $email->save_all_attachments('files/media/');
                     }
                 } else {
                     //Ticket Attributes
                     $ticket_attributes = array('reference' => $ticket_reference, 'from' => $email->get_from() . ' - ' . $emailaddr, 'subject' => $email->get_subject(), 'text' => $emailbody, 'updated' => "1", 'created' => time(), 'user_id' => $settings->ticket_default_owner, 'type_id' => $settings->ticket_default_type, 'status' => $settings->ticket_default_status, 'queue_id' => $settings->ticket_default_queue);
                     //check if sender is client
                     $client = Client::find_by_email($emailaddr);
                     if (isset($client)) {
                         $ticket_attributes['client_id'] = $client->id;
                         $ticket_attributes['company_id'] = $client->company->id;
                     }
                     //create Ticket
                     $ticket = Ticket::create($ticket_attributes);
                     //Attachments
                     $parts = $email->get_parts_array();
                     if ($email->has_attachment()) {
                         foreach ($parts as $part) {
                             $savename = $email->get_fingerprint() . random_string('alnum', 8) . $part->get_filename();
                             $orgname = $part->get_filename();
                             $part->filename = $savename;
                             $attributes = array('ticket_id' => $ticket->id, 'filename' => $orgname, 'savename' => $savename);
                             $attachment = TicketHasAttachment::create($attributes);
                         }
                         $email->save_all_attachments('files/media/');
                     }
                     send_ticket_notification($ticket->user->email, '[Ticket#' . $ticket->reference . '] - ' . $ticket->subject, $emailbody, $ticket->id);
                     log_message('error', 'New ticket created #' . $ticket->reference);
                 }
                 if ($emailconfig->ticket_config_delete == "1") {
                     $email->set_delete();
                     $email->expunge();
                     $this->peeker->delete_and_expunge($email_id);
                 }
             }
         }
         $this->peeker->close();
         // tell the story of the connection (only for debuging)
         //echo "<pre>"; print_r($this->peeker->trace()); echo "</pre>";
     }
     die;
 }
Пример #15
0
 function createTicket($mid)
 {
     global $ost;
     if (!($mailinfo = $this->getHeaderInfo($mid))) {
         return false;
     }
     //Make sure the email is NOT already fetched... (undeleted emails)
     if ($mailinfo['mid'] && ($id = Ticket::getIdByMessageId(trim($mailinfo['mid']), $mailinfo['email']))) {
         return true;
     }
     //Reporting success so the email can be moved or deleted.
     //Is the email address banned?
     if ($mailinfo['email'] && EmailFilter::isBanned($mailinfo['email'])) {
         //We need to let admin know...
         $ost->logWarning('Ticket denied', 'Banned email - ' . $mailinfo['email']);
         return true;
         //Report success (moved or delete)
     }
     $emailId = $this->getEmailId();
     $var['name'] = $this->mime_decode($mailinfo['name']);
     $var['email'] = $mailinfo['email'];
     $var['subject'] = $mailinfo['subject'] ? $this->mime_decode($mailinfo['subject']) : '[No Subject]';
     $var['message'] = Format::stripEmptyLines($this->getBody($mid));
     $var['header'] = $this->getHeader($mid);
     $var['emailId'] = $emailId ? $emailId : $ost->getConfig()->getDefaultEmailId();
     //ok to default?
     $var['name'] = $var['name'] ? $var['name'] : $var['email'];
     //No name? use email
     $var['mid'] = $mailinfo['mid'];
     if (!$var['message']) {
         //An email with just attachments can have empty body.
         $var['message'] = '(EMPTY)';
     }
     if ($ost->getConfig()->useEmailPriority()) {
         $var['priorityId'] = $this->getPriority($mid);
     }
     $ticket = null;
     $newticket = true;
     //Check the subject line for possible ID.
     if ($var['subject'] && preg_match("[[#][0-9]{1,10}]", $var['subject'], $regs)) {
         $tid = trim(preg_replace("/[^0-9]/", "", $regs[0]));
         //Allow mismatched emails?? For now NO.
         if (!($ticket = Ticket::lookupByExtId($tid)) || strcasecmp($ticket->getEmail(), $var['email'])) {
             $ticket = null;
         }
     }
     $errors = array();
     if ($ticket) {
         if (!($msgid = $ticket->postMessage($var['message'], 'Email', $var['mid'], $var['header']))) {
             return false;
         }
     } elseif ($ticket = Ticket::create($var, $errors, 'Email')) {
         $msgid = $ticket->getLastMsgId();
     } else {
         //TODO: Log error..
         return null;
     }
     //Save attachments if any.
     if ($msgid && $ost->getConfig()->allowEmailAttachments() && ($struct = imap_fetchstructure($this->mbox, $mid)) && $struct->parts && ($attachments = $this->getAttachments($struct))) {
         //We're just checking the type of file - not size or number of attachments...
         // Restrictions are mainly due to PHP file uploads limitations
         foreach ($attachments as $a) {
             if ($ost->isFileTypeAllowed($a['name'], $a['mime'])) {
                 $file = array('name' => $a['name'], 'type' => $a['mime'], 'data' => $this->decode($a['encoding'], imap_fetchbody($this->mbox, $mid, $a['index'])));
                 $ticket->saveAttachment($file, $msgid, 'M');
             } else {
                 //This should be really a comment on message - NoT an internal note.
                 //TODO: support comments on Messages and Responses.
                 $error = sprintf('Attachment %s [%s] rejected because of file type', $a['name'], $a['mime']);
                 $ticket->postNote('Email Attachment Rejected', $error, false);
                 $ost->logDebug('Email Attachment Rejected (Ticket #' . $ticket->getExtId() . ')', $error);
             }
         }
     }
     return $ticket;
 }
Пример #16
0
$var['header'] = $parser->getHeader();
$var['priorityId'] = $cfg->useEmailPriority() ? $parser->getPriority() : 0;
$ticket = null;
if (preg_match("[[#][0-9]{1,10}]", $var['subject'], $regs)) {
    $extid = trim(preg_replace("/[^0-9]/", "", $regs[0]));
    $ticket = new Ticket(Ticket::getIdByExtId($extid));
    //Allow mismatched emails?? For now hell NO.
    if (!is_object($ticket) || strcasecmp($ticket->getEmail(), $var['email'])) {
        $ticket = null;
    }
}
$errors = array();
$msgid = 0;
if (!$ticket) {
    //New tickets...
    $ticket = Ticket::create($var, $errors, 'email');
    if (!is_object($ticket) || $errors) {
        api_exit(EX_DATAERR, 'Ticket create Failed ' . implode("\n", $errors) . "\n\n");
    }
    $msgid = $ticket->getLastMsgId();
} else {
    //post message....postMessage does the cleanup.
    if (!($msgid = $ticket->postMessage($var['message'], 'Email', $var['mid'], $var['header']))) {
        api_exit(EX_DATAERR, 'Unable to post message');
    }
}
//Ticket created...save attachments if enabled.
if ($cfg->allowEmailAttachments() && ($attachments = $parser->getAttachments())) {
    foreach ($attachments as $attachment) {
        if ($attachment['filename'] && $ost->isFileTypeAllowed($attachment['filename'])) {
            $ticket->saveAttachment(array('name' => $attachment['filename'], 'data' => $attachment['body']), $msgid, 'M');
Пример #17
0
            $errors['captcha']=__('Enter text shown on the image');
        elseif(strcmp($_SESSION['captcha'], md5(strtoupper($_POST['captcha']))))
            $errors['captcha']=__('Invalid - try again!');
    }

    $tform = TicketForm::objects()->one()->getForm($vars);
    $messageField = $tform->getField('message');
    $attachments = $messageField->getWidget()->getAttachments();
    if (!$errors && $messageField->isAttachmentsEnabled())
        $vars['cannedattachments'] = $attachments->getClean();

    // Drop the draft.. If there are validation errors, the content
    // submitted will be displayed back to the user
    Draft::deleteForNamespace('ticket.client.'.substr(session_id(), -12));
    //Ticket::create...checks for errors..
    if(($ticket=Ticket::create($vars, $errors, SOURCE))){
        $msg=__('Support ticket request created');
        // Drop session-backed form data
        unset($_SESSION[':form-data']);
        //Logged in...simply view the newly created ticket.
        if($thisclient && $thisclient->isValid()) {
            session_write_close();
            session_regenerate_id();
            @header('Location: tickets.php?id='.$ticket->getId());
        }
    }else{
        $errors['err']=$errors['err']?$errors['err']:__('Unable to create a ticket. Please correct errors below and try again!');
    }
}

//page
Пример #18
0
 function createTicket($data)
 {
     # Pull off some meta-data
     $alert = (bool) (isset($data['alert']) ? $data['alert'] : true);
     $autorespond = (bool) (isset($data['autorespond']) ? $data['autorespond'] : true);
     # Assign default value to source if not defined, or defined as NULL
     $data['source'] = isset($data['source']) ? $data['source'] : 'API';
     # Create the ticket with the data (attempt to anyway)
     $errors = array();
     $ticket = Ticket::create($data, $errors, $data['source'], $autorespond, $alert);
     # Return errors (?)
     if (count($errors)) {
         if (isset($errors['errno']) && $errors['errno'] == 403) {
             return $this->exerr(403, __('Ticket denied'));
         } else {
             return $this->exerr(400, __("Unable to create new ticket: validation errors") . ":\n" . Format::array_implode(": ", "\n", $errors));
         }
     } elseif (!$ticket) {
         return $this->exerr(500, __("Unable to create new ticket: unknown error"));
     }
     // $ticket->setStaffId(0);
     return $ticket;
 }
Пример #19
0
 static function open($vars, &$errors)
 {
     global $thisstaff, $cfg;
     if (!$thisstaff || !$thisstaff->canCreateTickets()) {
         return false;
     }
     if ($vars['source'] && !in_array(strtolower($vars['source']), array('email', 'phone', 'other'))) {
         $errors['source'] = 'Invalid source - ' . Format::htmlchars($vars['source']);
     }
     if (!$vars['uid']) {
         //Special validation required here
         if (!$vars['email'] || !Validator::is_email($vars['email'])) {
             $errors['email'] = 'Valid email required';
         }
         if (!$vars['name']) {
             $errors['name'] = 'Name required';
         }
     }
     if (!$thisstaff->canAssignTickets()) {
         unset($vars['assignId']);
     }
     if (!($ticket = Ticket::create($vars, $errors, 'staff', false))) {
         return false;
     }
     $vars['msgId'] = $ticket->getLastMsgId();
     // post response - if any
     $response = null;
     if ($vars['response'] && $thisstaff->canPostReply()) {
         // unpack any uploaded files into vars.
         if ($_FILES['attachments']) {
             $vars['files'] = AttachmentFile::format($_FILES['attachments']);
         }
         $vars['response'] = $ticket->replaceVars($vars['response']);
         if ($response = $ticket->postReply($vars, $errors, false)) {
             //Only state supported is closed on response
             if (isset($vars['ticket_state']) && $thisstaff->canCloseTickets()) {
                 $ticket->setState($vars['ticket_state']);
             }
         }
     }
     // Not assigned...save optional note if any
     if (!$vars['assignId'] && $vars['note']) {
         $ticket->logNote('New Ticket', $vars['note'], $thisstaff, false);
     } else {
         // Not assignment and no internal note - log activity
         $ticket->logActivity('New Ticket by Staff', 'Ticket created by staff -' . $thisstaff->getName());
     }
     $ticket->reload();
     if (!$cfg->notifyONNewStaffTicket() || !isset($vars['alertuser']) || !($dept = $ticket->getDept())) {
         return $ticket;
     }
     //No alerts.
     //Send Notice to user --- if requested AND enabled!!
     if (($tpl = $dept->getTemplate()) && ($msg = $tpl->getNewTicketNoticeMsgTemplate()) && ($email = $dept->getEmail())) {
         $message = (string) $ticket->getLastMessage();
         if ($response) {
             $message .= $cfg->isHtmlThreadEnabled() ? "<br><br>" : "\n\n";
             $message .= $response->getBody();
         }
         if ($vars['signature'] == 'mine') {
             $signature = $thisstaff->getSignature();
         } elseif ($vars['signature'] == 'dept' && $dept && $dept->isPublic()) {
             $signature = $dept->getSignature();
         } else {
             $signature = '';
         }
         $attachments = $cfg->emailAttachments() && $response ? $response->getAttachments() : array();
         $msg = $ticket->replaceVars($msg->asArray(), array('message' => $message, 'signature' => $signature, 'response' => $response ? $response->getBody() : '', 'recipient' => $ticket->getOwner(), 'staff' => $thisstaff));
         $references = $ticket->getLastMessage()->getEmailMessageId();
         if (isset($response)) {
             $references = array($response->getEmailMessageId(), $references);
         }
         $options = array('references' => $references, 'thread' => $ticket->getLastMessage());
         $email->send($ticket->getEmail(), $msg['subj'], $msg['body'], $attachments, $options);
     }
     return $ticket;
 }
Пример #20
0
 static function createWelcomeTicket()
 {
     global $gbl, $sgbl, $login, $ghtml;
     $name = ucfirst($sgbl->__var_program_name);
     $parent['parent_clname'] = createParentName('client', 'admin');
     $param['made_by'] = createParentName('pserver', $name);
     $param['sent_to'] = createParentName('client', 'admin');
     $param['subject'] = "Welcome to {$name}";
     //$param['priority'] = "low";
     $param['category'] = "Welcome";
     $param['descr_f'] = "Welcome to {$name}";
     $param['ddate'] = time();
     $param['date_modified'] = time();
     $ticketconfig = $login->getObject('ticketconfig');
     $param['nname'] = $ticketconfig->getAndIncrementTicket();
     $ticketconfig->write();
     $param['unread_flag'] = 'on';
     $param['state'] = 'open';
     $ticket = new Ticket(null, null, $param['nname']);
     $ticket->create($param);
     $ticket->postAdd();
     $ticket->was();
 }
Пример #21
0
    function createTicket($mid,$emailid=0){
        global $cfg;

        $mailinfo=$this->getHeaderInfo($mid);

        //Make sure the email is NOT one of the undeleted emails.
        if($mailinfo['mid'] && ($id=Ticket::getIdByMessageId(trim($mailinfo['mid']),$mailinfo['from']['email']))){
            //TODO: Move emails to a fetched folder when delete is false?? 
            return false;
        }

        $var['name']=$this->mime_decode($mailinfo['from']['name']);
        $var['email']=$mailinfo['from']['email'];
        $var['subject']=$mailinfo['subject']?$this->mime_decode($mailinfo['subject']):'[No Subject]';
        $var['message']=Format::stripEmptyLines($this->getBody($mid));
        $var['header']=$this->getHeader($mid);
        $var['emailId']=$emailid?$emailid:$cfg->getDefaultEmailId(); //ok to default?
        $var['name']=$var['name']?$var['name']:$var['email']; //No name? use email
        $var['mid']=$mailinfo['mid'];

        if($cfg->useEmailPriority())
            $var['pri']=$this->getPriority($mid);
       
        $ticket=null;
        $newticket=true;
        //Check the subject line for possible ID.
        if(preg_match ("[[#][0-9]{1,10}]",$var['subject'],$regs)) {
            $extid=trim(preg_replace("/[^0-9]/", "", $regs[0]));
            $ticket= new Ticket(Ticket::getIdByExtId($extid));
            //Allow mismatched emails?? For now NO.
            if(!$ticket || strcasecmp($ticket->getEmail(),$var['email']))
                $ticket=null;
        }
        
        $errors=array();
        if(!$ticket) {
            if(!($ticket=Ticket::create($var,$errors,'Email')) || $errors)
                return null;
            $msgid=$ticket->getLastMsgId();
        }else{
            $message=$var['message'];
            //Strip quoted reply...TODO: figure out how mail clients do it without special tag..
            if($cfg->stripQuotedReply() && ($tag=$cfg->getReplySeparator()) && strpos($var['message'],$tag))
                list($message)=split($tag,$var['message']);
            $msgid=$ticket->postMessage($message,'Email',$var['mid'],$var['header']);
        }
        //Save attachments if any.
        if($msgid && $cfg->allowEmailAttachments()){
            if(($struct = imap_fetchstructure($this->mbox,$mid)) && $struct->parts) {
                if($ticket->getLastMsgId()!=$msgid)
                    $ticket->setLastMsgId($msgid);
                $this->saveAttachments($ticket,$mid,$struct);

            }
        } 
        return $ticket;
    }
Пример #22
0
 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;
 }
Пример #23
0
             $msg = "{$i} of {$count} selected tickets deleted";
         }
     }
 } elseif (!strcasecmp($_POST['a'], 'open')) {
     //Open ticket
     $ticket = null;
     $_POST['emailId'] = $_POST['topicId'] = 0;
     //clean crap.
     $_POST['message'] = 'Ticket created by staff';
     if (!$_POST['issue']) {
         $errors['issue'] = 'Summary of the issue required';
     }
     if ($_POST['source'] && !in_array($_POST['source'], array('email', 'phone', 'other'))) {
         $errors['source'] = 'Invalid source';
     }
     if ($ticket = Ticket::create($_POST, $errors, 'staff', isset($_POST['alertuser']) ? true : false, false)) {
         //post issue as a response...but no alerts are sent to the user. ?? TODO: Add optional alert
         $msgId = $ticket->getLastMsgId();
         if ($respId = $ticket->postResponse($msgId, $_POST['issue'], 'none', null, false)) {
             //Upload attachment if any...
             if ($_FILES['attachment'] && $_FILES['attachment']['size']) {
                 $ticket->uploadAttachment($_FILES['attachment'], $respId, 'R');
             }
         }
         if ($_POST['staffId']) {
             //Assign ticket to staff if any. (internal note as message)
             $ticket->assignStaff($_POST['staffId'], $_POST['note'], isset($_POST['alertstaff']) ? true : false);
         } elseif ($_POST['note']) {
             //Not assigned...save optionl note if any
             $ticket->postNote('New Ticket', $_POST['note']);
         }
 /**
  * 
  * Create ticket into Database
  * 
  * @param	array	$aryTicket		Ticket object
  */
 private function CreateTicket($aryTicket)
 {
     global $db, $user, $conf;
     $function = "CreateTicket";
     $idTicket = -1;
     $data = $aryTicket['data'];
     $lines = $data['lines'];
     if ($data['idsource'] > 0) {
         $prods_returned = self::testSource($aryTicket);
         if (sizeof($prods_returned) > 0) {
             return -6;
         }
         $vater = self::fetch($data['idsource']);
         $data['payment_type'] = $vater->mode_reglement_id;
     }
     $cash = new Cash($db);
     $terminal = $data["cashId"];
     $cash->fetch($terminal);
     if (!$data['customerId']) {
         $socid = $cash->fk_soc;
         $data['customerId'] = $socid;
     } else {
         $socid = $data['customerId'];
     }
     if (!$data['employeeId']) {
         $employee = $_SESSION['uid'];
     } else {
         $employee = $data['employeeId'];
     }
     $object = new Ticket($db);
     $object->type = $data['type'];
     $object->socid = $socid;
     $object->statut = $data['state'];
     $object->fk_cash = $terminal;
     $object->remise_percent = $data['discount_percent'];
     $object->remise_absolut = $data['discount_qty'];
     if ($data['customerpay1'] > 0) {
         $object->mode_reglement_id = $cash->fk_modepaycash;
     } else {
         if ($data['customerpay2'] > 0) {
             $object->mode_reglement_id = $cash->fk_modepaybank;
         } else {
             $object->mode_reglement_id = $cash->fk_modepaybank_extra;
         }
     }
     $object->fk_place = $data['id_place'];
     $object->note = $data['note'];
     $object->customer_pay = $data['customerpay'];
     $object->diff_payment = $data['difpayment'];
     $object->id_source = $data['idsource'];
     $db->begin;
     $idTicket = $object->create($employee, 1, 0);
     $data['ref'] = $object->ref;
     if ($idTicket < 0) {
         $db->rollback();
         return -1;
     } else {
         //Adding lines
         $data['id'] = $idTicket;
         if ($data['id_place']) {
             $place = new Place($db);
             $place->fetch($data['id_place']);
             $place->fk_ticket = $idTicket;
             $place->set_place($idTicket);
         }
         $idLines = self::addTicketLines($lines, $idTicket, $object->type == 1 ? true : false);
         if ($idLines < 0) {
             $db->rollback();
             return -2;
         } else {
             if ($object->fk_place) {
                 $place = new Place($db);
                 $place->fetch($object->fk_place);
             }
             if ($object->statut != 0) {
                 //Adding Payments
                 $payment = self::addPayment($data);
                 if (!$payment) {
                     $db->rollback();
                     return -3;
                 } else {
                     if ($object->diff_payment <= 0) {
                         $object->set_paid($user);
                     }
                 }
                 //Decrease stock
                 $stock = self::quitSotck($lines, $object->type == 1 ? true : false);
                 if ($stock) {
                     $db->rollback();
                     return -4;
                 }
                 // liberar puesto
                 if ($place) {
                     $place->free_place();
                 }
             } else {
                 // usar puesto
                 if ($place) {
                     $place->set_place($idTicket);
                 }
             }
         }
     }
     $db->commit;
     return $idTicket;
 }
Пример #25
0
 /**
  * function that creates a new ticket.
  * A new ticket will be created, in case the extra_info != 0 and the http request came from ingame, then a ticket_info page will be created.
  * A log entry will be written, depending on the $real_authors value. In case the for_support_group parameter is set, the ticket will be forwarded immediately.
  * Also the mail handler will create a new email that will be sent to the author to notify him that his ticket is freshly created.
  * @param $title the title we want to give to the ticket.
  * @param $content the content we want to give to the starting post of the ticket.
  * @param $category the id of the category that should be related to the ticket.
  * @param $author the person who's id will be stored in the database as creator of the ticket.
  * @param $real_author should be the same id, or a moderator/admin who creates a ticket for another user (this is used for logging purposes).
  * @param $for_support_group in case you directly want to forward the ticket after creating it. (default value = 0 =  don't forward)
  * @param $extra_info used for creating an ticket_info page related to the ticket, this only happens when the ticket is made ingame.
  * @return the created tickets id.
  */
 public static function create_Ticket($title, $content, $category, $author, $real_author, $for_support_group = 0, $extra_info = 0)
 {
     //create the new ticket!
     $ticket = new Ticket();
     $values = array("Title" => $title, "Timestamp" => 0, "Status" => 1, "Queue" => 0, "Ticket_Category" => $category, "Author" => $author, "Priority" => 0);
     $ticket->set($values);
     $ticket->create();
     $ticket_id = $ticket->getTId();
     //if ingame then add an extra info
     if (Helpers::check_if_game_client() && $extra_info != 0) {
         $extra_info['Ticket'] = $ticket_id;
         Ticket_Info::create_Ticket_Info($extra_info);
     }
     //write a log entry
     if ($author == $real_author) {
         Ticket_Log::createLogEntry($ticket_id, $author, 1);
     } else {
         Ticket_Log::createLogEntry($ticket_id, $real_author, 2, $author);
     }
     Ticket_Reply::createReply($content, $author, $ticket_id, 0, $author);
     //forwards the ticket directly after creation to the supposed support group
     if ($for_support_group) {
         Ticket::forwardTicket(0, $ticket_id, $for_support_group);
     }
     //send email that new ticket has been created
     Mail_Handler::send_ticketing_mail($ticket->getAuthor(), $ticket, $content, "NEW", $ticket->getForwardedGroupId());
     return $ticket_id;
 }
Пример #26
0
    function install($vars) {

        $this->errors=$f=array();

        $f['name']          = array('type'=>'string',   'required'=>1, 'error'=>__('Name required'));
        $f['email']         = array('type'=>'email',    'required'=>1, 'error'=>__('Valid email required'));
        $f['fname']         = array('type'=>'string',   'required'=>1, 'error'=>__('First name required'));
        $f['lname']         = array('type'=>'string',   'required'=>1, 'error'=>__('Last name required'));
        $f['admin_email']   = array('type'=>'email',    'required'=>1, 'error'=>__('Valid email required'));
        $f['username']      = array('type'=>'username', 'required'=>1, 'error'=>__('Username required'));
        $f['passwd']        = array('type'=>'password', 'required'=>1, 'error'=>__('Password required'));
        $f['passwd2']       = array('type'=>'password', 'required'=>1, 'error'=>__('Confirm Password'));
        $f['prefix']        = array('type'=>'string',   'required'=>1, 'error'=>__('Table prefix required'));
        $f['dbhost']        = array('type'=>'string',   'required'=>1, 'error'=>__('Host name required'));
        $f['dbname']        = array('type'=>'string',   'required'=>1, 'error'=>__('Database name required'));
        $f['dbuser']        = array('type'=>'string',   'required'=>1, 'error'=>__('Username required'));
        $f['dbpass']        = array('type'=>'string',   'required'=>1, 'error'=>__('Password required'));

        $vars = array_map('trim', $vars);

        if(!Validator::process($f,$vars,$this->errors) && !$this->errors['err'])
            $this->errors['err']=__('Missing or invalid data - correct the errors and try again.');


        //Staff's email can't be same as system emails.
        if($vars['admin_email'] && $vars['email'] && !strcasecmp($vars['admin_email'],$vars['email']))
            $this->errors['admin_email']=__('Conflicts with system email above');
        //Admin's pass confirmation.
        if(!$this->errors && strcasecmp($vars['passwd'],$vars['passwd2']))
            $this->errors['passwd2']=__('Password(s) do not match');
        //Check table prefix underscore required at the end!
        if($vars['prefix'] && substr($vars['prefix'], -1)!='_')
            $this->errors['prefix']=__('Bad prefix. Must have underscore (_) at the end. e.g \'ost_\'');

        //Make sure admin username is not very predictable. XXX: feels dirty but necessary
        if(!$this->errors['username'] && in_array(strtolower($vars['username']),array('admin','admins','username','osticket')))
            $this->errors['username']=__('Bad username');

        // Support port number specified in the hostname with a colon (:)
        list($host, $port) = explode(':', $vars['dbhost']);
        if ($port && is_numeric($port) && ($port < 1 || $port > 65535))
            $this->errors['db'] = __('Invalid database port number');

        //MYSQL: Connect to the DB and check the version & database (create database if it doesn't exist!)
        if(!$this->errors) {
            if(!db_connect($vars['dbhost'],$vars['dbuser'],$vars['dbpass']))
                $this->errors['db']=sprintf(__('Unable to connect to MySQL server: %s'), db_connect_error());
            elseif(explode('.', db_version()) < explode('.', $this->getMySQLVersion()))
                $this->errors['db']=sprintf(__('osTicket requires MySQL %s or later!'),$this->getMySQLVersion());
            elseif(!db_select_database($vars['dbname']) && !db_create_database($vars['dbname'])) {
                $this->errors['dbname']=__("Database doesn't exist");
                $this->errors['db']=__('Unable to create the database.');
            } elseif(!db_select_database($vars['dbname'])) {
                $this->errors['dbname']=__('Unable to select the database');
            } else {
                //Abort if we have another installation (or table) with same prefix.
                $sql = 'SELECT * FROM `'.$vars['prefix'].'config` LIMIT 1';
                if(db_query($sql, false)) {
                    $this->errors['err'] = __('We have a problem - another installation with same table prefix exists!');
                    $this->errors['prefix'] = __('Prefix already in-use');
                } else {
                    //Try changing charset and collation of the DB - no bigie if we fail.
                    db_query('ALTER DATABASE '.$vars['dbname'].' DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci', false);
                }
            }
        }

        //bailout on errors.
        if($this->errors) return false;

        /*************** We're ready to install ************************/
        define('ADMIN_EMAIL',$vars['admin_email']); //Needed to report SQL errors during install.
        define('TABLE_PREFIX',$vars['prefix']); //Table prefix
        Bootstrap::defineTables(TABLE_PREFIX);
        Bootstrap::loadCode();

        $debug = true; // Change it to false to squelch SQL errors.

        //Last minute checks.
        if(!file_exists($this->getConfigFile()) || !($configFile=file_get_contents($this->getConfigFile())))
            $this->errors['err']=__('Unable to read config file. Permission denied! (#2)');
        elseif(!($fp = @fopen($this->getConfigFile(),'r+')))
            $this->errors['err']=__('Unable to open config file for writing. Permission denied! (#3)');

        else {
            $streams = DatabaseMigrater::getUpgradeStreams(INCLUDE_DIR.'upgrader/streams/');
            foreach ($streams as $stream=>$signature) {
                $schemaFile = INC_DIR."streams/$stream/install-mysql.sql";
                if (!file_exists($schemaFile) || !($fp2 = fopen($schemaFile, 'rb')))
                    $this->errors['err'] = sprintf(
                        __('%s: Internal Error - please make sure your download is the latest (#1)'),
                        $stream);
                elseif (
                        // TODO: Make the hash algo configurable in the streams
                        //       configuration ( core : md5 )
                        !($hash = md5(fread($fp2, filesize($schemaFile))))
                        || strcasecmp($signature, $hash))
                    $this->errors['err'] = sprintf(
                        __('%s: Unknown or invalid schema signature (%s .. %s)'),
                        $stream,
                        $signature, $hash);
                elseif (!$this->load_sql_file($schemaFile, $vars['prefix'], true, $debug))
                    $this->errors['err'] = sprintf(
                        __('%s: Error parsing SQL schema! Get help from developers (#4)'),
                        $stream);
            }
        }

        if(!$this->errors) {

            // TODO: Use language selected from install worksheet
            $i18n = new Internationalization($vars['lang_id']);
            $i18n->loadDefaultData();

            Signal::send('system.install', $this);

            $sql='SELECT `id` FROM '.TABLE_PREFIX.'sla ORDER BY `id` LIMIT 1';
            $sla_id_1 = db_result(db_query($sql, false));

            $sql='SELECT `dept_id` FROM '.TABLE_PREFIX.'department ORDER BY `dept_id` LIMIT 1';
            $dept_id_1 = db_result(db_query($sql, false));

            $sql='SELECT `tpl_id` FROM '.TABLE_PREFIX.'email_template_group ORDER BY `tpl_id` LIMIT 1';
            $template_id_1 = db_result(db_query($sql, false));

            $sql='SELECT `group_id` FROM '.TABLE_PREFIX.'groups ORDER BY `group_id` LIMIT 1';
            $group_id_1 = db_result(db_query($sql, false));

            $sql='SELECT `value` FROM '.TABLE_PREFIX.'config WHERE namespace=\'core\' and `key`=\'default_timezone_id\' LIMIT 1';
            $default_timezone = db_result(db_query($sql, false));

            //Create admin user.
            $sql='INSERT INTO '.TABLE_PREFIX.'staff SET created=NOW() '
                .", isactive=1, isadmin=1, group_id='$group_id_1', dept_id='$dept_id_1'"
                .", timezone_id='$default_timezone', max_page_size=25"
                .', email='.db_input($vars['admin_email'])
                .', firstname='.db_input($vars['fname'])
                .', lastname='.db_input($vars['lname'])
                .', username='******'username'])
                .', passwd='.db_input(Passwd::hash($vars['passwd']));
            if(!db_query($sql, false) || !($uid=db_insert_id()))
                $this->errors['err']=__('Unable to create admin user (#6)');
        }

        if(!$this->errors) {
            //Create default emails!
            $email = $vars['email'];
            list(,$domain)=explode('@',$vars['email']);
            $sql='INSERT INTO '.TABLE_PREFIX.'email (`name`,`email`,`created`,`updated`) VALUES '
                    ." ('Support','$email',NOW(),NOW())"
                    .",('osTicket Alerts','alerts@$domain',NOW(),NOW())"
                    .",('','noreply@$domain',NOW(),NOW())";
            $support_email_id = db_query($sql, false) ? db_insert_id() : 0;


            $sql='SELECT `email_id` FROM '.TABLE_PREFIX."email WHERE `email`='alerts@$domain' LIMIT 1";
            $alert_email_id = db_result(db_query($sql, false));

            //Create config settings---default settings!
            $defaults = array(
                'default_email_id'=>$support_email_id,
                'alert_email_id'=>$alert_email_id,
                'default_dept_id'=>$dept_id_1, 'default_sla_id'=>$sla_id_1,
                'default_template_id'=>$template_id_1,
                'admin_email'=>$vars['admin_email'],
                'schema_signature'=>$streams['core'],
                'helpdesk_url'=>URL,
                'helpdesk_title'=>$vars['name']);
            $config = new Config('core');
            if (!$config->updateAll($defaults))
                $this->errors['err']=__('Unable to create config settings').' (#7)';

            // Set company name
            require_once(INCLUDE_DIR.'class.company.php');
            $company = new Company();
            $company->getForm()->setAnswer('name', $vars['name']);
            $company->getForm()->save();

			foreach ($streams as $stream=>$signature) {
				if ($stream != 'core') {
                    $config = new Config($stream);
                    if (!$config->update('schema_signature', $signature))
                        $this->errors['err']=__('Unable to create config settings').' (#8)';
				}
			}
        }

        if($this->errors) return false; //Abort on internal errors.


        //Rewrite the config file - MUST be done last to allow for installer recovery.
        $configFile= str_replace("define('OSTINSTALLED',FALSE);","define('OSTINSTALLED',TRUE);",$configFile);
        $configFile= str_replace('%ADMIN-EMAIL',$vars['admin_email'],$configFile);
        $configFile= str_replace('%CONFIG-DBHOST',$vars['dbhost'],$configFile);
        $configFile= str_replace('%CONFIG-DBNAME',$vars['dbname'],$configFile);
        $configFile= str_replace('%CONFIG-DBUSER',$vars['dbuser'],$configFile);
        $configFile= str_replace('%CONFIG-DBPASS',$vars['dbpass'],$configFile);
        $configFile= str_replace('%CONFIG-PREFIX',$vars['prefix'],$configFile);
        $configFile= str_replace('%CONFIG-SIRI',Misc::randCode(32),$configFile);
        if(!$fp || !ftruncate($fp,0) || !fwrite($fp,$configFile)) {
            $this->errors['err']=__('Unable to write to config file. Permission denied! (#5)');
            return false;
        }
        @fclose($fp);

        /************* Make the system happy ***********************/

        $sql='UPDATE '.TABLE_PREFIX."email SET dept_id=$dept_id_1";
        db_query($sql, false);

        global $cfg;
        $cfg = new OsticketConfig();

        //Create a ticket to make the system warm and happy.
        $errors = array();
        $ticket_vars = $i18n->getTemplate('templates/ticket/installed.yaml')
            ->getData();
        $ticket = Ticket::create($ticket_vars, $errors, 'api', false, false);

        if ($ticket
                && ($org = Organization::objects()->order_by('id')->one())) {

            $user=User::lookup($ticket->getOwnerId());
            $user->setOrganization($org);
        }

        //TODO: create another personalized ticket and assign to admin??

        //Log a message.
        $msg=__("Congratulations osTicket basic installation completed!\n\nThank you for choosing osTicket!");
        $sql='INSERT INTO '.TABLE_PREFIX.'syslog SET created=NOW(), updated=NOW(), log_type="Debug" '
            .', title="osTicket installed!"'
            .', log='.db_input($msg)
            .', ip_address='.db_input($_SERVER['REMOTE_ADDR']);
        db_query($sql, false);

        return true;
    }
Пример #27
0
 public function run()
 {
     DB::table('Tickets')->delete();
     Ticket::create(array('estado' => 'A', 'fechaPago' => DateTime::createFromFormat('Y-m-d H:i:s', '2015-04-30 23:00:00'), 'fechaGenerado' => DateTime::createFromFormat('Y-m-d H:i:s', '2015-04-30 23:01:00'), 'clienteId' => '1', 'carteleraId' => '1'));
 }
Пример #28
0
 static function open($vars, &$errors)
 {
     global $thisstaff, $cfg;
     if (!$thisstaff || !$thisstaff->canCreateTickets()) {
         return false;
     }
     if ($vars['source'] && !in_array(strtolower($vars['source']), array('email', 'phone', 'other'))) {
         $errors['source'] = sprintf(__('Invalid source given - %s'), Format::htmlchars($vars['source']));
     }
     if (!$vars['uid']) {
         //Special validation required here
         if (!$vars['email'] || !Validator::is_email($vars['email'])) {
             $errors['email'] = __('Valid email address is required');
         }
         if (!$vars['name']) {
             $errors['name'] = __('Name is required');
         }
     }
     if (!$thisstaff->canAssignTickets()) {
         unset($vars['assignId']);
     }
     $create_vars = $vars;
     $tform = TicketForm::objects()->one()->getForm($create_vars);
     $create_vars['cannedattachments'] = $tform->getField('message')->getWidget()->getAttachments()->getClean();
     if (!($ticket = Ticket::create($create_vars, $errors, 'staff', false))) {
         return false;
     }
     $vars['msgId'] = $ticket->getLastMsgId();
     // post response - if any
     $response = null;
     if ($vars['response'] && $thisstaff->canPostReply()) {
         $vars['response'] = $ticket->replaceVars($vars['response']);
         // $vars['cannedatachments'] contains the attachments placed on
         // the response form.
         $response = $ticket->postReply($vars, $errors, false);
     }
     // Not assigned...save optional note if any
     if (!$vars['assignId'] && $vars['note']) {
         if (!$cfg->isHtmlThreadEnabled()) {
             $vars['note'] = new TextThreadBody($vars['note']);
         }
         $ticket->logNote(_S('New Ticket'), $vars['note'], $thisstaff, false);
     } else {
         // Not assignment and no internal note - log activity
         $ticket->logActivity(_S('New Ticket by Agent'), sprintf(_S('Ticket created by agent - %s'), $thisstaff->getName()));
     }
     $ticket->reload();
     if (!$cfg->notifyONNewStaffTicket() || !isset($vars['alertuser']) || !($dept = $ticket->getDept())) {
         return $ticket;
     }
     //No alerts.
     //Send Notice to user --- if requested AND enabled!!
     if (($tpl = $dept->getTemplate()) && ($msg = $tpl->getNewTicketNoticeMsgTemplate()) && ($email = $dept->getEmail())) {
         $message = (string) $ticket->getLastMessage();
         if ($response) {
             $message .= $cfg->isHtmlThreadEnabled() ? "<br><br>" : "\n\n";
             $message .= $response->getBody();
         }
         if ($vars['signature'] == 'mine') {
             $signature = $thisstaff->getSignature();
         } elseif ($vars['signature'] == 'dept' && $dept && $dept->isPublic()) {
             $signature = $dept->getSignature();
         } else {
             $signature = '';
         }
         $attachments = $cfg->emailAttachments() && $response ? $response->getAttachments() : array();
         $msg = $ticket->replaceVars($msg->asArray(), array('message' => $message, 'signature' => $signature, 'response' => $response ? $response->getBody() : '', 'recipient' => $ticket->getOwner(), 'staff' => $thisstaff));
         $references = $ticket->getLastMessage()->getEmailMessageId();
         if (isset($response)) {
             $references = array($response->getEmailMessageId(), $references);
         }
         $options = array('references' => $references, 'thread' => $ticket->getLastMessage());
         $email->send($ticket->getOwner(), $msg['subj'], $msg['body'], $attachments, $options);
     }
     return $ticket;
 }
Пример #29
0
//Ticket source.
$inc = 'open.inc.php';
//default include.
$errors = array();
if ($_POST) {
    $_POST['deptId'] = $_POST['emailId'] = 0;
    //Just Making sure we don't accept crap...only topicId is expected.
    if ($cfg->enableCaptcha()) {
        if (!$_POST['captcha']) {
            $errors['captcha'] = 'Enter text shown on the image';
        } elseif (strcmp($_SESSION['captcha'], md5($_POST['captcha']))) {
            $errors['captcha'] = 'Invalid - try again!';
        }
    }
    //Ticket::create...checks for errors..
    if ($ticket = Ticket::create($_POST, $errors, SOURCE)) {
        $msg = $trl->translate('TEXT_TICKET_CREATED');
        if ($thisclient && $thisclient->isValid()) {
            //Logged in...simply view the newly created ticket.
            @header('Location: tickets.php?id=' . $ticket->getExtId());
        }
        //Thank the user and promise speedy resolution!
        $inc = 'thankyou.inc.php';
    } else {
        $errors['err'] = $errors['err'] ? $errors['err'] : $trl->translate('TEXT_UNABLE_CREATE_TICKET');
    }
}
//page
require CLIENTINC_DIR . 'header.inc.php';
require CLIENTINC_DIR . $inc;
require CLIENTINC_DIR . 'footer.inc.php';
Пример #30
0
 function open($vars, $files, &$errors)
 {
     global $thisstaff, $cfg;
     if (!$thisstaff || !$thisstaff->canCreateTickets()) {
         return false;
     }
     if (!$vars['issue']) {
         $errors['issue'] = 'Summary of the issue required';
     } else {
         $vars['message'] = $vars['issue'];
     }
     if ($var['source'] && !in_array(strtolower($var['source']), array('email', 'phone', 'other'))) {
         $errors['source'] = 'Invalid source - ' . Format::htmlchars($var['source']);
     }
     if (!($ticket = Ticket::create($vars, $errors, 'staff', false, !$vars['assignId']))) {
         return false;
     }
     $vars['msgId'] = $ticket->getLastMsgId();
     $respId = 0;
     // post response - if any
     if ($vars['response']) {
         $vars['response'] = $ticket->replaceTemplateVars($vars['response']);
         if ($respId = $ticket->postReply($vars, $files, $errors, false)) {
             //Only state supported is closed on response
             if (isset($vars['ticket_state']) && $thisstaff->canCloseTickets()) {
                 $ticket->setState($vars['ticket_state']);
             }
         }
     }
     //Post Internal note
     if ($var['assignId'] && $thisstaff->canAssignTickets()) {
         //Assign ticket to staff or team.
         $ticket->assign($vars['assignId'], $vars['note']);
     } elseif ($vars['note']) {
         //Not assigned...save optional note if any
         $ticket->postNote('New Ticket', $vars['note'], false);
     } else {
         //Not assignment and no internal note - log activity
         $ticket->logActivity('New Ticket by Staff', 'Ticket created by staff -' . $thisstaff->getName());
     }
     $ticket->reload();
     if (!$cfg->notifyONNewStaffTicket() || !isset($var['alertuser'])) {
         return $ticket;
     }
     //No alerts.
     //Send Notice to user --- if requested AND enabled!!
     $dept = $ticket->getDept();
     if (!$dept || !($tpl = $dept->getTemplate())) {
         $tpl = $cfg->getDefaultTemplate();
     }
     if (!$dept || !($email = $dept->getEmail())) {
         $email = $cfg->getDefaultEmail();
     }
     if ($tpl && ($msg = $tpl->getNewTicketNoticeMsgTemplate()) && $email) {
         $message = $vars['issue'] . "\n\n" . $vars['response'];
         $body = $ticket->replaceTemplateVars($msg['body']);
         $subj = $ticket->replaceTemplateVars($msg['subj']);
         $body = str_replace('%message', $message, $body);
         if ($vars['signature'] == 'mine') {
             $signature = $thisstaff->getSignature();
         } elseif ($vars['signature'] == 'dept' && $dept && $dept->isPublic()) {
             $signature = $dept->getSignature();
         } else {
             $signature = '';
         }
         $body = str_replace('%signature', $signature, $body);
         if ($cfg->stripQuotedReply() && ($tag = trim($cfg->getReplySeparator()))) {
             $body = "\n{$tag}\n\n" . $body;
         }
         $attachments = $cfg->emailAttachments() && $respId ? $this->getAttachments($respId, 'R') : array();
         $email->send($ticket->getEmail(), $subj, $body, $attachments);
     }
     return $ticket;
 }