function getUser()
 {
     if (!$this->user && $this->getUserId()) {
         $this->user = User::lookup($this->getUserId());
     }
     return $this->user;
 }
Example #2
0
 public function action_index()
 {
     $headersOnly = false;
     if ($header = Request::current()->headers('Authorization')) {
         // Check for special case, because cURL sometimes does an
         // internal second request and doubles the authorization header,
         // which always resulted in an error.
         //
         // 1st request: Authorization: Bearer XXX
         // 2nd request: Authorization: Bearer XXX, Bearer XXX
         if (strpos($header, ',') !== false) {
             $headerPart = explode(',', $header);
             $accessToken = trim(preg_replace('/^(?:\\s+)?Bearer\\s/', '', $headerPart[0]));
         } else {
             $accessToken = trim(preg_replace('/^(?:\\s+)?Bearer\\s/', '', $header));
         }
         $accessToken = $accessToken === 'Bearer' ? '' : $accessToken;
     } elseif ($headersOnly === false) {
         $method = Request::current()->method() == 'GET' ? 'query' : 'post';
         $accessToken = Request::current()->query('access_token');
     }
     if (empty($accessToken)) {
         //return Oauth::$exceptions['invalid_request'];
         throw new Exception('Access token is missing');
     }
     $oatoken = Model::factory('oauth')->getAccessToken($accessToken);
     if ($oatoken['access_expires'] < time()) {
         //return Oauth::$exceptions['invalid_grant'];
         throw new Exception('Access token is expired');
     }
     $user = User::lookup($oatoken['user_id']);
     if ($user) {
         $user_info = array('id' => $user->id, 'email' => $user->mail, 'name' => $user->nick);
     } else {
         $user_info = array('message' => "User doesnt exists", 'Status code' => 400);
     }
     $this->response->body(json_encode($user_info));
 }
Example #3
0
 function changeUserForm($tid)
 {
     global $thisstaff;
     if (!$thisstaff || !($ticket = Ticket::lookup($tid)) || !$ticket->checkStaffAccess($thisstaff)) {
         Http::response(404, 'No such ticket');
     }
     $user = User::lookup($ticket->getOwnerId());
     $info = array('title' => sprintf('Change user for ticket #%s', $ticket->getNumber()));
     return self::_userlookup($user, null, $info);
 }
Example #4
0
 protected function validate($userid)
 {
     $number = $_SESSION['_auth']['user-ticket'];
     if (!($ticket = Ticket::lookupByNumber($number))) {
         return false;
     }
     if (!($user = User::lookup($userid))) {
         return false;
     }
     if (!($user = $this->_getTicketUser($ticket, $user))) {
         return false;
     }
     $user = new ClientSession($user);
     $user->flagGuest();
     return $user;
 }
 function addUser($id, $userId = 0, $remote = false)
 {
     global $thisstaff;
     if (!$thisstaff) {
         Http::response(403, 'Login Required');
     } elseif (!($org = Organization::lookup($id))) {
         Http::response(404, 'Unknown organization');
     }
     $info = array();
     $info['title'] = __('Add User');
     $info['action'] = '#orgs/' . $org->getId() . '/add-user';
     $info['onselect'] = 'ajax.php/orgs/' . $org->getId() . '/add-user/';
     $info['lookup'] = false;
     if (AuthenticationBackend::getSearchDirectories()) {
         $info['lookup'] = 'remote';
     }
     if ($_POST) {
         if ($_POST['id']) {
             //Existing useer
             if (!($user = User::lookup($_POST['id']))) {
                 $info['error'] = __('Unknown user selected');
             } elseif ($user->getOrgId() == $org->getId()) {
                 $info['error'] = sprintf('%s already belongs to the organization', Format::htmlchars($user->getName()));
             }
         } else {
             //Creating new  user
             $form = UserForm::getUserForm()->getForm($_POST);
             if (!($user = User::fromForm($form))) {
                 $info['error'] = __('Error adding user - try again!');
             }
         }
         if (!$info['error'] && $user && $user->setOrganization($org)) {
             Http::response(201, $user->to_json());
         } elseif (!$info['error']) {
             $info['error'] = __('Unable to add user to the organization - try again');
         }
     } elseif ($remote && $userId) {
         list($bk, $userId) = explode(':', $userId, 2);
         if (!($backend = AuthenticationBackend::getSearchDirectoryBackend($bk)) || !($user_info = $backend->lookup($userId))) {
             Http::response(404, 'User not found');
         }
         $form = UserForm::getUserForm()->getForm($user_info);
     } elseif ($userId) {
         //Selected local user
         $user = User::lookup($userId);
     }
     if ($user && $user->getOrgId()) {
         if ($user->getOrgId() == $org->getId()) {
             $info['warn'] = __('User already belongs to this organization!');
         } else {
             $info['warn'] = __("Are you sure you want to change the user's organization?");
         }
     }
     ob_start();
     include STAFFINC_DIR . 'templates/user-lookup.tmpl.php';
     $resp = ob_get_contents();
     ob_end_clean();
     return $resp;
 }
 public function getUser()
 {
     return \User::lookup($this->user_id);
 }
Example #7
0
 static function lookupByEmail($email)
 {
     if (!($user = User::lookup(array('emails__address' => $email)))) {
         return null;
     }
     return new EndUser($user);
 }
