function testValidEmail() { // Common emails $this->assert(Validator::is_email('*****@*****.**')); $this->assert(Validator::is_email('*****@*****.**')); $this->assert(Validator::is_email('*****@*****.**')); $this->assert(Validator::is_email('*****@*****.**')); $this->assert(Validator::is_email('*****@*****.**')); $this->assert(Validator::is_email('*****@*****.**')); // Illegal or unsupported $this->assert(!Validator::is_email('jared r@domain.tld')); $this->assert(!Validator::is_email('jared')); $this->assert(!Validator::is_email('jared@')); $this->assert(!Validator::is_email('@domain.tld')); $this->assert(!Validator::is_email('@domain.tld, @domain2.tld')); // Odd cases, but legal $this->assert(Validator::is_email('jared@host')); $this->assert(Validator::is_email('jared@[127.0.0.1]')); $this->assert(Validator::is_email('jared@[ipv6:::1]')); $this->assert(Validator::is_email('*@domain.tld')); $this->assert(Validator::is_email("'@domain.tld")); $this->assert(Validator::is_email('"jared r"@domain.tld')); // RFC 6530 #$this->assert(Validator::is_email('Pelé@example.com')); #$this->assert(Validator::is_email('δοκιμή@παράδειγμα.δοκιμή')); #$this->assert(Validator::is_email('甲斐@黒川.日本')); }
function load($var = '') { if (!$var && !($var = $this->getId())) { return false; } $sql = 'SELECT staff.created as added, grp.*, staff.* ' . ' FROM ' . STAFF_TABLE . ' staff ' . ' LEFT JOIN ' . GROUP_TABLE . ' grp ON(grp.group_id=staff.group_id) WHERE '; if (is_numeric($var)) { $sql .= 'staff_id=' . db_input($var); } elseif (Validator::is_email($var)) { $sql .= 'email=' . db_input($var); } elseif (is_string($var)) { $sql .= 'username='******'staff_id']; $this->teams = $this->ht['teams'] = array(); $this->group = $this->dept = null; $this->departments = $this->stats = array(); $this->config = new Config('staff.' . $this->id); //WE have to patch info here to support upgrading from old versions. if ($time = strtotime($this->ht['passwdreset'] ? $this->ht['passwdreset'] : $this->ht['added'])) { $this->ht['passwd_change'] = time() - $time; } //XXX: check timezone issues. if ($this->ht['timezone_id']) { $this->ht['tz_offset'] = Timezone::getOffsetById($this->ht['timezone_id']); } elseif ($this->ht['timezone_offset']) { $this->ht['tz_offset'] = $this->ht['timezone_offset']; } return $this->id; }
function update($vars, &$errors) { global $thisstaff; if (!$thisstaff) { $errors['err'] = __('Access Denied'); return false; } // TODO: Make sure the username is unique if (!$vars['timezone_id']) { $errors['timezone_id'] = __('Time zone selection is required'); } // Changing password? if ($vars['passwd1'] || $vars['passwd2']) { if (!$vars['passwd1']) { $errors['passwd1'] = __('New password is required'); } elseif ($vars['passwd1'] && strlen($vars['passwd1']) < 6) { $errors['passwd1'] = __('Must be at least 6 characters'); } elseif ($vars['passwd1'] && strcmp($vars['passwd1'], $vars['passwd2'])) { $errors['passwd2'] = __('Passwords do not match'); } } // Make sure the username is not an email. if ($vars['username'] && Validator::is_email($vars['username'])) { $errors['username'] = __('Users can always sign in with their email address'); } if ($errors) { return false; } $this->set('timezone_id', $vars['timezone_id']); $this->set('dst', isset($vars['dst']) ? 1 : 0); $this->set('username', $vars['username']); if ($vars['passwd1']) { $this->set('passwd', Passwd::hash($vars['passwd1'])); $this->setStatus(UserAccountStatus::CONFIRMED); } // Set flags foreach (array('pwreset-flag' => UserAccountStatus::REQUIRE_PASSWD_RESET, 'locked-flag' => UserAccountStatus::LOCKED, 'forbid-pwchange-flag' => UserAccountStatus::FORBID_PASSWD_RESET) as $ck => $flag) { if ($vars[$ck]) { $this->setStatus($flag); } else { $this->clearStatus($flag); } } return $this->save(true); }
<?php if (!defined('OSTADMININC') || !$thisstaff || !$thisstaff->isAdmin() || !$filter) { die('Access Denied'); } $qstr = ''; $select = 'SELECT rule.* '; $from = 'FROM ' . EMAIL_FILTER_RULE_TABLE . ' rule '; $where = 'WHERE rule.filter_id=' . db_input($filter->getId()); $search = false; if ($_REQUEST['q'] && strlen($_REQUEST['q']) > 3) { $search = true; if (strpos($_REQUEST['q'], '@') && Validator::is_email($_REQUEST['q'])) { $where .= ' AND rule.val=' . db_input($_REQUEST['q']); } else { $where .= ' AND rule.val LIKE "%' . db_input($_REQUEST['q'], false) . '%"'; } } elseif ($_REQUEST['q']) { $errors['q'] = 'Term too short!'; } //TODO: Add search here.. $sortOptions = array('email' => 'rule.val', 'status' => 'isactive', 'created' => 'rule.created', 'created' => 'rule.updated'); $orderWays = array('DESC' => 'DESC', 'ASC' => 'ASC'); $sort = $_REQUEST['sort'] && $sortOptions[strtolower($_REQUEST['sort'])] ? strtolower($_REQUEST['sort']) : 'email'; //Sorting options... if ($sort && $sortOptions[$sort]) { $order_column = $sortOptions[$sort]; } $order_column = $order_column ? $order_column : 'rule.val'; if ($_REQUEST['order'] && $orderWays[strtoupper($_REQUEST['order'])]) { $order = $orderWays[strtoupper($_REQUEST['order'])];
function save($id, $vars, &$errors) { include_once INCLUDE_DIR . 'class.dept.php'; if ($id && $id != $vars['staff_id']) { $errors['err'] = 'Error Interno'; } if (!$vars['firstname'] || !$vars['lastname']) { $errors['name'] = 'Nombre y apellidos requerido'; } if (!$vars['username'] || strlen($vars['username']) < 3) { $errors['username'] = '******'; } else { //check if the username is already in-use. $sql = 'SELECT staff_id FROM ' . STAFF_TABLE . ' WHERE username='******'username']); if ($id) { $sql .= ' AND staff_id!=' . db_input($id); } if (db_num_rows(db_query($sql))) { $errors['username'] = '******'; } } if (!$vars['email'] || !Validator::is_email($vars['email'])) { $errors['email'] = 'Se requiere email Valido'; } elseif (Email::getIdByEmail($vars['email'])) { $errors['email'] = 'Este Email ya se esta usando como Email del sistema'; } if ($vars['phone'] && !Validator::is_phone($vars['phone'])) { $errors['phone'] = 'Numero de teláfono requerido'; } if ($vars['mobile'] && !Validator::is_phone($vars['mobile'])) { $errors['mobile'] = 'Numero de movil Requerido'; } if ($vars['npassword'] || $vars['vpassword'] || !$id) { if (!$vars['npassword'] && !$id) { $errors['npassword'] = '******'; } elseif ($vars['npassword'] && strcmp($vars['npassword'], $vars['vpassword'])) { $errors['vpassword'] = '******'; } elseif ($vars['npassword'] && strlen($vars['npassword']) < 6) { $errors['npassword'] = '******'; } } if (!$vars['dept_id']) { $errors['dept'] = 'Departamento requerido'; } if (!$vars['group_id']) { $errors['group'] = 'Grupo requerido'; } if (!$errors) { $sql = ' SET updated=NOW() ' . ',isadmin=' . db_input($vars['isadmin']) . ',isactive=' . db_input($vars['isactive']) . ',isvisible=' . db_input(isset($vars['isvisible']) ? 1 : 0) . ',onvacation=' . db_input(isset($vars['onvacation']) ? 1 : 0) . ',dept_id=' . db_input($vars['dept_id']) . ',group_id=' . db_input($vars['group_id']) . ',username='******'username'])) . ',firstname=' . db_input(Format::striptags($vars['firstname'])) . ',lastname=' . db_input(Format::striptags($vars['lastname'])) . ',email=' . db_input($vars['email']) . ',phone="' . db_input($vars['phone'], false) . '"' . ',phone_ext=' . db_input($vars['phone_ext']) . ',mobile="' . db_input($vars['mobile'], false) . '"' . ',signature=' . db_input(Format::striptags($vars['signature'])); if ($vars['npassword']) { $sql .= ',passwd=' . db_input(md5($vars['npassword'])); } if (isset($vars['resetpasswd'])) { $sql .= ',change_passwd=1'; } if ($id) { $sql = 'UPDATE ' . STAFF_TABLE . ' ' . $sql . ' WHERE staff_id=' . db_input($id); if (!db_query($sql) || !db_affected_rows()) { $errors['err'] = 'No se puede actualizar el usuario. Error interno'; } } else { $sql = 'INSERT INTO ' . STAFF_TABLE . ' ' . $sql . ',created=NOW()'; if (db_query($sql) && ($uID = db_insert_id())) { return $uID; } $errors['err'] = 'No se puede crear el usuario. Error interno'; } } return $errors ? false : true; }
case 'install': if ($installer->install($_POST)) { $_SESSION['info'] = array('name' => ucfirst($_POST['fname'] . ' ' . $_POST['lname']), 'email' => $_POST['admin_email'], 'URL' => URL); //TODO: Go to subscribe step. $_SESSION['ost_installer']['s'] = 'done'; } elseif (!($errors = $installer->getErrors()) || !$errors['err']) { $errors['err'] = 'Error installing osTicket - correct the errors below and try again.'; } break; case 'subscribe': if (!trim($_POST['name'])) { $errors['name'] = 'Required'; } if (!$_POST['email']) { $errors['email'] = 'Required'; } elseif (!Validator::is_email($_POST['email'])) { $errors['email'] = 'Invalid'; } if (!$_POST['alerts'] && !$_POST['news']) { $errors['notify'] = 'Check one or more'; } if (!$errors) { $_SESSION['ost_installer']['s'] = 'done'; } break; } } elseif ($_GET['s'] && $_GET['s'] == 'ns' && $_SESSION['ost_installer']['s'] == 'subscribe') { $_SESSION['ost_installer']['s'] = 'done'; } switch (strtolower($_SESSION['ost_installer']['s'])) { case 'config':
define('TICKET_MESSAGE_TABLE', TABLE_PREFIX . 'ticket_message'); define('TICKET_RESPONSE_TABLE', TABLE_PREFIX . 'ticket_response'); define('TICKET_ATTACHMENT_TABLE', TABLE_PREFIX . 'ticket_attachment'); define('TICKET_PRIORITY_TABLE', TABLE_PREFIX . 'ticket_priority'); define('TICKET_LOCK_TABLE', TABLE_PREFIX . 'ticket_lock'); define('EMAIL_TABLE', TABLE_PREFIX . 'email'); define('POP3_TABLE', TABLE_PREFIX . 'email_pop3'); define('EMAIL_TEMPLATE_TABLE', TABLE_PREFIX . 'email_template'); define('BANLIST_TABLE', TABLE_PREFIX . 'email_banlist'); define('TIMEZONE_TABLE', TABLE_PREFIX . 'timezone'); #Connect to the DB && get configuration from database $ferror = null; $cfg = new Config(); if (!db_connect(DBHOST, DBUSER, DBPASS) || !db_select_database(DBNAME)) { $ferror = 'Unable to connect to the DB'; } elseif (!$cfg->load(1)) { $ferror = 'Unable to load config info'; } if ($ferror) { //Fatal error if (defined(ADMIN_EMAIL) && Validator::is_email(ADMIN_EMAIL)) { Misc::sendmail(ADMIN_EMAIL, 'Fatal DB Error', $ferror, ADMIN_EMAIL); } die("<b>Fatal Error:</b> Contact site admin."); exit; } //Set default timezone...staff will overwrite it. list($mysqltz) = db_fetch_row(db_query('SELECT @@session.time_zone ')); $cfg->setMysqlTZ($mysqltz); $_SESSION['TZ_OFFSET'] = $cfg->getTZoffset(); $_SESSION['daylight'] = $cfg->observeDaylightSaving();
function save($id, $vars, &$errors) { $vars['username'] = Format::striptags($vars['username']); $vars['firstname'] = Format::striptags($vars['firstname']); $vars['lastname'] = Format::striptags($vars['lastname']); if ($id && $id != $vars['id']) { $errors['err'] = 'Internal Error'; } if (!$vars['firstname']) { $errors['firstname'] = 'First name required'; } if (!$vars['lastname']) { $errors['lastname'] = 'Last name required'; } $error = ''; if (!$vars['username'] || !Validator::is_username($vars['username'], $error)) { $errors['username'] = $error ? $error : 'Username required'; } elseif (($uid = Staff::getIdByUsername($vars['username'])) && $uid != $id) { $errors['username'] = '******'; } if (!$vars['email'] || !Validator::is_email($vars['email'])) { $errors['email'] = 'Valid email required'; } elseif (Email::getIdByEmail($vars['email'])) { $errors['email'] = 'Already in-use system email'; } elseif (($uid = Staff::getIdByEmail($vars['email'])) && $uid != $id) { $errors['email'] = 'Email already in use by another staff member'; } if ($vars['phone'] && !Validator::is_phone($vars['phone'])) { $errors['phone'] = 'Valid number required'; } if ($vars['mobile'] && !Validator::is_phone($vars['mobile'])) { $errors['mobile'] = 'Valid number required'; } if ($vars['passwd1'] || $vars['passwd2'] || !$id) { if ($vars['passwd1'] && strcmp($vars['passwd1'], $vars['passwd2'])) { $errors['passwd2'] = 'Password(s) do not match'; } elseif ($vars['backend'] != 'local' || $vars['welcome_email']) { // Password can be omitted } elseif (!$vars['passwd1'] && !$id) { $errors['passwd1'] = 'Temp. password required'; $errors['temppasswd'] = 'Required'; } elseif ($vars['passwd1'] && strlen($vars['passwd1']) < 6) { $errors['passwd1'] = 'Must be at least 6 characters'; } } if (!$vars['dept_id']) { $errors['dept_id'] = 'Department required'; } if (!$vars['group_id']) { $errors['group_id'] = 'Group required'; } if (!$vars['timezone_id']) { $errors['timezone_id'] = 'Time zone required'; } if ($errors) { return false; } $sql = 'SET updated=NOW() ' . ' ,isadmin=' . db_input($vars['isadmin']) . ' ,isactive=' . db_input($vars['isactive']) . ' ,isvisible=' . db_input(isset($vars['isvisible']) ? 1 : 0) . ' ,onvacation=' . db_input(isset($vars['onvacation']) ? 1 : 0) . ' ,assigned_only=' . db_input(isset($vars['assigned_only']) ? 1 : 0) . ' ,dept_id=' . db_input($vars['dept_id']) . ' ,group_id=' . db_input($vars['group_id']) . ' ,timezone_id=' . db_input($vars['timezone_id']) . ' ,daylight_saving=' . db_input(isset($vars['daylight_saving']) ? 1 : 0) . ' ,username='******'username']) . ' ,firstname=' . db_input($vars['firstname']) . ' ,lastname=' . db_input($vars['lastname']) . ' ,email=' . db_input($vars['email']) . ' ,backend=' . db_input($vars['backend']) . ' ,phone="' . db_input(Format::phone($vars['phone']), false) . '"' . ' ,phone_ext=' . db_input($vars['phone_ext']) . ' ,mobile="' . db_input(Format::phone($vars['mobile']), false) . '"' . ' ,signature=' . db_input(Format::sanitize($vars['signature'])) . ' ,notes=' . db_input(Format::sanitize($vars['notes'])); if ($vars['passwd1']) { $sql .= ' ,passwd=' . db_input(Passwd::hash($vars['passwd1'])); if (isset($vars['change_passwd'])) { $sql .= ' ,change_passwd=1'; } } elseif (!isset($vars['change_passwd'])) { $sql .= ' ,change_passwd=0'; } if ($id) { $sql = 'UPDATE ' . STAFF_TABLE . ' ' . $sql . ' WHERE staff_id=' . db_input($id); if (db_query($sql) && db_affected_rows()) { return true; } $errors['err'] = 'Unable to update the user. Internal error occurred'; } else { $sql = 'INSERT INTO ' . STAFF_TABLE . ' ' . $sql . ', created=NOW()'; if (db_query($sql) && ($uid = db_insert_id())) { return $uid; } $errors['err'] = 'Unable to create user. Internal error'; } return false; }
function update($vars, &$errors) { $valid = true; $forms = $this->getForms($vars); foreach ($forms as $cd) { if (!$cd->isValid()) { $valid = false; } if ($cd->get('type') == 'O' && ($form = $cd->getForm($vars)) && ($f = $form->getField('name')) && $f->getClean() && ($o = Organization::lookup(array('name' => $f->getClean()))) && $o->id != $this->getId()) { $valid = false; $f->addError('Organization with the same name already exists'); } } if ($vars['domain']) { foreach (explode(',', $vars['domain']) as $d) { if (!Validator::is_email('t@' . trim($d))) { $errors['domain'] = 'Enter a valid email domain, like domain.com'; } } } if ($vars['manager']) { switch ($vars['manager'][0]) { case 's': if ($staff = Staff::lookup(substr($vars['manager'], 1))) { break; } case 't': if ($vars['manager'][0] == 't' && ($team = Team::lookup(substr($vars['manager'], 1)))) { break; } default: $errors['manager'] = 'Select a staff member or team from the list'; } } if (!$valid || $errors) { return false; } foreach ($this->getDynamicData() as $cd) { if (($f = $cd->getForm()) && $f->get('type') == 'O' && ($name = $f->getField('name'))) { $this->name = $name->getClean(); $this->save(); } $cd->save(); } // Set flags foreach (array('collab-all-flag' => Organization::COLLAB_ALL_MEMBERS, 'collab-pc-flag' => Organization::COLLAB_PRIMARY_CONTACT, 'assign-am-flag' => Organization::ASSIGN_AGENT_MANAGER) as $ck => $flag) { if ($vars[$ck]) { $this->setStatus($flag); } else { $this->clearStatus($flag); } } // Set staff and primary contacts $this->set('domain', $vars['domain']); $this->set('manager', $vars['manager'] ?: ''); if ($vars['contacts'] && is_array($vars['contacts'])) { foreach ($this->allMembers() as $u) { $u->setPrimaryContact(array_search($u->id, $vars['contacts']) !== false); $u->save(); } } return $this->save(); }
function create($vars, &$errors, $origin, $autorespond = true, $alertstaff = true) { global $cfg, $thisclient, $_FILES; //Check for 403 if ($vars['email'] && Validator::is_email($vars['email'])) { //Make sure the email address is not banned if (EmailFilter::isBanned($vars['email'])) { $errors['err'] = 'Ticket denied. Error #403'; Sys::log(LOG_WARNING, 'Ticket denied', 'Banned email - ' . $vars['email']); return 0; } //Make sure the open ticket limit hasn't been reached. (LOOP CONTROL) if ($cfg->getMaxOpenTickets() > 0 && strcasecmp($origin, 'staff') && ($client = Client::lookupByEmail($vars['email'])) && ($openTickets = $client->getNumOpenTickets()) && $opentickets >= $cfg->getMaxOpenTickets()) { $errors['err'] = "You've reached the maximum open tickets allowed."; Sys::log(LOG_WARNING, 'Ticket denied -' . $vars['email'], sprintf('Max open tickets (%d) reached for %s ', $cfg->getMaxOpenTickets(), $vars['email'])); return 0; } } // Make sure email contents should not be rejected if (($email_filter = new EmailFilter($vars)) && ($filter = $email_filter->shouldReject())) { $errors['err'] = 'Ticket denied. Error #403'; Sys::log(LOG_WARNING, 'Ticket denied', sprintf('Banned email - %s by filter "%s"', $vars['email'], $filter->getName())); return 0; } $id = 0; $fields = array(); $fields['name'] = array('type' => 'string', 'required' => 1, 'error' => 'Name required'); $fields['email'] = array('type' => 'email', 'required' => 1, 'error' => 'Valid email required'); $fields['subject'] = array('type' => 'string', 'required' => 1, 'error' => 'Subject required'); $fields['message'] = array('type' => 'text', 'required' => 1, 'error' => 'Message required'); switch (strtolower($origin)) { case 'web': $fields['topicId'] = array('type' => 'int', 'required' => 1, 'error' => 'Select help topic'); break; case 'staff': $fields['deptId'] = array('type' => 'int', 'required' => 1, 'error' => 'Dept. required'); $fields['topicId'] = array('type' => 'int', 'required' => 1, 'error' => 'Topic required'); $fields['duedate'] = array('type' => 'date', 'required' => 0, 'error' => 'Invalid date - must be MM/DD/YY'); case 'api': $fields['source'] = array('type' => 'string', 'required' => 1, 'error' => 'Indicate source'); break; case 'email': $fields['emailId'] = array('type' => 'int', 'required' => 1, 'error' => 'Email unknown'); break; default: # TODO: Return error message $errors['err'] = $errors['origin'] = 'Invalid origin given'; } $fields['priorityId'] = array('type' => 'int', 'required' => 0, 'error' => 'Invalid Priority'); $fields['phone'] = array('type' => 'phone', 'required' => 0, 'error' => 'Valid phone # required'); if (!Validator::process($fields, $vars, $errors) && !$errors['err']) { $errors['err'] = 'Missing or invalid data - check the errors and try again'; } //Make sure phone extension is valid if ($vars['phone_ext']) { if (!is_numeric($vars['phone_ext']) && !$errors['phone']) { $errors['phone'] = 'Invalid phone ext.'; } elseif (!$vars['phone']) { //make sure they just didn't enter ext without phone # XXX: reconsider allowing! $errors['phone'] = 'Phone number required'; } } //Make sure the due date is valid if ($vars['duedate']) { if (!$vars['time'] || strpos($vars['time'], ':') === false) { $errors['time'] = 'Select time'; } elseif (strtotime($vars['duedate'] . ' ' . $vars['time']) === false) { $errors['duedate'] = 'Invalid duedate'; } elseif (strtotime($vars['duedate'] . ' ' . $vars['time']) <= time()) { $errors['duedate'] = 'Due date must be in the future'; } } # Perform email filter actions on the new ticket arguments XXX: Move filter to the top and check for reject... if (!$errors && $email_filter) { $email_filter->apply($vars); } # Some things will need to be unpacked back into the scope of this # function if (isset($vars['autorespond'])) { $autorespond = $vars['autorespond']; } //Any error above is fatal. if ($errors) { return 0; } // OK...just do it. $deptId = $vars['deptId']; //pre-selected Dept if any. $priorityId = $vars['priorityId']; $source = ucfirst($vars['source']); $topic = NULL; // Intenal mapping magic...see if we need to overwrite anything if (isset($vars['topicId']) && ($topic = Topic::lookup($vars['topicId']))) { //Ticket created via web by user/or staff $deptId = $deptId ? $deptId : $topic->getDeptId(); $priorityId = $priorityId ? $priorityId : $topic->getPriorityId(); if ($autorespond) { $autorespond = $topic->autoRespond(); } $source = $vars['source'] ? $vars['source'] : 'Web'; } elseif ($vars['emailId'] && !$vars['deptId'] && ($email = Email::lookup($vars['emailId']))) { //Emailed Tickets $deptId = $email->getDeptId(); $priorityId = $priorityId ? $priorityId : $email->getPriorityId(); if ($autorespond) { $autorespond = $email->autoRespond(); } $email = null; $source = 'Email'; } elseif ($vars['deptId']) { //Opened by staff. $deptId = $vars['deptId']; $source = ucfirst($vars['source']); } //Last minute checks $priorityId = $priorityId ? $priorityId : $cfg->getDefaultPriorityId(); $deptId = $deptId ? $deptId : $cfg->getDefaultDeptId(); $topicId = $vars['topicId'] ? $vars['topicId'] : 0; $ipaddress = $vars['ip'] ? $vars['ip'] : $_SERVER['REMOTE_ADDR']; //We are ready son...hold on to the rails. $extId = Ticket::genExtRandID(); $sql = 'INSERT INTO ' . TICKET_TABLE . ' SET created=NOW() ' . ' ,lastmessage= NOW()' . ' ,ticketID=' . db_input($extId) . ' ,dept_id=' . db_input($deptId) . ' ,topic_id=' . db_input($topicId) . ' ,priority_id=' . db_input($priorityId) . ' ,email=' . db_input($vars['email']) . ' ,name=' . db_input(Format::striptags($vars['name'])) . ' ,subject=' . db_input(Format::striptags($vars['subject'])) . ' ,phone="' . db_input($vars['phone'], false) . '"' . ' ,phone_ext=' . db_input($vars['phone_ext'] ? $vars['phone_ext'] : '') . ' ,ip_address=' . db_input($ipaddress) . ' ,source=' . db_input($source); //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 ------------------------ */ $dept = $ticket->getDept(); if (!$cfg->useRandomIds()) { //Sequential ticketIDs support really..really suck arse. $extId = $id; //To make things really easy we are going to use autoincrement ticket_id. db_query('UPDATE ' . TICKET_TABLE . ' SET ticketID=' . db_input($extId) . ' WHERE ticket_id=' . $id . ' LIMIT 1'); //TODO: RETHING what happens if this fails?? [At the moment on failure random ID is used...making stuff usable] } //post the message. $msgid = $ticket->postMessage($vars['message'], $source, $vars['mid'], $vars['header'], true); // Configure service-level-agreement for this ticket $ticket->selectSLAId($vars['slaId']); //Auto assign staff or team - auto assignment based on filter rules. if ($vars['staffId'] && !$vars['assignId']) { $ticket->assignToStaff($vars['staffId'], 'auto-assignment'); } if ($vars['teamId'] && !$vars['assignId']) { $ticket->assignToTeam($vars['teamId'], 'auto-assignment'); } /********** double check auto-response ************/ //Overwrite auto responder if the FROM email is one of the internal emails...loop control. if ($autorespond && Email::getIdByEmail($ticket->getEmail())) { $autorespond = false; } if ($autorespond && $dept && !$dept->autoRespONNewTicket()) { $autorespond = false; } # Messages that are clearly auto-responses from email systems should # not have a return 'ping' message if ($autorespond && $vars['header'] && EmailFilter::isAutoResponse(Mail_Parse::splitHeaders($vars['header']))) { $autorespond = false; } //Don't auto respond to mailer daemons. if ($autorespond && (strpos(strtolower($vars['email']), 'mailer-daemon@') !== false || strpos(strtolower($vars['email']), 'postmaster@') !== false)) { $autorespond = false; } /***** See if we need to send some alerts ****/ $ticket->onNewTicket($vars['message'], $autorespond, $alertstaff); /************ check if the user JUST reached the max. open tickets limit **********/ if ($cfg->getMaxOpenTickets() > 0 && ($client = $ticket->getClient()) && $client->getNumOpenTickets() == $cfg->getMaxOpenTickets()) { $ticket->onOpenLimit($autorespond && strcasecmp($origin, 'staff')); } /* Phew! ... time for tea (KETEPA) */ return $ticket; }
function save($id, $vars, &$errors) { global $cfg; //very basic checks if ($id && $id != $vars['email_id']) { $errors['err'] = 'Erro interno.'; } if (!$vars['email'] || !Validator::is_email($vars['email'])) { $errors['email'] = 'Email válido obrigatório'; } elseif (($eid = Email::getIdByEmail($vars['email'])) && $eid != $id) { $errors['email'] = 'Email já existe.'; } elseif (!strcasecmp($cfg->getAdminEmail(), $vars['email'])) { $errors['email'] = 'Email já usado como email do administrador!'; } else { //make sure the email doesn't belong to any of the staff $sql = 'SELECT staff_id FROM ' . STAFF_TABLE . ' WHERE email=' . db_input($vars['email']); if (($res = db_query($sql)) && db_num_rows($res)) { $errors['email'] = 'Email em uso por um membro do suporte.'; } } if (!$vars['dept_id'] || !is_numeric($vars['dept_id'])) { $errors['dept_id'] = 'Você deve selecionar um departamento.'; } if (!$vars['priority_id']) { $errors['priority_id'] = 'Você deve selecionar uma prioridade'; } if ($vars['mail_active'] || $vars['smtp_active'] && $vars['smtp_auth']) { if (!$vars['userid']) { $errors['userid'] = 'Nome de usuário ausente'; } if (!$vars['userpass']) { $errors['userpass'] = '******'; } } if ($vars['mail_active']) { //Check pop/imapinfo only when enabled. if (!function_exists('imap_open')) { $errors['mail_active'] = 'IMAP não existe. PHP deve ser compilado com IMAP habilitado.'; } if (!$vars['mail_host']) { $errors['mail_host'] = 'Nome do host obrigatório'; } if (!$vars['mail_port']) { $errors['mail_port'] = 'Porta obrigatória'; } if (!$vars['mail_protocol']) { $errors['mail_protocol'] = 'Selecione protocolo'; } if (!$vars['mail_fetchfreq'] || !is_numeric($vars['mail_fetchfreq'])) { $errors['mail_fetchfreq'] = 'Buscar intervalo obrigatório'; } if (!$vars['mail_fetchmax'] || !is_numeric($vars['mail_fetchmax'])) { $errors['mail_fetchmax'] = 'Máximo de emails exigidos'; } } if ($vars['smtp_active']) { if (!$vars['smtp_host']) { $errors['smtp_host'] = 'Nome do host obrigatório'; } if (!$vars['smtp_port']) { $errors['smtp_port'] = 'Porta obrigatória'; } } if (!$errors && ($vars['mail_host'] && $vars['userid'])) { $sql = 'SELECT email_id FROM ' . EMAIL_TABLE . ' WHERE mail_host=' . db_input($vars['mail_host']) . ' AND userid=' . db_input($vars['userid']); if ($id) { $sql .= ' AND email_id!=' . db_input($id); } if (db_num_rows(db_query($sql))) { $errors['userid'] = $errors['host'] = 'Outro departamento está usando combinação de nome/host.'; } } if (!$errors && $vars['mail_active']) { //note: password is unencrypted at this point...MailFetcher expect plain text. $fetcher = new MailFetcher($vars['userid'], $vars['userpass'], $vars['mail_host'], $vars['mail_port'], $vars['mail_protocol'], $vars['mail_encryption']); if (!$fetcher->connect()) { $errors['userpass'] = '******' . $vars['mail_protocol'] . ' configurações'; $errors['mail'] = '<br>' . $fetcher->getLastError(); } } if (!$errors && $vars['smtp_active']) { //Check SMTP login only. require_once 'Mail.php'; // PEAR Mail package $smtp = mail::factory('smtp', array('host' => $vars['smtp_host'], 'port' => $vars['smtp_port'], 'auth' => $vars['smtp_auth'] ? true : false, 'username' => $vars['userid'], 'password' => $vars['userpass'], 'timeout' => 20, 'debug' => false)); $mail = $smtp->connect(); if (PEAR::isError($mail)) { $errors['userpass'] = '******'; $errors['smtp'] = '<br>' . $mail->getMessage(); } else { $smtp->disconnect(); //Thank you, sir! } } if (!$errors) { $sql = 'updated=NOW(),mail_errors=0, mail_lastfetch=NULL' . ',email=' . db_input($vars['email']) . ',name=' . db_input(Format::striptags($vars['name'])) . ',dept_id=' . db_input($vars['dept_id']) . ',priority_id=' . db_input($vars['priority_id']) . ',noautoresp=' . db_input(isset($vars['noautoresp']) ? 1 : 0) . ',userid=' . db_input($vars['userid']) . ',userpass='******'userpass'], SECRET_SALT)) . ',mail_active=' . db_input($vars['mail_active']) . ',mail_host=' . db_input($vars['mail_host']) . ',mail_protocol=' . db_input($vars['mail_protocol'] ? $vars['mail_protocol'] : 'POP') . ',mail_encryption=' . db_input($vars['mail_encryption']) . ',mail_port=' . db_input($vars['mail_port'] ? $vars['mail_port'] : 0) . ',mail_fetchfreq=' . db_input($vars['mail_fetchfreq'] ? $vars['mail_fetchfreq'] : 0) . ',mail_fetchmax=' . db_input($vars['mail_fetchmax'] ? $vars['mail_fetchmax'] : 0) . ',mail_delete=' . db_input(isset($vars['mail_delete']) ? $vars['mail_delete'] : 0) . ',smtp_active=' . db_input($vars['smtp_active']) . ',smtp_host=' . db_input($vars['smtp_host']) . ',smtp_port=' . db_input($vars['smtp_port'] ? $vars['smtp_port'] : 0) . ',smtp_auth=' . db_input($vars['smtp_auth']); if ($id) { //update $sql = 'UPDATE ' . EMAIL_TABLE . ' SET ' . $sql . ' WHERE email_id=' . db_input($id); if (!db_query($sql) || !db_affected_rows()) { $errors['err'] = 'Não é possível atualizar e-mail. Erro interno'; } } else { $sql = 'INSERT INTO ' . EMAIL_TABLE . ' SET ' . $sql . ',created=NOW()'; if (!db_query($sql) or !($emailID = db_insert_id())) { $errors['err'] = 'Não é possível adicionar e-mail. Erro interno'; } else { return $emailID; } //newly created email. } } else { $errors['err'] = 'Erro(s). Tente novamente'; } return $errors ? FALSE : TRUE; }
if (strlen($_POST['userpw']) < 4) { $errors['userpw3'] = _t('비밀번호는 4자 이상으로 해 주세요.'); } } if (empty($_POST['useremail'])) { $errors['useremail1'] = _t('이메일 주소를 입력해주세요.'); } } if (!empty($_POST['userid']) && !empty($_POST['userpw']) && !empty($_POST['useremail'])) { if (!Validator::is_alnum($_POST['userid'])) { $errors['userid2'] = _t('아이디에 잘못된 문자가 포함되어 있습니다.'); } if (!Validator::is_email($_POST['useremail'])) { $errors['useremail2'] = _t('이메일 주소가 잘못되었습니다.'); } if ($_POST['userpw'] != $_POST['userpw2']) { $errors['userpw4'] = _t('두 비밀번호가 일치하지 않습니다.'); } if (count($errors) == 0) { requireComponent('Bloglounge.Model.Users'); if (User::doesLoginIdExists($_POST['userid'])) { $errors['userid4'] = _t('이미 존재하는 아이디입니다.'); } else { if (User::add($_POST['userid'], $_POST['userpw'], $_POST['username'], $_POST['useremail'])) { login($_POST['userid'], $_POST['userpw'], false); } else { $errors['usererror'] = _t('회원가입에 실패했습니다.');
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; }
function tryLogin($ticketID, $email, $auth = null) { global $ost; $cfg = $ost->getConfig(); # Only consider auth token for GET requests, and for GET requests, # REQUIRE the auth token $auto_login = $_SERVER['REQUEST_METHOD'] == 'GET'; //Check time for last max failed login attempt strike. $loginmsg = 'Invalid login'; # XXX: SECURITY: Max attempts is enforced client-side via the PHP # session cookie. if ($_SESSION['_client']['laststrike']) { if (time() - $_SESSION['_client']['laststrike'] < $cfg->getClientLoginTimeout()) { $loginmsg = 'Excessive failed login attempts'; $errors['err'] = 'You\'ve reached maximum failed login attempts allowed. Try again later or <a href="open.php">open a new ticket</a>'; } else { //Timeout is over. //Reset the counter for next round of attempts after the timeout. $_SESSION['_client']['laststrike'] = null; $_SESSION['_client']['strikes'] = 0; } } //See if we can fetch local ticket id associated with the ID given if (!$errors && is_numeric($ticketID) && Validator::is_email($email) && ($ticket = Ticket::lookupByExtId($ticketID))) { //At this point we know the ticket is valid. //TODO: 1) Check how old the ticket is...3 months max?? 2) Must be the latest 5 tickets?? //Check the email given. # Require auth token for automatic logins if (!$auto_login || $auth === $ticket->getAuthToken()) { if ($ticket->getId() && strcasecmp($ticket->getEmail(), $email) == 0) { //valid match...create session goodies for the client. $user = new ClientSession($email, $ticket->getId()); $_SESSION['_client'] = array(); //clear. $_SESSION['_client']['userID'] = $ticket->getEmail(); //Email $_SESSION['_client']['key'] = $ticket->getExtId(); //Ticket ID --acts as password when used with email. See above. $_SESSION['_client']['token'] = $user->getSessionToken(); $_SESSION['TZ_OFFSET'] = $cfg->getTZoffset(); $_SESSION['TZ_DST'] = $cfg->observeDaylightSaving(); //Log login info... $msg = sprintf("%s/%s logged in [%s]", $ticket->getEmail(), $ticket->getExtId(), $_SERVER['REMOTE_ADDR']); $ost->logDebug('User login', $msg); //Redirect tickets.php session_write_close(); session_regenerate_id(); @header("Location: tickets.php?id=" . $ticket->getExtId()); require_once 'tickets.php'; //Just incase. of header already sent error. exit; } } } //If we get to this point we know the login failed. $_SESSION['_client']['strikes'] += 1; if (!$errors && $_SESSION['_client']['strikes'] > $cfg->getClientMaxLogins()) { $loginmsg = 'Access Denied'; $errors['err'] = 'Forgot your login info? Please <a href="open.php">open a new ticket</a>.'; $_SESSION['_client']['laststrike'] = time(); $alert = 'Excessive login attempts by a client?' . "\n" . 'Email: ' . $_POST['lemail'] . "\n" . 'Ticket#: ' . $_POST['lticket'] . "\n" . 'IP: ' . $_SERVER['REMOTE_ADDR'] . "\n" . 'Time:' . date('M j, Y, g:i a T') . "\n\n" . 'Attempts #' . $_SESSION['_client']['strikes']; $ost->logError('Excessive login attempts (client)', $alert, $cfg->alertONLoginError()); } elseif ($_SESSION['_client']['strikes'] % 2 == 0) { //Log every other failed login attempt as a warning. $alert = 'Email: ' . $_POST['lemail'] . "\n" . 'Ticket #: ' . $_POST['lticket'] . "\n" . 'IP: ' . $_SERVER['REMOTE_ADDR'] . "\n" . 'TIME: ' . date('M j, Y, g:i a T') . "\n\n" . 'Attempts #' . $_SESSION['_client']['strikes']; $ost->logWarning('Failed login attempt (client)', $alert); } }
function save($id, $vars, &$errors) { $vars['username'] = Format::striptags($vars['username']); $vars['firstname'] = Format::striptags($vars['firstname']); $vars['lastname'] = Format::striptags($vars['lastname']); if ($id && $id != $vars['id']) { $errors['err'] = __('Internal Error'); } if (!$vars['firstname']) { $errors['firstname'] = __('First name required'); } if (!$vars['lastname']) { $errors['lastname'] = __('Last name required'); } $error = ''; if (!$vars['username'] || !Validator::is_username($vars['username'], $error)) { $errors['username'] = $error ? $error : __('Username is required'); } elseif (($uid = Staff::getIdByUsername($vars['username'])) && $uid != $id) { $errors['username'] = __('Username already in use'); } if (!$vars['email'] || !Validator::is_email($vars['email'])) { $errors['email'] = __('Valid email is required'); } elseif (Email::getIdByEmail($vars['email'])) { $errors['email'] = __('Already in use system email'); } elseif (($uid = Staff::getIdByEmail($vars['email'])) && $uid != $id) { $errors['email'] = __('Email already in use by another agent'); } if ($vars['phone'] && !Validator::is_phone($vars['phone'])) { $errors['phone'] = __('Valid phone number is required'); } if ($vars['mobile'] && !Validator::is_phone($vars['mobile'])) { $errors['mobile'] = __('Valid phone number is required'); } if ($vars['passwd1'] || $vars['passwd2'] || !$id) { if ($vars['passwd1'] && strcmp($vars['passwd1'], $vars['passwd2'])) { $errors['passwd2'] = __('Passwords do not match'); } elseif ($vars['backend'] != 'local' || $vars['welcome_email']) { // Password can be omitted } elseif (!$vars['passwd1'] && !$id) { $errors['passwd1'] = __('Temporary password is required'); $errors['temppasswd'] = __('Required'); } elseif ($vars['passwd1'] && strlen($vars['passwd1']) < 6) { $errors['passwd1'] = __('Password must be at least 6 characters'); } } if (!$vars['dept_id']) { $errors['dept_id'] = __('Department is required'); } if (!$vars['group_id']) { $errors['group_id'] = __('Group is required'); } if (!$vars['timezone_id']) { $errors['timezone_id'] = __('Time zone selection is required'); } // Ensure we will still have an administrator with access if ($vars['isadmin'] !== '1' || $vars['isactive'] !== '1') { $sql = 'select count(*), max(staff_id) from ' . STAFF_TABLE . ' WHERE isadmin=1 and isactive=1'; if (($res = db_query($sql)) && (list($count, $sid) = db_fetch_row($res))) { if ($count == 1 && $sid == $id) { $errors['isadmin'] = __('Cowardly refusing to remove or lock out the only active administrator'); } } } if ($errors) { return false; } $sql = 'SET updated=NOW() ' . ' ,isadmin=' . db_input($vars['isadmin']) . ' ,isactive=' . db_input($vars['isactive']) . ' ,isvisible=' . db_input(isset($vars['isvisible']) ? 1 : 0) . ' ,onvacation=' . db_input(isset($vars['onvacation']) ? 1 : 0) . ' ,assigned_only=' . db_input(isset($vars['assigned_only']) ? 1 : 0) . ' ,dept_id=' . db_input($vars['dept_id']) . ' ,group_id=' . db_input($vars['group_id']) . ' ,timezone_id=' . db_input($vars['timezone_id']) . ' ,daylight_saving=' . db_input(isset($vars['daylight_saving']) ? 1 : 0) . ' ,username='******'username']) . ' ,firstname=' . db_input($vars['firstname']) . ' ,lastname=' . db_input($vars['lastname']) . ' ,email=' . db_input($vars['email']) . ' ,backend=' . db_input($vars['backend']) . ' ,phone="' . db_input(Format::phone($vars['phone']), false) . '"' . ' ,phone_ext=' . db_input($vars['phone_ext']) . ' ,mobile="' . db_input(Format::phone($vars['mobile']), false) . '"' . ' ,signature=' . db_input(Format::sanitize($vars['signature'])) . ' ,notes=' . db_input(Format::sanitize($vars['notes'])); if ($vars['passwd1']) { $sql .= ' ,passwd=' . db_input(Passwd::hash($vars['passwd1'])); if (isset($vars['change_passwd'])) { $sql .= ' ,change_passwd=1'; } } elseif (!isset($vars['change_passwd'])) { $sql .= ' ,change_passwd=0'; } if ($id) { $sql = 'UPDATE ' . STAFF_TABLE . ' ' . $sql . ' WHERE staff_id=' . db_input($id); if (db_query($sql) && db_affected_rows()) { return true; } $errors['err'] = sprintf(__('Unable to update %s.'), __('this agent')) . ' ' . __('Internal error occurred'); } else { $sql = 'INSERT INTO ' . STAFF_TABLE . ' ' . $sql . ', created=NOW()'; if (db_query($sql) && ($uid = db_insert_id())) { return $uid; } $errors['err'] = sprintf(__('Unable to create %s.'), __('this agent')) . ' ' . __('Internal error occurred'); } return false; }
//Parse the email. $parser = new Mail_Parse($data); if (!$parser->decode()) { //Decode...returns false on decoding errors api_exit(EX_DATAERR, 'Email parse failed [' . $parser->getError() . "]\n\n" . $data); } //Check from address. make sure it is not a banned address. $fromlist = $parser->getFromAddressList(); //Check for parsing errors on FROM address. if (!$fromlist || PEAR::isError($fromlist)) { api_exit(EX_DATAERR, 'Invalid FROM address [' . $fromlist ? $fromlist->getMessage() : '' . "]\n\n" . $data); } $from = $fromlist[0]; //Default. foreach ($fromlist as $fromobj) { if (!Validator::is_email($fromobj->mailbox . '@' . $fromobj->host)) { continue; } $from = $fromobj; break; } //TO Address:Try to figure out the email associated with the message. $tolist = $parser->getToAddressList(); foreach ($tolist as $toaddr) { if ($emailId = Email::getIdByEmail($toaddr->mailbox . '@' . $toaddr->host)) { //We've found target email. break; } } if (!$emailId && ($cclist = $parser->getCcAddressList())) { foreach ($cclist as $ccaddr) {
function save($id, $vars, &$errors) { if ($id && $id != $vars['client_id']) { $errors['err'] = _('Internal Error'); } // Check email. if (!$vars['client_email'] || !Validator::is_email($vars['client_email'])) { $errors['email'] = _('Valid email required'); } elseif (Email::getIdByEmail($vars['client_email'])) { $errors['email'] = _('Already in-use system email'); } else { //check if the email is already in-use. $sql = 'SELECT client_id FROM ' . CLIENT_TABLE . ' WHERE client_email=' . db_input($vars['client_email']); if ($id) { $sql .= ' AND client_id!=' . db_input($id); } if (db_num_rows(db_query($sql))) { $errors['email'] = _('Already in-use email'); } } if ($vars['client_phone'] && !Validator::is_phone($vars['client_phone'])) { $errors['phone'] = _('Valid number required'); } if ($vars['client_mobile'] && !Validator::is_phone($vars['client_mobile'])) { $errors['mobile'] = _('Valid number required'); } // Check passwords if ($vars['npassword'] || $vars['vpassword'] || !$id) { if (!$vars['npassword'] && !$id) { $errors['npassword'] = _('Password required'); } elseif ($vars['npassword'] && strcmp($vars['npassword'], $vars['vpassword'])) { $errors['vpassword'] = _('Password(s) do not match'); } elseif ($vars['npassword'] && strlen($vars['npassword']) < 6) { $errors['npassword'] = _('Must be at least 6 characters'); } elseif ($vars['npassword'] && strlen($vars['npassword']) > 128) { $errors['npassword'] = _('Password too long'); } } if (!$errors) { $sql = ' SET client_isactive=' . db_input($vars['client_isactive']) . ',client_email=' . db_input(Format::striptags($vars['client_email'])) . ',client_firstname=' . db_input(Format::striptags($vars['client_firstname'])) . ',client_lastname=' . db_input(Format::striptags($vars['client_lastname'])) . ',client_organization=' . db_input(Format::striptags($vars['client_organization'])) . ',client_phone="' . db_input($vars['client_phone'], false) . '"' . ',client_mobile="' . db_input($vars['client_mobile'], false) . '"'; if ($vars['npassword']) { $hash = PhpassHashedPass::hash($vars['npassword']); $sql .= ',client_password='******'UPDATE ' . CLIENT_TABLE . ' ' . $sql . ' WHERE client_id=' . db_input($id); if (!db_query($sql) || !db_affected_rows()) { $errors['err'] = _('Unable to update the user. Internal error occured'); } if ($vars['old_client_email'] != $vars['client_email']) { // Email changed? Update the tickets! $sql = 'UPDATE ' . TICKET_TABLE . ' SET email=' . db_input(Format::striptags($vars['client_email'])) . ' WHERE email=' . db_input($vars['old_client_email']); if (!db_query($sql)) { $errors['err'] = _('Unable to update the user. Internal error occured'); } //TODO: reverse the previous db operation! } } else { $sql = 'INSERT INTO ' . CLIENT_TABLE . ' ' . $sql . ',client_created=NOW()'; if (db_query($sql) && ($uID = db_insert_id())) { return $uID; } $errors['err'] = _('Unable to create user. Internal error'); } } return $errors ? false : true; }
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; }
function save_rules($id, $vars, &$errors) { $matches = array_keys(self::getSupportedMatchFields()); $types = array_keys(self::getSupportedMatchTypes()); $rules = array(); for ($i = 1; $i <= 25; $i++) { //Expecting no more than 25 rules... if ($vars["rule_w{$i}"] || $vars["rule_h{$i}"]) { // Check for REGEX compile errors if (in_array($vars["rule_h{$i}"], array('match', 'not_match'))) { $wrapped = "/" . $vars["rule_v{$i}"] . "/iu"; if (false === @preg_match($vars["rule_v{$i}"], ' ') && false !== @preg_match($wrapped, ' ')) { $vars["rule_v{$i}"] = $wrapped; } } if (!$vars["rule_w{$i}"] || !in_array($vars["rule_w{$i}"], $matches)) { $errors["rule_{$i}"] = __('Invalid match selection'); } elseif (!$vars["rule_h{$i}"] || !in_array($vars["rule_h{$i}"], $types)) { $errors["rule_{$i}"] = __('Invalid match type selection'); } elseif (!$vars["rule_v{$i}"]) { $errors["rule_{$i}"] = __('Value required'); } elseif ($vars["rule_w{$i}"] == 'email' && $vars["rule_h{$i}"] == 'equal' && !Validator::is_email($vars["rule_v{$i}"])) { $errors["rule_{$i}"] = __('Valid email required for the match type'); } elseif (in_array($vars["rule_h{$i}"], array('match', 'not_match')) && false === @preg_match($vars["rule_v{$i}"], ' ')) { $errors["rule_{$i}"] = sprintf(__('Regex compile error: (#%s)'), preg_last_error()); } else { //for everything-else...we assume it's valid. $rules[] = array('what' => $vars["rule_w{$i}"], 'how' => $vars["rule_h{$i}"], 'val' => trim($vars["rule_v{$i}"])); } } elseif ($vars["rule_v{$i}"]) { $errors["rule_{$i}"] = __('Incomplete selection'); } } if (!$rules && is_array($vars["rules"])) { # XXX: Validation bypass $rules = $vars["rules"]; } elseif (!$rules && !$errors) { $errors['rules'] = __('You must set at least one rule.'); } if ($errors) { return false; } if (!$id) { return true; } //When ID is 0 then assume it was just validation... //Clear existing rules...we're doing mass replace on each save!! db_query('DELETE FROM ' . FILTER_RULE_TABLE . ' WHERE filter_id=' . db_input($id)); $num = 0; foreach ($rules as $rule) { $rule['filter_id'] = $id; if (FilterRule::create($rule, $errors)) { $num++; } } return $num; }
$errors['err'] = 'Unknown or invalid ban rule.'; } elseif (!$_POST['val'] || !Validator::is_email($_POST['val'])) { $errors['err'] = $errors['val'] = 'Valid email address required'; } elseif (!$errors) { $vars = array('w' => 'email', 'h' => 'equal', 'v' => trim($_POST['val']), 'filter_id' => $filter->getId(), 'isactive' => $_POST['isactive'], 'notes' => $_POST['notes']); if ($rule->update($vars, $errors)) { $msg = 'Email updated successfully'; } elseif (!$errors['err']) { $errors['err'] = 'Error updating ban rule. Try again!'; } } break; case 'add': if (!$filter) { $errors['err'] = 'Unknown or invalid ban list'; } elseif (!$_POST['val'] || !Validator::is_email($_POST['val'])) { $errors['err'] = $errors['val'] = 'Valid email address required'; } elseif (BanList::includes(trim($_POST['val']))) { $errors['err'] = $errors['val'] = 'Email already in the ban list'; } elseif ($filter->addRule('email', 'equal', trim($_POST['val']), array('isactive' => $_POST['isactive'], 'notes' => $_POST['notes']))) { $msg = 'Email address added to ban list successfully'; $_REQUEST['a'] = null; //Add filter rule here. } elseif (!$errors['err']) { $errors['err'] = 'Error creating ban rule. Try again!'; } break; case 'mass_process': if (!$_POST['ids'] || !is_array($_POST['ids']) || !count($_POST['ids'])) { $errors['err'] = 'You must select at least one email to process.'; } else {
//$_SESSION['_client']=array(); #Uncomment to disable login strikes. //Check time for last max failed login attempt strike. $loginmsg = 'Invalid login'; if ($_SESSION['_client']['laststrike']) { if (time() - $_SESSION['_client']['laststrike'] < $cfg->getClientLoginTimeout()) { $loginmsg = 'Excessive failed login attempts'; $errors['err'] = 'You\'ve reached maximum failed login attempts allowed. Try again later or <a href="open.php">open a new ticket</a>'; } else { //Timeout is over. //Reset the counter for next round of attempts after the timeout. $_SESSION['_client']['laststrike'] = null; $_SESSION['_client']['strikes'] = 0; } } //See if we can fetch local ticket id associated with the ID given if (!$errors && is_numeric($ticketID) && Validator::is_email($email) && ($tid = Ticket::getIdByExtId($ticketID))) { //At this point we know the ticket is valid. $ticket = new Ticket($tid); //TODO: 1) Check how old the ticket is...3 months max?? 2) Must be the latest 5 tickets?? //Check the email given. if ($ticket->getId() && strcasecmp($ticket->getEMail(), $email) == 0) { //valid match...create session goodies for the client. $user = new ClientSession($email, $ticket->getId()); $_SESSION['_client'] = array(); //clear. $_SESSION['_client']['userID'] = $ticket->getEmail(); //Email $_SESSION['_client']['key'] = $ticket->getExtId(); //Ticket ID --acts as password when used with email. See above. $_SESSION['_client']['token'] = $user->getSessionToken(); $_SESSION['TZ_OFFSET'] = $cfg->getTZoffset();
function parse($stream) { global $cfg; $contents = ''; if (is_resource($stream)) { while (!feof($stream)) { $contents .= fread($stream, 8192); } } else { $contents = $stream; } $parser = new Mail_Parse($contents); if (!$parser->decode()) { //Decode...returns false on decoding errors return $this->err('Email parse failed [' . $parser->getError() . ']'); } $data = array(); $data['emailId'] = 0; $data['recipients'] = array(); $data['subject'] = $parser->getSubject(); $data['header'] = $parser->getHeader(); $data['mid'] = $parser->getMessageId(); $data['priorityId'] = $parser->getPriority(); $data['flags'] = new ArrayObject(); //FROM address: who sent the email. if ($fromlist = $parser->getFromAddressList()) { $from = $fromlist[0]; //Default. foreach ($fromlist as $fromobj) { if (!Validator::is_email($fromobj->mailbox . '@' . $fromobj->host)) { continue; } $from = $fromobj; break; } $data['email'] = $from->mailbox . '@' . $from->host; $data['name'] = trim($from->personal, '"'); if ($from->comment && $from->comment[0]) { $data['name'] .= ' (' . $from->comment[0] . ')'; } //Use email address as name when FROM address doesn't have a name. if (!$data['name'] && $data['email']) { $data['name'] = $data['email']; } } /* Scan through the list of addressees (via To, Cc, and Delivered-To headers), and identify * how the mail arrived at the system. One of the mails should be in the system email list. * The recipient list (without the Delivered-To addressees) will be made available to the * ticket filtering system. However, addresses in the Delivered-To header should never be * considered for the collaborator list. */ $tolist = array(); if ($to = $parser->getToAddressList()) { $tolist['to'] = $to; } if ($cc = $parser->getCcAddressList()) { $tolist['cc'] = $cc; } if ($dt = $parser->getDeliveredToAddressList()) { $tolist['delivered-to'] = $dt; } foreach ($tolist as $source => $list) { foreach ($list as $addr) { if (!($emailId = Email::getIdByEmail(strtolower($addr->mailbox) . '@' . $addr->host))) { //Skip virtual Delivered-To addresses if ($source == 'delivered-to') { continue; } $data['recipients'][] = array('source' => sprintf(_S("Email (%s)"), $source), 'name' => trim(@$addr->personal, '"'), 'email' => strtolower($addr->mailbox) . '@' . $addr->host); } elseif (!$data['emailId']) { $data['emailId'] = $emailId; } } } /* * In the event that the mail was delivered to the system although none of the system * mail addresses are in the addressee lists, be careful not to include the addressee * in the collaborator list. Therefore, the delivered-to addressees should be flagged so they * are not added to the collaborator list in the ticket creation process. */ if ($tolist['delivered-to']) { foreach ($tolist['delivered-to'] as $addr) { foreach ($data['recipients'] as $i => $r) { if (strcasecmp($r['email'], $addr->mailbox . '@' . $addr->host) === 0) { $data['recipients'][$i]['source'] = 'delivered-to'; } } } } //maybe we got BCC'ed?? if (!$data['emailId']) { $emailId = 0; if ($bcc = $parser->getBccAddressList()) { foreach ($bcc as $addr) { if ($emailId = Email::getIdByEmail($addr->mailbox . '@' . $addr->host)) { break; } } } $data['emailId'] = $emailId; } if ($parser->isBounceNotice()) { // Fetch the original References and assign to 'references' if ($headers = $parser->getOriginalMessageHeaders()) { $data['references'] = $headers['references']; $data['in-reply-to'] = @$headers['in-reply-to'] ?: null; } // Fetch deliver status report $data['message'] = $parser->getDeliveryStatusMessage() ?: $parser->getBody(); $data['thread-type'] = 'N'; $data['flags']['bounce'] = true; } else { // Typical email $data['message'] = $parser->getBody(); $data['in-reply-to'] = @$parser->struct->headers['in-reply-to']; $data['references'] = @$parser->struct->headers['references']; $data['flags']['bounce'] = TicketFilter::isBounce($data['header']); } $data['to-email-id'] = $data['emailId']; if ($replyto = $parser->getReplyTo()) { $replyto = $replyto[0]; $data['reply-to'] = $replyto->mailbox . '@' . $replyto->host; if ($replyto->personal) { $data['reply-to-name'] = trim($replyto->personal, " \t\n\r\v\""); } } $data['attachments'] = $parser->getAttachments(); return $data; }
function save($id, $vars, &$errors) { global $cfg; //very basic checks if ($id && $id != $vars['email_id']) { $errors['err'] = 'Internal error.'; } if (!$vars['email'] || !Validator::is_email($vars['email'])) { $errors['email'] = 'Valid email required'; } elseif (($eid = Email::getIdByEmail($vars['email'])) && $eid != $id) { $errors['email'] = 'Email already exits'; } elseif (!strcasecmp($cfg->getAdminEmail(), $vars['email'])) { $errors['email'] = 'Email already used as admin email!'; } else { //make sure the email doesn't belong to any of the staff $sql = 'SELECT staff_id FROM ' . STAFF_TABLE . ' WHERE email=' . db_input($vars['email']); if (($res = db_query($sql)) && db_num_rows($res)) { $errors['email'] = 'Email in-use by a staff member'; } } if (!$vars['dept_id'] || !is_numeric($vars['dept_id'])) { $errors['dept_id'] = 'You must select a Dept.'; } if (!$vars['priority_id']) { $errors['priority_id'] = 'You must select a priority'; } if ($vars['mail_active'] || $vars['smtp_active'] && $vars['smtp_auth']) { if (!$vars['userid']) { $errors['userid'] = 'Username missing'; } if (!$vars['userpass']) { $errors['userpass'] = '******'; } } if ($vars['mail_active']) { //Check pop/imapinfo only when enabled. if (!function_exists('imap_open')) { $errors['mail_active'] = 'IMAP doesn\'t exist. PHP must be compiled with IMAP enabled.'; } if (!$vars['mail_host']) { $errors['mail_host'] = 'Host name required'; } if (!$vars['mail_port']) { $errors['mail_port'] = 'Port required'; } if (!$vars['mail_protocol']) { $errors['mail_protocol'] = 'Select protocol'; } if (!$vars['mail_fetchfreq'] || !is_numeric($vars['mail_fetchfreq'])) { $errors['mail_fetchfreq'] = 'Fetch interval required'; } if (!$vars['mail_fetchmax'] || !is_numeric($vars['mail_fetchmax'])) { $errors['mail_fetchmax'] = 'Maximum emails required'; } } if ($vars['smtp_active']) { if (!$vars['smtp_host']) { $errors['smtp_host'] = 'Host name required'; } if (!$vars['smtp_port']) { $errors['smtp_port'] = 'Port required'; } } if (!$errors && ($vars['mail_host'] && $vars['userid'])) { $sql = 'SELECT email_id FROM ' . EMAIL_TABLE . ' WHERE mail_host=' . db_input($vars['mail_host']) . ' AND userid=' . db_input($vars['userid']); if ($id) { $sql .= ' AND email_id!=' . db_input($id); } if (db_num_rows(db_query($sql))) { $errors['userid'] = $errors['host'] = 'Another department using host/username combination.'; } } if (!$errors && $vars['mail_active']) { //note: password is unencrypted at this point...MailFetcher expect plain text. $fetcher = new MailFetcher($vars['userid'], $vars['userpass'], $vars['mail_host'], $vars['mail_port'], $vars['mail_protocol'], $vars['mail_encryption']); if (!$fetcher->connect()) { $errors['userpass'] = '******' . $vars['mail_protocol'] . ' settings'; $errors['mail'] = '<br>' . $fetcher->getLastError(); } } if (!$errors && $vars['smtp_active']) { //Check SMTP login only. require_once 'Mail.php'; // PEAR Mail package $smtp = mail::factory('smtp', array('host' => $vars['smtp_host'], 'port' => $vars['smtp_port'], 'auth' => $vars['smtp_auth'] ? true : false, 'username' => $vars['userid'], 'password' => $vars['userpass'], 'timeout' => 20, 'debug' => false)); $mail = $smtp->connect(); if (PEAR::isError($mail)) { $errors['userpass'] = '******'; $errors['smtp'] = '<br>' . $mail->getMessage(); } else { $smtp->disconnect(); //Thank you, sir! } } if (!$errors) { $sql = 'updated=NOW(),mail_errors=0, mail_lastfetch=NULL' . ',email=' . db_input($vars['email']) . ',name=' . db_input(Format::striptags($vars['name'])) . ',dept_id=' . db_input($vars['dept_id']) . ',priority_id=' . db_input($vars['priority_id']) . ',noautoresp=' . db_input(isset($vars['noautoresp']) ? 1 : 0) . ',userid=' . db_input($vars['userid']) . ',userpass='******'userpass'], SECRET_SALT)) . ',mail_active=' . db_input($vars['mail_active']) . ',mail_host=' . db_input($vars['mail_host']) . ',mail_protocol=' . db_input($vars['mail_protocol'] ? $vars['mail_protocol'] : 'POP') . ',mail_encryption=' . db_input($vars['mail_encryption']) . ',mail_port=' . db_input($vars['mail_port'] ? $vars['mail_port'] : 0) . ',mail_fetchfreq=' . db_input($vars['mail_fetchfreq'] ? $vars['mail_fetchfreq'] : 0) . ',mail_fetchmax=' . db_input($vars['mail_fetchmax'] ? $vars['mail_fetchmax'] : 0) . ',mail_delete=' . db_input(isset($vars['mail_delete']) ? $vars['mail_delete'] : 0) . ',smtp_active=' . db_input($vars['smtp_active']) . ',smtp_host=' . db_input($vars['smtp_host']) . ',smtp_port=' . db_input($vars['smtp_port'] ? $vars['smtp_port'] : 0) . ',smtp_auth=' . db_input($vars['smtp_auth']); if ($id) { //update $sql = 'UPDATE ' . EMAIL_TABLE . ' SET ' . $sql . ' WHERE email_id=' . db_input($id); if (!db_query($sql) || !db_affected_rows()) { $errors['err'] = 'Unable to update email. Internal error occured'; } } else { $sql = 'INSERT INTO ' . EMAIL_TABLE . ' SET ' . $sql . ',created=NOW()'; if (!db_query($sql) or !($emailID = db_insert_id())) { $errors['err'] = 'Unable to add email. Internal error'; } else { return $emailID; } //newly created email. } } else { $errors['err'] = 'Error(s) Occured. Try again'; } return $errors ? FALSE : TRUE; }
// Auto-registration failed. Show the user the info we have $inc = 'register.inc.php'; $user_form = UserForm::getUserForm()->getForm($user->getInfo()); } else { $errors['err'] = __('Access Denied. Contact your help desk administrator to have an account registered for you'); // fall through to show login page again } } else { Http::redirect($_SESSION['_client']['auth']['dest'] ?: 'tickets.php'); } } elseif (!$errors['err']) { $errors['err'] = __('Invalid username or password - try again!'); } $suggest_pwreset = true; } elseif ($_POST && isset($_POST['lticket'])) { if (!Validator::is_email($_POST['lemail'])) { $errors['err'] = __('Valid email address and ticket number required'); } elseif ($user = UserAuthenticationBackend::process($_POST['lemail'], $_POST['lticket'], $errors)) { // If email address verification is not required, then provide // immediate access to the ticket! if (!$cfg->isClientEmailVerificationRequired()) { Http::redirect('tickets.php'); } // We're using authentication backend so we can guard aganist brute // force attempts (which doesn't buy much since the link is emailed) $user->sendAccessLink(); $msg = sprintf(__("%s - access link sent to your email!"), Format::htmlchars($user->getName()->getFirst())); $_POST = null; } elseif (!$errors['err']) { $errors['err'] = __('Invalid email or ticket number - try again!'); }
See LICENSE.TXT for details. vim: expandtab sw=4 ts=4 sts=4: **********************************************************************/ require 'admin.inc.php'; include_once INCLUDE_DIR . 'class.email.php'; include_once INCLUDE_DIR . 'class.csrf.php'; $info = array(); $info['subj'] = 'osTicket test email'; if ($_POST) { $errors = array(); $email = null; if (!$_POST['email_id'] || !($email = Email::lookup($_POST['email_id']))) { $errors['email_id'] = __('Select from email address'); } if (!$_POST['email'] || !Validator::is_email($_POST['email'])) { $errors['email'] = __('To email address required'); } if (!$_POST['subj']) { $errors['subj'] = __('Subject required'); } if (!$_POST['message']) { $errors['message'] = __('Message required'); } if (!$errors && $email) { if ($email->send($_POST['email'], $_POST['subj'], Format::sanitize($_POST['message']), null, array('reply-tag' => false))) { $msg = Format::htmlchars(sprintf(__('Test email sent successfully to <%s>'), $_POST['email'])); Draft::deleteForNamespace('email.diag'); } else { $errors['err'] = __('Error sending email - try again.'); }
function save($id, $vars, &$errors) { include_once INCLUDE_DIR . 'class.dept.php'; if ($id && $id != $vars['staff_id']) { $errors['err'] = 'Internal Error'; } if (!$vars['firstname'] || !$vars['lastname']) { $errors['name'] = 'First and last name required'; } if (!$vars['username'] || strlen($vars['username']) < 3) { $errors['username'] = '******'; } else { //check if the username is already in-use. $sql = 'SELECT staff_id FROM ' . STAFF_TABLE . ' WHERE username='******'username']); if ($id) { $sql .= ' AND staff_id!=' . db_input($id); } if (db_num_rows(db_query($sql))) { $errors['username'] = '******'; } } if (!$vars['email'] || !Validator::is_email($vars['email'])) { $errors['email'] = 'Valid email required'; } elseif (Email::getIdByEmail($vars['email'])) { $errors['email'] = 'Already in-use system email'; } if ($vars['phone'] && !Validator::is_phone($vars['phone'])) { $errors['phone'] = 'Valid number required'; } if ($vars['mobile'] && !Validator::is_phone($vars['mobile'])) { $errors['mobile'] = 'Valid number required'; } if ($vars['npassword'] || $vars['vpassword'] || !$id) { if (!$vars['npassword'] && !$id) { $errors['npassword'] = '******'; } elseif ($vars['npassword'] && strcmp($vars['npassword'], $vars['vpassword'])) { $errors['vpassword'] = '******'; } elseif ($vars['npassword'] && strlen($vars['npassword']) < 6) { $errors['npassword'] = '******'; } } if (!$vars['dept_id']) { $errors['dept'] = 'Department required'; } if (!$vars['group_id']) { $errors['group'] = 'Group required'; } if (!$errors) { $sql = ' SET updated=NOW() ' . ',isadmin=' . db_input($vars['isadmin']) . ',isactive=' . db_input($vars['isactive']) . ',new_tkt_not=' . db_input($vars['new_tkt_not']) . ',close_tkt_not=' . db_input($vars['close_tkt_not']) . ',isvisible=' . db_input(isset($vars['isvisible']) ? 1 : 0) . ',onvacation=' . db_input(isset($vars['onvacation']) ? 1 : 0) . ',dept_id=' . db_input($vars['dept_id']) . ',group_id=' . db_input($vars['group_id']) . ',username='******'username'])) . ',firstname=' . db_input(Format::striptags($vars['firstname'])) . ',lastname=' . db_input(Format::striptags($vars['lastname'])) . ',email=' . db_input($vars['email']) . ',phone="' . db_input($vars['phone'], false) . '"' . ',phone_ext=' . db_input($vars['phone_ext']) . ',mobile="' . db_input($vars['mobile'], false) . '"' . ',signature=' . db_input(Format::striptags($vars['signature'])); if ($vars['npassword']) { $sql .= ',passwd=' . db_input(md5($vars['npassword'])); } if (isset($vars['resetpasswd'])) { $sql .= ',change_passwd=1'; } if ($id) { $sql = 'UPDATE ' . STAFF_TABLE . ' ' . $sql . ' WHERE staff_id=' . db_input($id); if (!db_query($sql) || !db_affected_rows()) { $errors['err'] = 'Unable to update the user. Internal error occured'; } } else { $sql = 'INSERT INTO ' . STAFF_TABLE . ' ' . $sql . ',created=NOW()'; if (db_query($sql) && ($uID = db_insert_id())) { return $uID; } $errors['err'] = 'Unable to create user. Internal error'; } } return $errors ? false : true; }
function save($id, $vars, &$errors) { global $cfg; //very basic checks $vars['name'] = Format::striptags(trim($vars['name'])); if ($id && $id != $vars['id']) { $errors['err'] = 'Internal error. Get technical help.'; } if (!$vars['email'] || !Validator::is_email($vars['email'])) { $errors['email'] = 'Valid email required'; } elseif (($eid = Email::getIdByEmail($vars['email'])) && $eid != $id) { $errors['email'] = 'Email already exits'; } elseif ($cfg && !strcasecmp($cfg->getAdminEmail(), $vars['email'])) { $errors['email'] = 'Email already used as admin email!'; } elseif (Staff::getIdByEmail($vars['email'])) { //make sure the email doesn't belong to any of the staff $errors['email'] = 'Email in-use by a staff member'; } if (!$vars['name']) { $errors['name'] = 'Email name required'; } if ($vars['mail_active'] || $vars['smtp_active'] && $vars['smtp_auth']) { if (!$vars['userid']) { $errors['userid'] = 'Username missing'; } if (!$id && !$vars['passwd']) { $errors['passwd'] = 'Password required'; } } if ($vars['mail_active']) { //Check pop/imapinfo only when enabled. if (!function_exists('imap_open')) { $errors['mail_active'] = 'IMAP doesn\'t exist. PHP must be compiled with IMAP enabled.'; } if (!$vars['mail_host']) { $errors['mail_host'] = 'Host name required'; } if (!$vars['mail_port']) { $errors['mail_port'] = 'Port required'; } if (!$vars['mail_protocol']) { $errors['mail_protocol'] = 'Select protocol'; } if (!$vars['mail_fetchfreq'] || !is_numeric($vars['mail_fetchfreq'])) { $errors['mail_fetchfreq'] = 'Fetch interval required'; } if (!$vars['mail_fetchmax'] || !is_numeric($vars['mail_fetchmax'])) { $errors['mail_fetchmax'] = 'Maximum emails required'; } if (!$vars['dept_id'] || !is_numeric($vars['dept_id'])) { $errors['dept_id'] = 'You must select a Dept.'; } if (!$vars['priority_id']) { $errors['priority_id'] = 'You must select a priority'; } if (!isset($vars['postfetch'])) { $errors['postfetch'] = 'Indicate what to do with fetched emails'; } elseif (!strcasecmp($vars['postfetch'], 'archive')) { if (!$vars['mail_archivefolder']) { $errors['postfetch'] = 'Valid folder required'; } } } if ($vars['smtp_active']) { if (!$vars['smtp_host']) { $errors['smtp_host'] = 'Host name required'; } if (!$vars['smtp_port']) { $errors['smtp_port'] = 'Port required'; } } //abort on errors if ($errors) { return false; } if (!$errors && ($vars['mail_host'] && $vars['userid'])) { $sql = 'SELECT email_id FROM ' . EMAIL_TABLE . ' WHERE mail_host=' . db_input($vars['mail_host']) . ' AND userid=' . db_input($vars['userid']); if ($id) { $sql .= ' AND email_id!=' . db_input($id); } if (db_num_rows(db_query($sql))) { $errors['userid'] = $errors['host'] = 'Host/userid combination already in-use.'; } } $passwd = $vars['passwd'] ? $vars['passwd'] : $vars['cpasswd']; if (!$errors && $vars['mail_active']) { //note: password is unencrypted at this point...MailFetcher expect plain text. $fetcher = new MailFetcher($vars['userid'], $passwd, $vars['mail_host'], $vars['mail_port'], $vars['mail_protocol'], $vars['mail_encryption']); if (!$fetcher->connect()) { $errors['err'] = 'Invalid login. Check ' . Format::htmlchars($vars['mail_protocol']) . ' settings'; $errors['mail'] = '<br>' . $fetcher->getLastError(); } elseif ($vars['mail_archivefolder'] && !$fetcher->checkMailbox($vars['mail_archivefolder'], true)) { $errors['postfetch'] = 'Invalid or unknown mail folder! >> ' . $fetcher->getLastError() . ''; if (!$errors['mail']) { $errors['mail'] = 'Invalid or unknown archive folder!'; } } } if (!$errors && $vars['smtp_active']) { //Check SMTP login only. require_once 'Mail.php'; // PEAR Mail package $smtp = mail::factory('smtp', array('host' => $vars['smtp_host'], 'port' => $vars['smtp_port'], 'auth' => $vars['smtp_auth'] ? true : false, 'username' => $vars['userid'], 'password' => $passwd, 'timeout' => 20, 'debug' => false)); $mail = $smtp->connect(); if (PEAR::isError($mail)) { $errors['err'] = 'Unable to login. Check SMTP settings.'; $errors['smtp'] = '<br>' . $mail->getMessage(); } else { $smtp->disconnect(); //Thank you, sir! } } if ($errors) { return false; } //Default to default priority and dept.. if (!$vars['priority_id'] && $cfg) { $vars['priority_id'] = $cfg->getDefaultPriorityId(); } if (!$vars['dept_id'] && $cfg) { $vars['dept_id'] = $cfg->getDefaultDeptId(); } $sql = 'updated=NOW(),mail_errors=0, mail_lastfetch=NULL' . ',email=' . db_input($vars['email']) . ',name=' . db_input(Format::striptags($vars['name'])) . ',dept_id=' . db_input($vars['dept_id']) . ',priority_id=' . db_input($vars['priority_id']) . ',noautoresp=' . db_input(isset($vars['noautoresp']) ? 1 : 0) . ',userid=' . db_input($vars['userid']) . ',mail_active=' . db_input($vars['mail_active']) . ',mail_host=' . db_input($vars['mail_host']) . ',mail_protocol=' . db_input($vars['mail_protocol'] ? $vars['mail_protocol'] : 'POP') . ',mail_encryption=' . db_input($vars['mail_encryption']) . ',mail_port=' . db_input($vars['mail_port'] ? $vars['mail_port'] : 0) . ',mail_fetchfreq=' . db_input($vars['mail_fetchfreq'] ? $vars['mail_fetchfreq'] : 0) . ',mail_fetchmax=' . db_input($vars['mail_fetchmax'] ? $vars['mail_fetchmax'] : 0) . ',smtp_active=' . db_input($vars['smtp_active']) . ',smtp_host=' . db_input($vars['smtp_host']) . ',smtp_port=' . db_input($vars['smtp_port'] ? $vars['smtp_port'] : 0) . ',smtp_auth=' . db_input($vars['smtp_auth']) . ',smtp_spoofing=' . db_input(isset($vars['smtp_spoofing']) ? 1 : 0) . ',notes=' . db_input($vars['notes']); //Post fetch email handling... if ($vars['postfetch'] && !strcasecmp($vars['postfetch'], 'delete')) { $sql .= ',mail_delete=1,mail_archivefolder=NULL'; } elseif ($vars['postfetch'] && !strcasecmp($vars['postfetch'], 'archive') && $vars['mail_archivefolder']) { $sql .= ',mail_delete=0,mail_archivefolder=' . db_input($vars['mail_archivefolder']); } else { $sql .= ',mail_delete=0,mail_archivefolder=NULL'; } if ($vars['passwd']) { //New password - encrypt. $sql .= ',userpass='******'passwd'], SECRET_SALT)); } if ($id) { //update $sql = 'UPDATE ' . EMAIL_TABLE . ' SET ' . $sql . ' WHERE email_id=' . db_input($id); if (db_query($sql) && db_affected_rows()) { return true; } $errors['err'] = 'Unable to update email. Internal error occurred'; } else { $sql = 'INSERT INTO ' . EMAIL_TABLE . ' SET ' . $sql . ',created=NOW()'; if (db_query($sql) && ($id = db_insert_id())) { return $id; } $errors['err'] = 'Unable to add email. Internal error'; } return false; }
function save_rules($id, $vars, &$errors) { $matches = array('name', 'email', 'subject', 'body', 'header'); $types = array('equal', 'not_equal', 'contains', 'dn_contain'); $rules = array(); for ($i = 1; $i <= 25; $i++) { //Expecting no more than 25 rules... if ($vars["rule_w{$i}"] || $vars["rule_h{$i}"]) { if (!$vars["rule_w{$i}"] || !in_array($vars["rule_w{$i}"], $matches)) { $errors["rule_{$i}"] = 'Invalid match selection'; } elseif (!$vars["rule_h{$i}"] || !in_array($vars["rule_h{$i}"], $types)) { $errors["rule_{$i}"] = 'Invalid match type selection'; } elseif (!$vars["rule_v{$i}"]) { $errors["rule_{$i}"] = 'Value required'; } elseif ($vars["rule_w{$i}"] == 'email' && $vars["rule_h{$i}"] == 'equal' && !Validator::is_email($vars["rule_v{$i}"])) { $errors["rule_{$i}"] = 'Valid email required for the match type'; } else { //for everything-else...we assume it's valid. $rules[] = array('w' => $vars["rule_w{$i}"], 'h' => $vars["rule_h{$i}"], 'v' => $vars["rule_v{$i}"]); } } elseif ($vars["rule_v{$i}"]) { $errors["rule_{$i}"] = 'Incomplete selection'; } } if (!$rules && is_array($vars["rules"])) { # XXX: Validation bypass $rules = $vars["rules"]; } elseif (!$rules && !$errors) { $errors['rules'] = 'You must set at least one rule.'; } if ($errors) { return false; } if (!$id) { return true; } //When ID is 0 then assume it was just validation... //Clear existing rules...we're doing mass replace on each save!! db_query('DELETE FROM ' . EMAIL_FILTER_RULE_TABLE . ' WHERE filter_id=' . db_input($id)); $num = 0; foreach ($rules as $rule) { $rule['filter_id'] = $id; if (FilterRule::create($rule, $errors)) { $num++; } } return $num; }
vim: expandtab sw=4 ts=4 sts=4: $Id: $ **********************************************************************/ require 'staff.inc.php'; $nav->setTabActive('directory'); $nav->addSubMenu(array('desc' => 'Staff Members', 'href' => 'directory.php', 'iconclass' => 'staff')); $WHERE = ' WHERE isvisible=1 '; $sql = ' SELECT staff.staff_id,staff.dept_id, firstname,lastname,email,phone,phone_ext,mobile,dept_name,onvacation ' . ' FROM ' . STAFF_TABLE . ' staff LEFT JOIN ' . DEPT_TABLE . ' USING(dept_id)'; if ($_POST && $_POST['a'] == 'search') { $searchTerm = $_POST['query']; if ($searchTerm) { $query = db_real_escape($searchTerm, false); //escape the term ONLY...no quotes. if (is_numeric($searchTerm)) { $WHERE .= " AND staff.phone LIKE '%{$query}%'"; } elseif (strpos($searchTerm, '@') && Validator::is_email($searchTerm)) { $WHERE .= " AND staff.email='{$query}'"; } else { $WHERE .= " AND ( staff.email LIKE '%{$query}%'" . " OR staff.lastname LIKE '%{$query}%'" . " OR staff.firstname LIKE '%{$query}%'" . ' ) '; } } if ($_POST['dept'] && is_numeric($_POST['dept'])) { $WHERE .= ' AND staff.dept_id=' . db_input($_POST['dept']); } } $users = db_query("{$sql} {$WHERE} ORDER BY lastname,firstname"); //Render the page. require_once STAFFINC_DIR . 'header.inc.php'; ?> <div> <?if($errors['err']) {?>
//Search?? Somebody...get me some coffee $deep_search=false; if($search): $qstr.='&a='.urlencode($_REQUEST['a']); $qstr.='&t='.urlencode($_REQUEST['t']); if(isset($_REQUEST['advance_search'])){ //advance search box! $qstr.='&advance_search=Search'; } //query if($searchTerm){ $qstr.='&query='.urlencode($searchTerm); $queryterm=db_real_escape($searchTerm,false); //escape the term ONLY...no quotes. if(is_numeric($searchTerm)){ $qwhere.=" AND ticket.ticketID LIKE '$queryterm%'"; }elseif(strpos($searchTerm,'@') && Validator::is_email($searchTerm)){ //pulling all tricks! $qwhere.=" AND ticket.email='$queryterm'"; }else{//Deep search! //This sucks..mass scan! search anything that moves! $deep_search=true; if($_REQUEST['stype'] && $_REQUEST['stype']=='FT') { //Using full text on big fields. $qwhere.=" AND ( ticket.email LIKE '%$queryterm%'". " OR ticket.name LIKE '%$queryterm%'". " OR ticket.subject LIKE '%$queryterm%'". " OR note.title LIKE '%$queryterm%'". " OR MATCH(message.message) AGAINST('$queryterm')". " OR MATCH(response.response) AGAINST('$queryterm')". " OR MATCH(note.note) AGAINST('$queryterm')". ' ) '; }else{