Example #8
0
    if (($id = $_config->get($_GET['token'])) && ($acct = ClientAccount::lookup(array('user_id' => $id)))) {
        if (!$acct->isConfirmed()) {
            $inc = 'register.confirmed.inc.php';
            $acct->confirm();
            // TODO: Log the user in
            if ($client = UserAuthenticationBackend::processSignOn($errors)) {
                if ($acct->hasPassword() && !$acct->get('backend')) {
                    $acct->cancelResetTokens();
                } else {
                    $_SESSION['_client']['reset-token'] = $_GET['token'];
                    $acct->forcePasswdReset();
                }
                Http::redirect('account.php?confirmed');
            }
        }
    } elseif ($id && ($user = User::lookup($id))) {
        $inc = 'pwreset.create.php';
    } else {
        Http::redirect('index.php');
    }
} elseif ($cfg->allowPasswordReset()) {
    $banner = __('Enter your username or email address below');
} else {
    $_SESSION['_staff']['auth']['msg'] = __('Password resets are disabled');
    return header('Location: index.php');
}
$nav = new UserNav();
$nav->setActiveNav('status');
require CLIENTINC_DIR . 'header.inc.php';
require CLIENTINC_DIR . $inc;
require CLIENTINC_DIR . 'footer.inc.php';
Example #9
0
 /**
  * Cooperates with the cron system to automatically find content that is
  * not index in the _search table and add it to the index.
  */
 function IndexOldStuff()
 {
     $class = get_class();
     $auto_create = function ($db_error) use($class) {
         if ($db_error != 1146) {
             // Perform the standard error handling
             return true;
         }
         // Create the search table automatically
         $class::__init();
     };
     // THREADS ----------------------------------
     $sql = "SELECT A1.`id`, A1.`title`, A1.`body`, A1.`format` FROM `" . TICKET_THREAD_TABLE . "` A1\n            LEFT JOIN `" . TABLE_PREFIX . "_search` A2 ON (A1.`id` = A2.`object_id` AND A2.`object_type`='H')\n            WHERE A2.`object_id` IS NULL AND (A1.poster <> 'SYSTEM')\n            AND (LENGTH(A1.`title`) + LENGTH(A1.`body`) > 0)\n            ORDER BY A1.`id` DESC";
     if (!($res = db_query_unbuffered($sql, $auto_create))) {
         return false;
     }
     while ($row = db_fetch_row($res)) {
         $body = ThreadBody::fromFormattedText($row[2], $row[3]);
         $body = $body->getSearchable();
         $title = Format::searchable($row[1]);
         if (!$body && !$title) {
             continue;
         }
         $record = array('H', $row[0], $title, $body);
         if (!$this->__index($record)) {
             return;
         }
     }
     // TICKETS ----------------------------------
     $sql = "SELECT A1.`ticket_id` FROM `" . TICKET_TABLE . "` A1\n            LEFT JOIN `" . TABLE_PREFIX . "_search` A2 ON (A1.`ticket_id` = A2.`object_id` AND A2.`object_type`='T')\n            WHERE A2.`object_id` IS NULL\n            ORDER BY A1.`ticket_id` DESC";
     if (!($res = db_query_unbuffered($sql, $auto_create))) {
         return false;
     }
     while ($row = db_fetch_row($res)) {
         $ticket = Ticket::lookup($row[0]);
         $cdata = $ticket->loadDynamicData();
         $content = array();
         foreach ($cdata as $k => $a) {
             if ($k != 'subject' && ($v = $a->getSearchable())) {
                 $content[] = $v;
             }
         }
         $record = array('T', $ticket->getId(), Format::searchable($ticket->getNumber() . ' ' . $ticket->getSubject()), implode("\n", $content));
         if (!$this->__index($record)) {
             return;
         }
     }
     // USERS ------------------------------------
     $sql = "SELECT A1.`id` FROM `" . USER_TABLE . "` A1\n            LEFT JOIN `" . TABLE_PREFIX . "_search` A2 ON (A1.`id` = A2.`object_id` AND A2.`object_type`='U')\n            WHERE A2.`object_id` IS NULL\n            ORDER BY A1.`id` DESC";
     if (!($res = db_query_unbuffered($sql, $auto_create))) {
         return false;
     }
     while ($row = db_fetch_row($res)) {
         $user = User::lookup($row[0]);
         $cdata = $user->getDynamicData();
         $content = array();
         foreach ($user->emails as $e) {
             $content[] = $e->address;
         }
         foreach ($cdata as $e) {
             foreach ($e->getAnswers() as $a) {
                 if ($c = $a->getSearchable()) {
                     $content[] = $c;
                 }
             }
         }
         $record = array('U', $user->getId(), Format::searchable($user->getFullName()), trim(implode("\n", $content)));
         if (!$this->__index($record)) {
             return;
         }
     }
     // ORGANIZATIONS ----------------------------
     $sql = "SELECT A1.`id` FROM `" . ORGANIZATION_TABLE . "` A1\n            LEFT JOIN `" . TABLE_PREFIX . "_search` A2 ON (A1.`id` = A2.`object_id` AND A2.`object_type`='O')\n            WHERE A2.`object_id` IS NULL\n            ORDER BY A1.`id` DESC";
     if (!($res = db_query_unbuffered($sql, $auto_create))) {
         return false;
     }
     while ($row = db_fetch_row($res)) {
         $org = Organization::lookup($row[0]);
         $cdata = $org->getDynamicData();
         $content = array();
         foreach ($cdata as $e) {
             foreach ($e->getAnswers() as $a) {
                 if ($c = $a->getSearchable()) {
                     $content[] = $c;
                 }
             }
         }
         $record = array('O', $org->getId(), Format::searchable($org->getName()), trim(implode("\n", $content)));
         if (!$this->__index($record)) {
             return null;
         }
     }
     // KNOWLEDGEBASE ----------------------------
     require_once INCLUDE_DIR . 'class.faq.php';
     $sql = "SELECT A1.`faq_id` FROM `" . FAQ_TABLE . "` A1\n            LEFT JOIN `" . TABLE_PREFIX . "_search` A2 ON (A1.`faq_id` = A2.`object_id` AND A2.`object_type`='K')\n            WHERE A2.`object_id` IS NULL\n            ORDER BY A1.`faq_id` DESC";
     if (!($res = db_query_unbuffered($sql, $auto_create))) {
         return false;
     }
     while ($row = db_fetch_row($res)) {
         $faq = FAQ::lookup($row[0]);
         $q = $faq->getQuestion();
         if ($k = $faq->getKeywords()) {
             $q = $k . ' ' . $q;
         }
         $record = array('K', $faq->getId(), Format::searchable($q), $faq->getSearchableAnswer());
         if (!$this->__index($record)) {
             return;
         }
     }
     // FILES ------------------------------------
     // Flush non-full batch of records
     $this->__index(null, true);
     if (!$this->_reindexed) {
         // Stop rebuilding the index
         $this->getConfig()->set('reindex', 0);
     }
 }
Example #10
0
 static function create($vars, &$errors, $origin, $autorespond = true, $alertstaff = true)
 {
     global $ost, $cfg, $thisclient, $_FILES;
     // Don't enforce form validation for email
     $field_filter = function ($type) use($origin) {
         return function ($f) use($origin, $type) {
             // Ultimately, only offer validation errors for web for
             // non-internal fields. For email, no validation can be
             // performed. For other origins, validate as usual
             switch (strtolower($origin)) {
                 case 'email':
                     return false;
                 case 'staff':
                     // Required 'Contact Information' fields aren't required
                     // when staff open tickets
                     return $type != 'user' || in_array($f->get('name'), array('name', 'email'));
                 case 'web':
                     return !$f->get('private');
                 default:
                     return true;
             }
         };
     };
     $reject_ticket = function ($message) use(&$errors) {
         global $ost;
         $errors = array('errno' => 403, 'err' => __('This help desk is for use by authorized users only'));
         $ost->logWarning(_S('Ticket Denied'), $message, false);
         return 0;
     };
     Signal::send('ticket.create.before', null, $vars);
     // Create and verify the dynamic form entry for the new ticket
     $form = TicketForm::getNewInstance();
     $form->setSource($vars);
     // If submitting via email or api, ensure we have a subject and such
     if (!in_array(strtolower($origin), array('web', 'staff'))) {
         foreach ($form->getFields() as $field) {
             $fname = $field->get('name');
             if ($fname && isset($vars[$fname]) && !$field->value) {
                 $field->value = $field->parse($vars[$fname]);
             }
         }
     }
     if (!$form->isValid($field_filter('ticket'))) {
         $errors += $form->errors();
     }
     /*INICIO
       Creado por Anthony Parisi
       2016-02-01
       Con las siguientes lineas de código, se crea el ticket mediante la API.*/
     if (!in_array(strtolower($origin), array('web', 'staff'))) {
         $errors = array();
     }
     /* FIN */
     if ($vars['uid']) {
         $user = User::lookup($vars['uid']);
     }
     $id = 0;
     $fields = array();
     $fields['message'] = array('type' => '*', 'required' => 1, 'error' => __('Message content is required'));
     switch (strtolower($origin)) {
         case 'web':
             $fields['topicId'] = array('type' => 'int', 'required' => 1, 'error' => __('Select a help topic'));
             break;
         case 'staff':
             $fields['deptId'] = array('type' => 'int', 'required' => 0, 'error' => __('Department selection is required'));
             $fields['topicId'] = array('type' => 'int', 'required' => 1, 'error' => __('Help topic selection is required'));
             $fields['duedate'] = array('type' => 'date', 'required' => 0, 'error' => __('Invalid date format - must be MM/DD/YY'));
         case 'api':
             $fields['source'] = array('type' => 'string', 'required' => 1, 'error' => __('Indicate ticket source'));
             break;
         case 'email':
             $fields['emailId'] = array('type' => 'int', 'required' => 1, 'error' => __('Unknown system email'));
             break;
         default:
             # TODO: Return error message
             $errors['err'] = $errors['origin'] = __('Invalid ticket origin given');
     }
     if (!Validator::process($fields, $vars, $errors) && !$errors['err']) {
         $errors['err'] = __('Missing or invalid data - check the errors and try again');
     }
     //Make sure the due date is valid
     if ($vars['duedate']) {
         if (!$vars['time'] || strpos($vars['time'], ':') === false) {
             $errors['time'] = __('Select a time from the list');
         } elseif (strtotime($vars['duedate'] . ' ' . $vars['time']) === false) {
             $errors['duedate'] = __('Invalid due date');
         } elseif (strtotime($vars['duedate'] . ' ' . $vars['time']) <= time()) {
             $errors['duedate'] = __('Due date must be in the future');
         }
     }
     if (!$errors) {
         # Perform ticket filter actions on the new ticket arguments
         $__form = null;
         if ($vars['topicId']) {
             if (($__topic = Topic::lookup($vars['topicId'])) && ($__form = $__topic->getForm())) {
                 $__form = $__form->instanciate();
                 $__form->setSource($vars);
             }
         }
         try {
             $vars = self::filterTicketData($origin, $vars, array($form, $__form), $user);
         } catch (RejectedException $ex) {
             return $reject_ticket(sprintf(_S('Ticket rejected (%s) by filter "%s"'), $ex->vars['email'], $ex->getRejectingFilter()->getName()));
         }
         //Make sure the open ticket limit hasn't been reached. (LOOP CONTROL)
         if ($cfg->getMaxOpenTickets() > 0 && strcasecmp($origin, 'staff') && ($_user = TicketUser::lookupByEmail($vars['email'])) && ($openTickets = $_user->getNumOpenTickets()) && $openTickets >= $cfg->getMaxOpenTickets()) {
             $errors = array('err' => __("You've reached the maximum open tickets allowed."));
             $ost->logWarning(sprintf(_S('Ticket denied - %s'), $vars['email']), sprintf(_S('Max open tickets (%1$d) reached for %2$s'), $cfg->getMaxOpenTickets(), $vars['email']), false);
             return 0;
         }
         // Allow vars to be changed in ticket filter and applied to the user
         // account created or detected
         if (!$user && $vars['email']) {
             $user = User::lookupByEmail($vars['email']);
         }
         if (!$user) {
             // Reject emails if not from registered clients (if
             // configured)
             if (strcasecmp($origin, 'email') === 0 && !$cfg->acceptUnregisteredEmail()) {
                 list($mailbox, $domain) = explode('@', $vars['email'], 2);
                 // Users not yet created but linked to an organization
                 // are still acceptable
                 if (!Organization::forDomain($domain)) {
                     return $reject_ticket(sprintf(_S('Ticket rejected (%s) (unregistered client)'), $vars['email']));
                 }
             }
             $user_form = UserForm::getUserForm()->getForm($vars);
             if (!$user_form->isValid($field_filter('user')) || !($user = User::fromVars($user_form->getClean()))) {
                 $errors['user'] = __('Incomplete client information');
             }
         }
     }
     if ($vars['topicId']) {
         if ($topic = Topic::lookup($vars['topicId'])) {
             if ($topic_form = $topic->getForm()) {
                 $TF = $topic_form->getForm($vars);
                 $topic_form = $topic_form->instanciate();
                 $topic_form->setSource($vars);
                 if (!$TF->isValid($field_filter('topic'))) {
                     $errors = array_merge($errors, $TF->errors());
                 }
             }
         } else {
             $errors['topicId'] = 'Invalid help topic selected';
         }
     }
     // Any error above is fatal.
     if ($errors) {
         return 0;
     }
     Signal::send('ticket.create.validated', null, $vars);
     # Some things will need to be unpacked back into the scope of this
     # function
     if (isset($vars['autorespond'])) {
         $autorespond = $vars['autorespond'];
     }
     # Apply filter-specific priority
     if ($vars['priorityId']) {
         $form->setAnswer('priority', null, $vars['priorityId']);
     }
     // If the filter specifies a help topic which has a form associated,
     // and there was previously either no help topic set or the help
     // topic did not have a form, there's no need to add it now as (1)
     // validation is closed, (2) there may be a form already associated
     // and filled out from the original  help topic, and (3) staff
     // members can always add more forms now
     // OK...just do it.
     $statusId = $vars['statusId'];
     $deptId = $vars['deptId'];
     //pre-selected Dept if any.
     $source = ucfirst($vars['source']);
     // Apply email settings for emailed tickets. Email settings should
     // trump help topic settins if the email has an associated help
     // topic
     if ($vars['emailId'] && ($email = Email::lookup($vars['emailId']))) {
         $deptId = $deptId ?: $email->getDeptId();
         $priority = $form->getAnswer('priority');
         if (!$priority || !$priority->getIdValue()) {
             $form->setAnswer('priority', null, $email->getPriorityId());
         }
         if ($autorespond) {
             $autorespond = $email->autoRespond();
         }
         if (!isset($topic) && ($T = $email->getTopic()) && $T->isActive()) {
             $topic = $T;
         }
         $email = null;
         $source = 'Email';
     }
     if (!isset($topic)) {
         // This may return NULL, no big deal
         $topic = $cfg->getDefaultTopic();
     }
     // Intenal mapping magic...see if we need to override anything
     if (isset($topic)) {
         $deptId = $deptId ?: $topic->getDeptId();
         $statusId = $statusId ?: $topic->getStatusId();
         $priority = $form->getAnswer('priority');
         if (!$priority || !$priority->getIdValue()) {
             $form->setAnswer('priority', null, $topic->getPriorityId());
         }
         if ($autorespond) {
             $autorespond = $topic->autoRespond();
         }
         //Auto assignment.
         if (!isset($vars['staffId']) && $topic->getStaffId()) {
             $vars['staffId'] = $topic->getStaffId();
         } elseif (!isset($vars['teamId']) && $topic->getTeamId()) {
             $vars['teamId'] = $topic->getTeamId();
         }
         //set default sla.
         if (isset($vars['slaId'])) {
             $vars['slaId'] = $vars['slaId'] ?: $cfg->getDefaultSLAId();
         } elseif ($topic && $topic->getSLAId()) {
             $vars['slaId'] = $topic->getSLAId();
         }
     }
     // Auto assignment to organization account manager
     if (($org = $user->getOrganization()) && $org->autoAssignAccountManager() && ($code = $org->getAccountManagerId())) {
         if (!isset($vars['staffId']) && $code[0] == 's') {
             $vars['staffId'] = substr($code, 1);
         } elseif (!isset($vars['teamId']) && $code[0] == 't') {
             $vars['teamId'] = substr($code, 1);
         }
     }
     // Last minute checks
     $priority = $form->getAnswer('priority');
     if (!$priority || !$priority->getIdValue()) {
         $form->setAnswer('priority', null, $cfg->getDefaultPriorityId());
     }
     $deptId = $deptId ?: $cfg->getDefaultDeptId();
     $statusId = $statusId ?: $cfg->getDefaultTicketStatusId();
     $topicId = isset($topic) ? $topic->getId() : 0;
     $ipaddress = $vars['ip'] ?: $_SERVER['REMOTE_ADDR'];
     $source = $source ?: 'Web';
     //We are ready son...hold on to the rails.
     $number = $topic ? $topic->getNewTicketNumber() : $cfg->getNewTicketNumber();
     $sql = 'INSERT INTO ' . TICKET_TABLE . ' SET created=NOW() ' . ' ,lastmessage= NOW()' . ' ,user_id=' . db_input($user->getId()) . ' ,`number`=' . db_input($number) . ' ,dept_id=' . db_input($deptId) . ' ,topic_id=' . db_input($topicId) . ' ,ip_address=' . db_input($ipaddress) . ' ,source=' . db_input($source);
     if (isset($vars['emailId']) && $vars['emailId']) {
         $sql .= ', email_id=' . db_input($vars['emailId']);
     }
     //Make sure the origin is staff - avoid firebug hack!
     if ($vars['duedate'] && !strcasecmp($origin, 'staff')) {
         $sql .= ' ,duedate=' . db_input(date('Y-m-d G:i', Misc::dbtime($vars['duedate'] . ' ' . $vars['time'])));
     }
     if (!db_query($sql) || !($id = db_insert_id()) || !($ticket = Ticket::lookup($id))) {
         return null;
     }
     /* -------------------- POST CREATE ------------------------ */
     // Save the (common) dynamic form
     $form->setTicketId($id);
     $form->save();
     // Save the form data from the help-topic form, if any
     if ($topic_form) {
         $topic_form->setTicketId($id);
         $topic_form->save();
     }
     $ticket->loadDynamicData();
     $dept = $ticket->getDept();
     // Add organizational collaborators
     if ($org && $org->autoAddCollabs()) {
         $pris = $org->autoAddPrimaryContactsAsCollabs();
         $members = $org->autoAddMembersAsCollabs();
         $settings = array('isactive' => true);
         $collabs = array();
         foreach ($org->allMembers() as $u) {
             if ($members || $pris && $u->isPrimaryContact()) {
                 if ($c = $ticket->addCollaborator($u, $settings, $errors)) {
                     $collabs[] = (string) $c;
                 }
             }
         }
         //TODO: Can collaborators add others?
         if ($collabs) {
             //TODO: Change EndUser to name of  user.
             $ticket->logNote(sprintf(_S('Collaborators for %s organization added'), $org->getName()), implode("<br>", $collabs), $org->getName(), false);
         }
     }
     //post the message.
     $vars['title'] = $vars['subject'];
     //Use the initial subject as title of the post.
     $vars['userId'] = $ticket->getUserId();
     $message = $ticket->postMessage($vars, $origin, false);
     // Configure service-level-agreement for this ticket
     $ticket->selectSLAId($vars['slaId']);
     // Assign ticket to staff or team (new ticket by staff)
     if ($vars['assignId']) {
         $ticket->assign($vars['assignId'], $vars['note']);
     } else {
         // Auto assign staff or team - auto assignment based on filter
         // rules. Both team and staff can be assigned
         if ($vars['staffId']) {
             $ticket->assignToStaff($vars['staffId'], _S('Auto Assignment'));
         }
         if ($vars['teamId']) {
             // No team alert if also assigned to an individual agent
             $ticket->assignToTeam($vars['teamId'], _S('Auto Assignment'), !$vars['staffId']);
         }
     }
     // Apply requested status — this should be done AFTER assignment,
     // because if it is requested to be closed, it should not cause the
     // ticket to be reopened for assignment.
     if ($statusId) {
         $ticket->setStatus($statusId, false, false);
     }
     /**********   double check auto-response  ************/
     //Override auto responder if the FROM email is one of the internal emails...loop control.
     if ($autorespond && Email::getIdByEmail($ticket->getEmail())) {
         $autorespond = false;
     }
     # Messages that are clearly auto-responses from email systems should
     # not have a return 'ping' message
     if (isset($vars['flags']) && $vars['flags']['bounce']) {
         $autorespond = false;
     }
     if ($autorespond && $message->isAutoReply()) {
         $autorespond = false;
     }
     //post canned auto-response IF any (disables new ticket auto-response).
     if ($vars['cannedResponseId'] && $ticket->postCannedReply($vars['cannedResponseId'], $message->getId(), $autorespond)) {
         $ticket->markUnAnswered();
         //Leave the ticket as unanswred.
         $autorespond = false;
     }
     //Check department's auto response settings
     // XXX: Dept. setting doesn't affect canned responses.
     if ($autorespond && $dept && !$dept->autoRespONNewTicket()) {
         $autorespond = false;
     }
     //Don't send alerts to staff when the message is a bounce
     //  this is necessary to avoid possible loop (especially on new ticket)
     if ($alertstaff && $message->isBounce()) {
         $alertstaff = false;
     }
     /***** See if we need to send some alerts ****/
     $ticket->onNewTicket($message, $autorespond, $alertstaff);
     /************ check if the user JUST reached the max. open tickets limit **********/
     if ($cfg->getMaxOpenTickets() > 0 && ($user = $ticket->getOwner()) && $user->getNumOpenTickets() == $cfg->getMaxOpenTickets()) {
         $ticket->onOpenLimit($autorespond && strcasecmp($origin, 'staff'));
     }
     /* Start tracking ticket lifecycle events */
     $ticket->logEvent('created');
     // Fire post-create signal (for extra email sending, searching)
     Signal::send('model.created', $ticket);
     /*INICIO
       Anthony Parisi
       2016-02-05
       Con las siguientes lineas de código, se actualizan los campos de 
       Detalle de su Solicitud en las tablas descritas en la Sentencia SQL*/
     if (!in_array(strtolower($origin), array('web', 'staff'))) {
         //echo "<pre>";
         //var_dump($vars);
         //die($vars['valores']);
         foreach ($ticket as $key => $value) {
             if ($key == "id") {
                 $ticket_idAPI = $value;
             }
             if ($key == "last_message") {
                 $last_message = $value;
                 $datos = explode("\n", $last_message);
                 $nombre = $vars['name'];
                 $correo = $vars['email'];
                 $telefono = $vars['phone'];
                 $valores = $vars['valores'];
                 $adicional = explode("%%", $valores);
                 //die($adicional[4]);
                 /*$nombre   = ucwords(strtolower(substr($datos[0], 20, strlen($datos[0])-21)));
                   $correo   = strtolower(substr($datos[1], 20, strlen($datos[1])-21));
                   $telefono = substr($datos[2], 22, strlen($datos[2])-23);
                   $i        = 5;
                   $mensaje  = "";
                   while(strpos($datos[$i], "------------------------------------------------------") === false){
                       $mensaje .= $datos[$i];
                       $i++;
                   }
                   for($i=5;$i < (count($datos)-6);$i++){
                       if(strpos($datos[$i], "TIPO DE PASAJE: ") > -1)
                           $pasaje = substr($datos[$i], 28, strlen($datos[$i])-29);
                       elseif(strpos($datos[$i], "CIUDAD DE ORIGEN: ") > -1)
                           $origen = substr($datos[$i], 18, strlen($datos[$i])-19);
                       elseif(strpos($datos[$i], "CIUDAD DE DESTINO: ") > -1)
                           $destino = substr($datos[$i], 21, strlen($datos[$i])-22);
                       elseif(strpos($datos[$i], "FECHA DE SALIDA: ") > -1)
                           $salida = substr($datos[$i], 17, strlen($datos[$i])-18);
                       elseif(strpos($datos[$i], "FECHA DE REGRESO: ") > -1)
                           $regreso = substr($datos[$i], 20, strlen($datos[$i])-21);
                       elseif(strpos($datos[$i], "CLASE: ") > -1)
                           $clase = substr($datos[$i], 19, strlen($datos[$i])-20);
                       elseif(strpos($datos[$i], "AEROL") > -1)
                           $aerolinea = substr($datos[$i], 14, strlen($datos[$i])-15);
                   }
                   $adultos = substr($datos[count($datos)-5], 9, strlen($datos[count($datos)-5])-10);
                   $mayores = substr($datos[count($datos)-4], 11, strlen($datos[count($datos)-4])-12);
                   $ninos = substr($datos[count($datos)-3], 9, strlen($datos[count($datos)-3])-10);
                   $bebes = substr($datos[count($datos)-2], 8, strlen($datos[count($datos)-2])-9);*/
             }
         }
         $detail = '{"88":"Cotizacion PopPup"}';
         $mysqli = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
         $mysqli->query("UPDATE `ost_form_entry_values` SET `value` = '{$detail}' WHERE field_id = '20' AND `entry_id` = (SELECT id FROM ost_form_entry WHERE object_id = '{$ticket_idAPI}' AND object_type = 'T');");
         $mysqli->query("INSERT INTO `ost_ticket__cdata` SET `subject`='88', `ticket_id`= '{$ticket_idAPI}' ON DUPLICATE KEY UPDATE `subject`='88';");
         $sqlUser = $mysqli->query("SELECT id FROM ost_user WHERE id = '" . $user->getId() . "' AND `org_id` = 30 LIMIT 1;");
         $rowUser = mysqli_num_rows($sqlUser);
         if ($rowUser <= 0) {
             $mysqli->query("UPDATE ost_user SET `org_id` = 30, `updated` = NOW() WHERE id = " . $user->getId() . " LIMIT 1;");
         }
         $mysqli->query("INSERT INTO \n                                `ost_cotizaciones` (\n                                    `ticket_id`, \n                                    `nombre`, \n                                    `correo`, \n                                    `telefono`, \n                                    `mensaje`, \n                                    `tipo_vuelo`, \n                                    `origen`, \n                                    `destino`, \n                                    `salida`, \n                                    `regreso`, \n                                    `clase`, \n                                    `aerolinea`, \n                                    `adultos`, \n                                    `mayores`, \n                                    `ninos`, \n                                    `bebe`) \n                                VALUES (\n                                    '{$ticket_idAPI}', \n                                    '{$nombre}', \n                                    '{$correo}', \n                                    '{$telefono}', \n                                    '{$adicional['0']}', \n                                    '{$adicional['1']}', \n                                    '{$adicional['2']}', \n                                    '{$adicional['3']}', \n                                    '{$adicional['4']}', \n                                    '{$adicional['5']}', \n                                    '{$adicional['6']}', \n                                    '{$adicional['7']}', \n                                    '{$adicional['8']}', \n                                    '{$adicional['9']}', \n                                    '{$adicional['10']}', \n                                    '{$adicional['11']}');");
     }
     /* FIN */
     /* Phew! ... time for tea (KETEPA) */
     return $ticket;
 }
 function add($vars, &$errors)
 {
     if (!$vars || !is_array($vars) || !$vars['ticketId']) {
         $errors['err'] = __('Missing or invalid data');
     } elseif (!$vars['message']) {
         $errors['message'] = __('Message content is required');
     }
     if ($errors) {
         return false;
     }
     $vars['type'] = 'M';
     $vars['body'] = $vars['message'];
     if (!$vars['poster'] && $vars['userId'] && ($user = User::lookup($vars['userId']))) {
         $vars['poster'] = (string) $user->getName();
     }
     return ThreadEntry::add($vars);
 }
Example #12
0
 function updateInfo($vars, &$errors, $staff = false)
 {
     $valid = true;
     $forms = $this->getDynamicData();
     foreach ($forms as $cd) {
         $cd->setSource($vars);
         if ($staff && !$cd->isValidForStaff()) {
             $valid = false;
         } elseif (!$cd->isValidForClient()) {
             $valid = false;
         } elseif ($cd->get('type') == 'U' && ($form = $cd->getForm()) && ($f = $form->getField('email')) && $f->getClean() && ($u = User::lookup(array('emails__address' => $f->getClean()))) && $u->id != $this->getId()) {
             $valid = false;
             $f->addError(__('Email is assigned to another user'));
         }
     }
     if (!$valid) {
         return false;
     }
     foreach ($this->getDynamicData() as $cd) {
         if (($f = $cd->getForm()) && $f->get('type') == 'U') {
             if ($name = $f->getField('name')) {
                 $this->name = $name->getClean();
                 $this->save();
             }
             if ($email = $f->getField('email')) {
                 $this->default_email->address = $email->getClean();
                 $this->default_email->save();
             }
         }
         $cd->save();
     }
     return true;
 }
Example #13
0
     if (is_numeric($status)) {
         $msg = "Successfully imported {$status} clients";
     } else {
         $errors['err'] = $status;
     }
     break;
 case 'remove-users':
     if (!$org) {
         $errors['err'] = ' Trying to remove users from unknown
          organization';
     } elseif (!$_POST['ids'] || !is_array($_POST['ids']) || !count($_POST['ids'])) {
         $errors['err'] = 'You must select at least one user to remove';
     } else {
         $i = 0;
         foreach ($_POST['ids'] as $k => $v) {
             if (($u = User::lookup($v)) && $org->removeUser($u)) {
                 $i++;
             }
         }
         $num = count($_POST['ids']);
         if ($i && $i == $num) {
             $msg = 'Selected users removed successfully';
         } elseif ($i > 0) {
             $warn = "{$i} of {$num} selected users removed";
         } elseif (!$errors['err']) {
             $errors['err'] = 'Unable to remove selected users';
         }
     }
     break;
 default:
     $errors['err'] = 'Unknown action';
Example #14
0
				<?php 
echo HTML::anchor("buddy/sent/" . $id, __('Sent'), array('class' => 'buddy btn btn-default pull-right', 'title' => __('View sent list')));
?>
				<?php 
echo HTML::anchor("buddy/" . $id, __('Friends'), array('class' => 'buddy btn btn-default pull-right', 'title' => __('View Friends list')));
?>
			</div>
			<div class="clearfix"></div>
		</div>
		
		<?php 
foreach ($pendings as $pending) {
    ?>
			<div class="list-group-item allusers panel-body col-md-12">
				<?php 
    $accept = User::lookup($pending['request_from']);
    ?>
				<?php 
    if ($accept) {
        ?>
					<div class="col-md-2">
					    <?php 
        echo HTML::anchor("user/view/" . $accept->id, User::getAvatar($accept, array('size' => 80)), array('class' => 'action-view', 'title' => __('view profile')));
        ?>
					</div>
					<div class="col-md-5">
					    <?php 
        echo HTML::anchor("user/view/" . $accept->id, $accept->nick, array('class' => 'action-view', 'title' => __('view profile')));
        ?>
</br>
					    <?php 
 function updateForms($user_id)
 {
     global $thisstaff;
     if (!$thisstaff) {
         Http::response(403, "Login required");
     } elseif (!($user = User::lookup($user_id))) {
         Http::response(404, "No such customer");
     } elseif (!isset($_POST['forms'])) {
         Http::response(422, "Send updated forms list");
     }
     // Add new forms
     $forms = DynamicFormEntry::forUser($user_id);
     foreach ($_POST['forms'] as $sort => $id) {
         $found = false;
         foreach ($forms as $e) {
             if ($e->get('form_id') == $id) {
                 $e->set('sort', $sort);
                 $e->save();
                 $found = true;
                 break;
             }
         }
         // New form added
         if (!$found && ($new = DynamicForm::lookup($id))) {
             $user->addForm($new, $sort);
         }
     }
     // Deleted forms
     foreach ($forms as $idx => $e) {
         if (!in_array($e->get('form_id'), $_POST['forms'])) {
             $e->delete();
         }
     }
     Http::response(201, 'Successfully managed');
 }
Example #16
0
if (Auth::instance()->logged_in() && $enable_buddy) {
    ?>
			<div class="list-group list-all1 panel panel-info">
				<div class="panel-heading">
					<h3 class="panel-title"><?php 
    echo __('Friends');
    ?>
</h3>
				</div>

				<?php 
    foreach ($friends as $id) {
        ?>
					<div class="list-group-item friends panel-body">
						<?php 
        $accept = User::lookup($id);
        ?>
						<?php 
        echo HTML::anchor("user/view/" . $accept->id, User::getAvatar($accept), array('class' => 'action-view', 'rel' => "popover", 'data-placement' => "right", 'rel1' => "tooltip", 'data-html' => "true", 'data-original-title' => "<strong>{$accept->nick}</strong>"));
        ?>
						<?php 
        echo HTML::anchor("user/view/" . $accept->id, $accept->nick, array('class' => 'action-view', 'title' => __('view profile')));
        ?>

						<?php 
        if ($is_owner) {
            ?>
							<?php 
            echo HTML::anchor("buddy/delete/" . $accept->id, '<i class="fa fa-trash-o"></i>', array('class' => 'action-delete pull-right', 'title' => __('Delete')));
            ?>
						<?php 
Example #17
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;
    }
Example #18
0
                 break;
             case 'unbanemail':
                 if (!$thisstaff->canBanEmails()) {
                     $errors['err'] = __('Permission Denied. You are not allowed to remove emails from banlist.');
                 } elseif (Banlist::remove($ticket->getEmail())) {
                     $msg = __('Email removed from banlist');
                 } elseif (!BanList::includes($ticket->getEmail())) {
                     $warn = __('Email is not in the banlist');
                 } else {
                     $errors['err'] = __('Unable to remove the email from banlist. Try again.');
                 }
                 break;
             case 'changeuser':
                 if (!$thisstaff->canEditTickets()) {
                     $errors['err'] = __('Permission Denied. You are not allowed to edit tickets');
                 } elseif (!$_POST['user_id'] || !($user = User::lookup($_POST['user_id']))) {
                     $errors['err'] = __('Unknown user selected');
                 } elseif ($ticket->changeOwner($user)) {
                     $msg = sprintf(__('Ticket ownership changed to %s'), Format::htmlchars($user->getName()));
                 } else {
                     $errors['err'] = __('Unable to change ticket ownership. Try again');
                 }
                 break;
             default:
                 $errors['err'] = __('You must select action to perform');
         }
         break;
     default:
         $errors['err'] = __('Unknown action');
 }
 if ($ticket && is_object($ticket)) {
Example #19
0
 static function create($vars, &$errors, $origin, $autorespond = true, $alertstaff = true)
 {
     global $ost, $cfg, $thisclient, $_FILES;
     // Don't enforce form validation for email
     $field_filter = function ($type) use($origin) {
         return function ($f) use($origin, $type) {
             // Ultimately, only offer validation errors for web for
             // non-internal fields. For email, no validation can be
             // performed. For other origins, validate as usual
             switch (strtolower($origin)) {
                 case 'email':
                     return false;
                 case 'staff':
                     // Required 'Contact Information' fields aren't required
                     // when staff open tickets
                     return $type != 'user' || in_array($f->get('name'), array('name', 'email'));
                 case 'web':
                     return !$f->get('private');
                 default:
                     return true;
             }
         };
     };
     $reject_ticket = function ($message) use(&$errors) {
         global $ost;
         $errors = array('errno' => 403, 'err' => __('This help desk is for use by authorized users only'));
         $ost->logWarning(_S('Ticket Denied'), $message, false);
         return 0;
     };
     Signal::send('ticket.create.before', null, $vars);
     // Create and verify the dynamic form entry for the new ticket
     $form = TicketForm::getNewInstance();
     $form->setSource($vars);
     // If submitting via email or api, ensure we have a subject and such
     if (!in_array(strtolower($origin), array('web', 'staff'))) {
         foreach ($form->getFields() as $field) {
             $fname = $field->get('name');
             if ($fname && isset($vars[$fname]) && !$field->value) {
                 $field->value = $field->parse($vars[$fname]);
             }
         }
     }
     if (!$form->isValid($field_filter('ticket'))) {
         $errors += $form->errors();
     }
     if ($vars['uid']) {
         $user = User::lookup($vars['uid']);
     }
     $id = 0;
     $fields = array();
     $fields['message'] = array('type' => '*', 'required' => 1, 'error' => __('Message content is required'));
     switch (strtolower($origin)) {
         case 'web':
             $fields['topicId'] = array('type' => 'int', 'required' => 1, 'error' => __('Select a help topic'));
             break;
         case 'staff':
             $fields['deptId'] = array('type' => 'int', 'required' => 0, 'error' => __('Department selection is required'));
             $fields['topicId'] = array('type' => 'int', 'required' => 1, 'error' => __('Help topic selection is required'));
             $fields['duedate'] = array('type' => 'date', 'required' => 0, 'error' => __('Invalid date format - must be MM/DD/YY'));
         case 'api':
             $fields['source'] = array('type' => 'string', 'required' => 1, 'error' => __('Indicate ticket source'));
             break;
         case 'email':
             $fields['emailId'] = array('type' => 'int', 'required' => 1, 'error' => __('Unknown system email'));
             break;
         default:
             # TODO: Return error message
             $errors['err'] = $errors['origin'] = __('Invalid ticket origin given');
     }
     if (!Validator::process($fields, $vars, $errors) && !$errors['err']) {
         $errors['err'] = __('Missing or invalid data - check the errors and try again');
     }
     //Make sure the due date is valid
     if ($vars['duedate']) {
         if (!$vars['time'] || strpos($vars['time'], ':') === false) {
             $errors['time'] = __('Select a time from the list');
         } elseif (strtotime($vars['duedate'] . ' ' . $vars['time']) === false) {
             $errors['duedate'] = __('Invalid due date');
         } elseif (strtotime($vars['duedate'] . ' ' . $vars['time']) <= time()) {
             $errors['duedate'] = __('Due date must be in the future');
         }
     }
     if (!$errors) {
         # Perform ticket filter actions on the new ticket arguments
         $__form = null;
         if ($vars['topicId']) {
             if (($__topic = Topic::lookup($vars['topicId'])) && ($__form = $__topic->getForm())) {
                 $__form = $__form->instanciate();
                 $__form->setSource($vars);
             }
         }
         try {
             $vars = self::filterTicketData($origin, $vars, array($form, $__form), $user);
         } catch (RejectedException $ex) {
             return $reject_ticket(sprintf(_S('Ticket rejected (%s) by filter "%s"'), $ex->vars['email'], $ex->getRejectingFilter()->getName()));
         }
         //Make sure the open ticket limit hasn't been reached. (LOOP CONTROL)
         if ($cfg->getMaxOpenTickets() > 0 && strcasecmp($origin, 'staff') && ($_user = TicketUser::lookupByEmail($vars['email'])) && ($openTickets = $_user->getNumOpenTickets()) && $openTickets >= $cfg->getMaxOpenTickets()) {
             $errors = array('err' => __("You've reached the maximum open tickets allowed."));
             $ost->logWarning(sprintf(_S('Ticket denied - %s'), $vars['email']), sprintf(_S('Max open tickets (%1$d) reached for %2$s'), $cfg->getMaxOpenTickets(), $vars['email']), false);
             return 0;
         }
         // Allow vars to be changed in ticket filter and applied to the user
         // account created or detected
         if (!$user && $vars['email']) {
             $user = User::lookupByEmail($vars['email']);
         }
         if (!$user) {
             // Reject emails if not from registered clients (if
             // configured)
             if (strcasecmp($origin, 'email') === 0 && !$cfg->acceptUnregisteredEmail()) {
                 list($mailbox, $domain) = explode('@', $vars['email'], 2);
                 // Users not yet created but linked to an organization
                 // are still acceptable
                 if (!Organization::forDomain($domain)) {
                     return $reject_ticket(sprintf(_S('Ticket rejected (%s) (unregistered client)'), $vars['email']));
                 }
             }
             $user_form = UserForm::getUserForm()->getForm($vars);
             if (!$user_form->isValid($field_filter('user')) || !($user = User::fromVars($user_form->getClean()))) {
                 $errors['user'] = __('Incomplete client information');
             }
         }
     }
     if ($vars['topicId']) {
         if ($topic = Topic::lookup($vars['topicId'])) {
             if ($topic_form = $topic->getForm()) {
                 $TF = $topic_form->getForm($vars);
                 $topic_form = $topic_form->instanciate();
                 $topic_form->setSource($vars);
                 if (!$TF->isValid($field_filter('topic'))) {
                     $errors = array_merge($errors, $TF->errors());
                 }
             }
         } else {
             $errors['topicId'] = 'Invalid help topic selected';
         }
     }
     // Any error above is fatal.
     if ($errors) {
         return 0;
     }
     Signal::send('ticket.create.validated', null, $vars);
     # Some things will need to be unpacked back into the scope of this
     # function
     if (isset($vars['autorespond'])) {
         $autorespond = $vars['autorespond'];
     }
     # Apply filter-specific priority
     if ($vars['priorityId']) {
         $form->setAnswer('priority', null, $vars['priorityId']);
     }
     // If the filter specifies a help topic which has a form associated,
     // and there was previously either no help topic set or the help
     // topic did not have a form, there's no need to add it now as (1)
     // validation is closed, (2) there may be a form already associated
     // and filled out from the original  help topic, and (3) staff
     // members can always add more forms now
     // OK...just do it.
     $statusId = $vars['statusId'];
     $deptId = $vars['deptId'];
     //pre-selected Dept if any.
     $source = ucfirst($vars['source']);
     // Apply email settings for emailed tickets. Email settings should
     // trump help topic settins if the email has an associated help
     // topic
     if ($vars['emailId'] && ($email = Email::lookup($vars['emailId']))) {
         $deptId = $deptId ?: $email->getDeptId();
         $priority = $form->getAnswer('priority');
         if (!$priority || !$priority->getIdValue()) {
             $form->setAnswer('priority', null, $email->getPriorityId());
         }
         if ($autorespond) {
             $autorespond = $email->autoRespond();
         }
         if (!isset($topic) && ($T = $email->getTopic()) && $T->isActive()) {
             $topic = $T;
         }
         $email = null;
         $source = 'Email';
     }
     if (!isset($topic)) {
         // This may return NULL, no big deal
         $topic = $cfg->getDefaultTopic();
     }
     // Intenal mapping magic...see if we need to override anything
     if (isset($topic)) {
         $deptId = $deptId ?: $topic->getDeptId();
         $statusId = $statusId ?: $topic->getStatusId();
         $priority = $form->getAnswer('priority');
         if (!$priority || !$priority->getIdValue()) {
             $form->setAnswer('priority', null, $topic->getPriorityId());
         }
         if ($autorespond) {
             $autorespond = $topic->autoRespond();
         }
         //Auto assignment.
         if (!isset($vars['staffId']) && $topic->getStaffId()) {
             $vars['staffId'] = $topic->getStaffId();
         } elseif (!isset($vars['teamId']) && $topic->getTeamId()) {
             $vars['teamId'] = $topic->getTeamId();
         }
         //set default sla.
         if (isset($vars['slaId'])) {
             $vars['slaId'] = $vars['slaId'] ?: $cfg->getDefaultSLAId();
         } elseif ($topic && $topic->getSLAId()) {
             $vars['slaId'] = $topic->getSLAId();
         }
     }
     // Auto assignment to organization account manager
     if (($org = $user->getOrganization()) && $org->autoAssignAccountManager() && ($code = $org->getAccountManagerId())) {
         if (!isset($vars['staffId']) && $code[0] == 's') {
             $vars['staffId'] = substr($code, 1);
         } elseif (!isset($vars['teamId']) && $code[0] == 't') {
             $vars['teamId'] = substr($code, 1);
         }
     }
     // Last minute checks
     $priority = $form->getAnswer('priority');
     if (!$priority || !$priority->getIdValue()) {
         $form->setAnswer('priority', null, $cfg->getDefaultPriorityId());
     }
     $deptId = $deptId ?: $cfg->getDefaultDeptId();
     $statusId = $statusId ?: $cfg->getDefaultTicketStatusId();
     $topicId = isset($topic) ? $topic->getId() : 0;
     $ipaddress = $vars['ip'] ?: $_SERVER['REMOTE_ADDR'];
     $source = $source ?: 'Web';
     //We are ready son...hold on to the rails.
     $number = $topic ? $topic->getNewTicketNumber() : $cfg->getNewTicketNumber();
     $sql = 'INSERT INTO ' . TICKET_TABLE . ' SET created=NOW() ' . ' ,lastmessage= NOW()' . ' ,user_id=' . db_input($user->getId()) . ' ,`number`=' . db_input($number) . ' ,dept_id=' . db_input($deptId) . ' ,topic_id=' . db_input($topicId) . ' ,ip_address=' . db_input($ipaddress) . ' ,source=' . db_input($source);
     if (isset($vars['emailId']) && $vars['emailId']) {
         $sql .= ', email_id=' . db_input($vars['emailId']);
     }
     //Make sure the origin is staff - avoid firebug hack!
     if ($vars['duedate'] && !strcasecmp($origin, 'staff')) {
         $sql .= ' ,duedate=' . db_input(date('Y-m-d G:i', Misc::dbtime($vars['duedate'] . ' ' . $vars['time'])));
     }
     if (!db_query($sql) || !($id = db_insert_id()) || !($ticket = Ticket::lookup($id))) {
         return null;
     }
     /* -------------------- POST CREATE ------------------------ */
     // Save the (common) dynamic form
     $form->setTicketId($id);
     $form->save();
     // Save the form data from the help-topic form, if any
     if ($topic_form) {
         $topic_form->setTicketId($id);
         $topic_form->save();
     }
     $ticket->loadDynamicData();
     $dept = $ticket->getDept();
     // Add organizational collaborators
     if ($org && $org->autoAddCollabs()) {
         $pris = $org->autoAddPrimaryContactsAsCollabs();
         $members = $org->autoAddMembersAsCollabs();
         $settings = array('isactive' => true);
         $collabs = array();
         foreach ($org->allMembers() as $u) {
             if ($members || $pris && $u->isPrimaryContact()) {
                 if ($c = $ticket->addCollaborator($u, $settings, $errors)) {
                     $collabs[] = (string) $c;
                 }
             }
         }
         //TODO: Can collaborators add others?
         if ($collabs) {
             //TODO: Change EndUser to name of  user.
             $ticket->logNote(sprintf(_S('Collaborators for %s organization added'), $org->getName()), implode("<br>", $collabs), $org->getName(), false);
         }
     }
     //post the message.
     $vars['title'] = $vars['subject'];
     //Use the initial subject as title of the post.
     $vars['userId'] = $ticket->getUserId();
     $message = $ticket->postMessage($vars, $origin, false);
     // Configure service-level-agreement for this ticket
     $ticket->selectSLAId($vars['slaId']);
     // Assign ticket to staff or team (new ticket by staff)
     if ($vars['assignId']) {
         $ticket->assign($vars['assignId'], $vars['note']);
     } else {
         // Auto assign staff or team - auto assignment based on filter
         // rules. Both team and staff can be assigned
         if ($vars['staffId']) {
             $ticket->assignToStaff($vars['staffId'], _S('Auto Assignment'));
         }
         if ($vars['teamId']) {
             // No team alert if also assigned to an individual agent
             $ticket->assignToTeam($vars['teamId'], _S('Auto Assignment'), !$vars['staffId']);
         }
     }
     // Apply requested status — this should be done AFTER assignment,
     // because if it is requested to be closed, it should not cause the
     // ticket to be reopened for assignment.
     if ($statusId) {
         $ticket->setStatus($statusId, false, false);
     }
     /**********   double check auto-response  ************/
     //Override auto responder if the FROM email is one of the internal emails...loop control.
     if ($autorespond && Email::getIdByEmail($ticket->getEmail())) {
         $autorespond = false;
     }
     # Messages that are clearly auto-responses from email systems should
     # not have a return 'ping' message
     if (isset($vars['flags']) && $vars['flags']['bounce']) {
         $autorespond = false;
     }
     if ($autorespond && $message->isAutoReply()) {
         $autorespond = false;
     }
     //post canned auto-response IF any (disables new ticket auto-response).
     if ($vars['cannedResponseId'] && $ticket->postCannedReply($vars['cannedResponseId'], $message->getId(), $autorespond)) {
         $ticket->markUnAnswered();
         //Leave the ticket as unanswred.
         $autorespond = false;
     }
     //Check department's auto response settings
     // XXX: Dept. setting doesn't affect canned responses.
     if ($autorespond && $dept && !$dept->autoRespONNewTicket()) {
         $autorespond = false;
     }
     //Don't send alerts to staff when the message is a bounce
     //  this is necessary to avoid possible loop (especially on new ticket)
     if ($alertstaff && $message->isBounce()) {
         $alertstaff = false;
     }
     /***** See if we need to send some alerts ****/
     $ticket->onNewTicket($message, $autorespond, $alertstaff);
     /************ check if the user JUST reached the max. open tickets limit **********/
     if ($cfg->getMaxOpenTickets() > 0 && ($user = $ticket->getOwner()) && $user->getNumOpenTickets() == $cfg->getMaxOpenTickets()) {
         $ticket->onOpenLimit($autorespond && strcasecmp($origin, 'staff'));
     }
     /* Start tracking ticket lifecycle events */
     $ticket->logEvent('created');
     // Fire post-create signal (for extra email sending, searching)
     Signal::send('model.created', $ticket);
     /* Phew! ... time for tea (KETEPA) */
     return $ticket;
 }
Example #20
0
require 'client.inc.php';
$inc = 'register.inc.php';
$errors = array();
if (!$cfg || !$cfg->isClientRegistrationEnabled()) {
    Http::redirect('index.php');
} elseif ($thisclient) {
    // Guest registering for an account
    if ($thisclient->isGuest()) {
        foreach ($thisclient->getForms() as $f) {
            if ($f->get('type') == 'U') {
                $user_form = $f;
            }
        }
        $user_form->getField('email')->configure('disabled', true);
    } else {
        $user = User::lookup($thisclient->getId());
        $content = Page::lookup(Page::getIdByType('registration-thanks'));
        $inc = isset($_GET['confirmed']) ? 'register.confirmed.inc.php' : 'profile.inc.php';
    }
}
if ($user && $_POST) {
    if ($acct = $thisclient->getAccount()) {
        $acct->update($_POST, $errors);
    }
    if (!$errors && $user->updateInfo($_POST, $errors)) {
        Http::redirect('tickets.php');
    }
} elseif ($_POST) {
    $user_form = UserForm::getUserForm()->getForm($_POST);
    if ($thisclient) {
        $user_form->getField('email')->configure('disabled', true);
Example #21
0
</h2>
 <table class="form_table" width="940" border="0" cellspacing="0" cellpadding="2">
    <tbody>
        <tr>
            <th colspan="2">
                <em><strong><?php 
echo __('User Information');
?>
</strong>: <?php 
echo __('Currently selected user');
?>
</em>
            </th>
        </tr>
    <?php 
if (!$info['user_id'] || !($user = User::lookup($info['user_id']))) {
    $user = $ticket->getUser();
}
?>
    <tr><td><?php 
echo __('User');
?>
:</td><td>
        <div id="client-info">
            <a href="#" onclick="javascript:
                $.userLookup('ajax.php/users/<?php 
echo $ticket->getOwnerId();
?>
/edit',
                        function (user) {
                            $('#client-name').text(user.name);
Example #22
0
    users.php

    Peter Rotich <*****@*****.**>
    Jared Hancock <*****@*****.**>
    Copyright (c)  2006-2014 osTicket
    http://www.osticket.com

    Released under the GNU General Public License WITHOUT ANY WARRANTY.
    See LICENSE.TXT for details.

    vim: expandtab sw=4 ts=4 sts=4:
**********************************************************************/
require 'staff.inc.php';
require_once INCLUDE_DIR . 'class.note.php';
$user = null;
if ($_REQUEST['id'] && !($user = User::lookup($_REQUEST['id']))) {
    $errors['err'] = 'Unknown or invalid user ID.';
}
if ($_POST) {
    switch (strtolower($_REQUEST['do'])) {
        case 'update':
            if (!$user) {
                $errors['err'] = 'Unknown or invalid user.';
            } elseif (($acct = $user->getAccount()) && !$acct->update($_POST, $errors)) {
                $errors['err'] = 'Unable to update user account information';
            } elseif ($user->updateInfo($_POST, $errors)) {
                $msg = 'User updated successfully';
                $_REQUEST['a'] = null;
            } elseif (!$errors['err']) {
                $errors['err'] = 'Unable to update user profile. Correct any error(s) below and try again!';
            }
Example #23
0
				<?php 
echo HTML::anchor("buddy/" . $id, __('Friends'), array('class' => 'buddy btn btn-default pull-right', 'title' => __('View Friends list')));
?>
				<?php 
echo HTML::anchor("buddy/pending/" . $id, __('Pending'), array('class' => 'buddy btn btn-default pull-right', 'title' => __('View Sent list')));
?>
			</div>
			<div class="clearfix"></div>
		</div>
		
		<?php 
foreach ($sents as $sent) {
    ?>
			<div class="list-group-item allusers panel-body">
				<?php 
    $accept = User::lookup($sent['request_to']);
    ?>
				<?php 
    if ($accept) {
        ?>
					<div class="col-md-2">
					   <?php 
        echo HTML::anchor("user/view/" . $accept->id, User::getAvatar($accept, array('size' => 80)), array('class' => 'action-view', 'title' => __('view profile')));
        ?>
					</div>
					<div class="col-md-5">
					    <?php 
        echo HTML::anchor("user/view/" . $accept->id, $accept->nick, array('class' => 'action-view', 'title' => __('view profile')));
        ?>
</br>
					    <?php