Esempio n. 1
0
 while ($_FILES['attachment']['name'][$i]) {
     if (!$cfg->allowOnlineAttachments()) {
         //Something wrong with the form...user shouldn't have an option to attach
         $errors['attachment'] = 'File [ ' . $_FILES['attachment']['name'] . ' ] rejected: no upload permission.';
     } elseif (!$cfg->canUploadFiles()) {
         //TODO: saved vs emailed attachments...admin config??
         $errors['attachment'] = _('Upload dir invalid. Contact admin.');
     } elseif (!$cfg->canUploadFileType($_FILES['attachment']['name'][$i])) {
         $errors['attachment'] = _('Invalid file type') . ' [ ' . Format::htmlchars($_FILES['attachment']['name'][$i]) . ' ]';
     } elseif ($_FILES['attachment']['size'][$i] > $cfg->getMaxFileSize()) {
         $errors['attachment'] = _('File is too big') . ': ' . $_FILES['attachment']['size'][$i] . ' bytes';
     }
     $i++;
 }
 //Make sure the email is not banned
 if (!$errors && BanList::isbanned($ticket->getEmail())) {
     $errors['err'] = _('Email is in banlist. Must be removed to reply');
 }
 //If no error...do the do.
 if (!$errors && ($respId = $ticket->postResponse($_POST['response'], $_POST['signature'], $_FILES['attachment']))) {
     $msg = _('Response Posted Successfully');
     //Set status if any.
     $wasOpen = $ticket->isOpen();
     if (isset($_POST['ticket_status']) && $_POST['ticket_status']) {
         if ($ticket->setStatus($_POST['ticket_status']) && $ticket->reload()) {
             $note = sprintf(_('%s %s the ticket on reply'), $thisuser->getName(), $ticket->isOpen() ? _('reopened') : _('closed'));
             $ticket->logActivity(sprintf(_('Ticket status changed to %s'), $ticket->isOpen() ? _('Open') : _('Closed')), $note);
         }
     }
     //Finally upload attachment if any
     if ($_FILES['attachment'] && $_FILES['attachment']['size']) {
//Useful warnings and errors the user might want to know!
if ($ticket->isClosed() && !$ticket->isReopenable()) {
    $warn = sprintf(__('Current ticket status (%s) does not allow the end user to reply.'), $ticket->getStatus());
} elseif ($ticket->isAssigned() && ($staff && $staff->getId() != $thisstaff->getId() || $team && !$team->hasMember($thisstaff))) {
    $warn .= sprintf('&nbsp;&nbsp;<span class="Icon assignedTicket">%s</span>', sprintf(__('Ticket is assigned to %s'), implode('/', $ticket->getAssignees())));
}
if (!$errors['err']) {
    if ($lock && $lock->getStaffId() != $thisstaff->getId()) {
        $errors['err'] = sprintf(__('This ticket is currently locked by %s'), $lock->getStaffName());
    } elseif ($emailBanned = TicketFilter::isBanned($ticket->getEmail())) {
        $errors['err'] = __('Email is in banlist! Must be removed before any reply/response');
    }
    // elseif (!Validator::is_valid_email($ticket->getEmail()))
    //     $errors['err'] = __('EndUser email address is not valid! Consider updating it before responding');
}
$unbannable = $emailBanned ? BanList::includes($ticket->getEmail()) : false;
if ($ticket->isOverdue()) {
    $warn .= '&nbsp;&nbsp;<span class="Icon overdueTicket">' . __('Marked overdue!') . '</span>';
}
?>
<table width="940" cellpadding="2" cellspacing="0" border="0">
    <tr>
        <td width="20%" class="has_bottom_border">
             <h2><a href="tickets.php?id=<?php 
echo $ticket->getId();
?>
"
             title="<?php 
echo __('Reload');
?>
"><i class="icon-refresh"></i>
Esempio n. 3
0
     if (!$thisstaff->canBanEmails()) {
         $errors['err'] = __('Permission Denied. You are not allowed to ban emails');
     } elseif (BanList::includes($ticket->getEmail())) {
         $errors['err'] = __('Email already in banlist');
     } elseif (Banlist::add($ticket->getEmail(), $thisstaff->getName())) {
         $msg = sprintf(__('Email %s added to banlist'), $ticket->getEmail());
     } else {
         $errors['err'] = __('Unable to add the email to banlist');
     }
     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');
     }
Esempio n. 4
0
             }
             break;
         default:
             $errors['err']='Unknown action '.$_POST['do'];
     }
     break;
 case 'banlist': //BanList.
     require_once(INCLUDE_DIR.'class.banlist.php');
     switch(strtolower($_POST['a'])) {
         case 'add':
             if(!$_POST['email'] || !Validator::is_email($_POST['email']))
                 $errors['err']='Please enter a valid email.';
             elseif(BanList::isbanned($_POST['email']))
                 $errors['err']='Email already banned';
             else{
                 if(BanList::add($_POST['email'],$thisuser->getName()))
                     $msg='Email added to banlist';
                 else
                     $errors['err']='Unable to add email to banlist. Try again';
             }
             break;
         case 'remove':
             if(!$_POST['ids'] || !is_array($_POST['ids'])) {
                 $errors['err']='You must select at least one email';
             }else{
                 //TODO: move mass remove to Banlist class when needed elsewhere...at the moment this is the only place.
                 $sql='DELETE FROM '.BANLIST_TABLE.' WHERE id IN ('.implode(',',$_POST['ids']).')';
                 if(db_query($sql) && ($num=db_affected_rows()))
                     $msg="$num of $count selected emails removed from banlist";
                 else
                     $errors['err']='Unable to make remove selected emails. Try again.';
Esempio n. 5
0
 function create($var, &$errors, $origin, $autorespond = true, $alertstaff = true)
 {
     global $cfg, $thisclient, $_FILES;
     /* Coders never code so fully and joyfully as when they do it for free  - Peter Rotich */
     $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');
     if (strcasecmp($origin, 'web') == 0) {
         //Help topic only applicable on web tickets.
         $fields['topicId'] = array('type' => 'int', 'required' => 1, 'error' => 'Select help topic');
     } elseif (strcasecmp($origin, 'staff') == 0) {
         //tickets created by staff...e.g on callins.
         $fields['deptId'] = array('type' => 'int', 'required' => 1, 'error' => 'Dept. required');
         $fields['source'] = array('type' => 'string', 'required' => 1, 'error' => 'Indicate source');
         $fields['duedate'] = array('type' => 'date', 'required' => 0, 'error' => 'Invalid date - must be MM/DD/YY');
     } else {
         //Incoming emails
         $fields['emailId'] = array('type' => 'int', 'required' => 1, 'error' => 'Email unknown');
     }
     $fields['pri'] = array('type' => 'int', 'required' => 0, 'error' => 'Invalid Priority');
     $fields['phone'] = array('type' => 'phone', 'required' => 0, 'error' => 'Valid phone # required');
     $validate = new Validator($fields);
     if (!$validate->validate($var)) {
         $errors = array_merge($errors, $validate->errors());
     }
     //Make sure the email is not banned
     if (!$errors && BanList::isbanned($var['email'])) {
         $errors['err'] = 'Ticket denied. Error #403';
         //We don't want to tell the user the real reason...Psssst.
         Sys::log(LOG_WARNING, 'Ticket denied', 'Banned email - ' . $var['email']);
         //We need to let admin know which email got banned.
     }
     if (!$errors && $thisclient && strcasecmp($thisclient->getEmail(), $var['email'])) {
         $errors['email'] = 'Email mismatch.';
     }
     //Make sure phone extension is valid
     if ($var['phone_ext']) {
         if (!is_numeric($var['phone_ext']) && !$errors['phone']) {
             $errors['phone'] = 'Invalid phone ext.';
         } elseif (!$var['phone']) {
             //make sure they just didn't enter ext without phone #
             $errors['phone'] = 'Phone number required';
         }
     }
     //Make sure the due date is valid
     if ($var['duedate']) {
         if (!$var['time'] || strpos($var['time'], ':') === false) {
             $errors['time'] = 'Select time';
         } elseif (strtotime($var['duedate'] . ' ' . $var['time']) === false) {
             $errors['duedate'] = 'Invalid duedate';
         } elseif (strtotime($var['duedate'] . ' ' . $var['time']) <= time()) {
             $errors['duedate'] = 'Due date must be in the future';
         }
     }
     //check attachment..if any is set ...only set on webbased tickets..
     if ($_FILES['attachment']['name'] && $cfg->allowOnlineAttachments()) {
         if (!$cfg->canUploadFileType($_FILES['attachment']['name'])) {
             $errors['attachment'] = 'Invalid file type [ ' . Format::htmlchars($_FILES['attachment']['name']) . ' ]';
         } elseif ($_FILES['attachment']['size'] > $cfg->getMaxFileSize()) {
             $errors['attachment'] = 'File is too big. Max ' . $cfg->getMaxFileSize() . ' bytes allowed';
         }
     }
     //check ticket limits..if limit set is >0
     //TODO: Base ticket limits on SLA...
     if ($var['email'] && !$errors && $cfg->getMaxOpenTickets() > 0 && strcasecmp($origin, 'staff')) {
         $openTickets = Ticket::getOpenTicketsByEmail($var['email']);
         if ($openTickets >= $cfg->getMaxOpenTickets()) {
             $errors['err'] = "You've reached the maximum open tickets allowed.";
             //Send the notice only once (when the limit is reached) incase of autoresponders at client end.
             if ($cfg->getMaxOpenTickets() == $openTickets && $cfg->sendOverlimitNotice()) {
                 if ($var['deptId']) {
                     $dept = new Dept($var['deptId']);
                 }
                 if (!$dept || !($tplId = $dept->getTemplateId())) {
                     $tplId = $cfg->getDefaultTemplateId();
                 }
                 $sql = 'SELECT ticket_overlimit_subj,ticket_overlimit_body FROM ' . EMAIL_TEMPLATE_TABLE . ' WHERE cfg_id=' . db_input($cfg->getId()) . ' AND tpl_id=' . db_input($tplId);
                 $resp = db_query($sql);
                 if (db_num_rows($resp) && (list($subj, $body) = db_fetch_row($resp))) {
                     $body = str_replace("%name", $var['name'], $body);
                     $body = str_replace("%email", $var['email'], $body);
                     $body = str_replace("%url", $cfg->getBaseUrl(), $body);
                     $body = str_replace('%signature', $dept && $dept->isPublic() ? $dept->getSignature() : '', $body);
                     if (!$dept || !($email = $dept->getAutoRespEmail())) {
                         $email = $cfg->getDefaultEmail();
                     }
                     if ($email) {
                         $email->send($var['email'], $subj, $body);
                     }
                 }
                 //Alert admin...this might be spammy (no option to disable)...but it is helpful..I think.
                 $msg = 'Support ticket request denied for ' . $var['email'] . "\n" . 'Open ticket:' . $openTickets . "\n" . 'Max Allowed:' . $cfg->getMaxOpenTickets() . "\n\nNotice only sent once";
                 Sys::alertAdmin('Overlimit Notice', $msg);
             }
         }
     }
     //Any error above is fatal.
     if ($errors) {
         return 0;
     }
     // OK...just do it.
     $deptId = $var['deptId'];
     //pre-selected Dept if any.
     $priorityId = $var['pri'];
     $source = ucfirst($var['source']);
     $topic = NULL;
     // Intenal mapping magic...see if we need to overwrite anything
     if (isset($var['topicId'])) {
         //Ticket created via web by user/or staff
         if ($var['topicId'] && ($topic = new Topic($var['topicId'])) && $topic->getId()) {
             $deptId = $deptId ? $deptId : $topic->getDeptId();
             $priorityId = $priorityId ? $priorityId : $topic->getPriorityId();
             $topicDesc = $topic->getName();
             if ($autorespond) {
                 $autorespond = $topic->autoRespond();
             }
         }
         $source = $var['source'] ? $var['source'] : 'Web';
     } elseif ($var['emailId'] && !$var['deptId']) {
         //Emailed Tickets
         $email = new Email($var['emailId']);
         if ($email && $email->getId()) {
             $deptId = $email->getDeptId();
             $priorityId = $priorityId ? $priorityId : $email->getPriorityId();
             if ($autorespond) {
                 $autorespond = $email->autoRespond();
             }
         }
         $email = null;
         $source = 'Email';
     } elseif ($var['deptId']) {
         //Opened by staff.
         $deptId = $var['deptId'];
         $source = ucfirst($var['source']);
     }
     //Don't auto respond to mailer daemons.
     if (strpos(strtolower($var['email']), 'mailer-daemon@') !== false || strpos(strtolower($var['email']), 'postmaster@') !== false) {
         $autorespond = false;
     }
     //Last minute checks
     $priorityId = $priorityId ? $priorityId : $cfg->getDefaultPriorityId();
     $deptId = $deptId ? $deptId : $cfg->getDefaultDeptId();
     $topicId = $var['topicId'] ? $var['topicId'] : 0;
     $ipaddress = $var['ip'] ? $var['ip'] : $_SERVER['REMOTE_ADDR'];
     //We are ready son...hold on to the rails.
     $extId = Ticket::genExtRandID();
     $sql = 'INSERT INTO ' . TICKET_TABLE . ' SET created=NOW() ' . ',ticketID=' . db_input($extId) . ',dept_id=' . db_input($deptId) . ',topic_id=' . db_input($topicId) . ',priority_id=' . db_input($priorityId) . ',email=' . db_input($var['email']) . ',name=' . db_input(Format::striptags($var['name'])) . ',subject=' . db_input(Format::striptags($var['subject'])) . ',helptopic=' . db_input(Format::striptags($topicDesc)) . ',phone="' . db_input($var['phone'], false) . '"' . ',phone_ext=' . db_input($var['phone_ext'] ? $var['phone_ext'] : '') . ',ip_address=' . db_input($ipaddress) . ',source=' . db_input($source);
     //Make sure the origin is staff - avoid firebug hack!
     if ($var['duedate'] && !strcasecmp($origin, 'staff')) {
         $sql .= ',duedate=' . db_input(date('Y-m-d G:i', Misc::dbtime($var['duedate'] . ' ' . $var['time'])));
     }
     //echo $sql;
     $ticket = null;
     //return $ticket;
     if (db_query($sql) && ($id = db_insert_id())) {
         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);
             //TODO: RETHING what happens if this fails?? [At the moment on failure random ID is used...making stuff usable]
         }
         //Load newly created ticket.
         $ticket = new Ticket($id);
         //post the message.
         $msgid = $ticket->postMessage($var['message'], $source, $var['mid'], $var['header'], true);
         //TODO: recover from postMessage error??
         //Upload attachments...web based.
         if ($_FILES['attachment']['name'] && $cfg->allowOnlineAttachments() && $msgid) {
             if (!$cfg->allowAttachmentsOnlogin() || $cfg->allowAttachmentsOnlogin() && ($thisclient && $thisclient->isValid())) {
                 $ticket->uploadAttachment($_FILES['attachment'], $msgid, 'M');
                 //TODO: recover from upload issues?
             }
         }
         $dept = $ticket->getDept();
         if (!$dept || !($tplId = $dept->getTemplateId())) {
             $tplId = $cfg->getDefaultTemplateId();
         }
         //Overwrite auto responder if the FROM email is one of the internal emails...loop control.
         if ($autorespond && Email::getIdByEmail($ticket->getEmail())) {
             $autorespond = false;
         }
         //SEND OUT NEW TICKET AUTORESP && ALERTS.
         //New Ticket AutoResponse..
         if ($autorespond && $cfg->autoRespONNewTicket() && $dept->autoRespONNewTicket()) {
             $sql = 'SELECT ticket_autoresp_subj,ticket_autoresp_body FROM ' . EMAIL_TEMPLATE_TABLE . ' WHERE cfg_id=' . db_input($cfg->getId()) . ' AND tpl_id=' . db_input($tplId);
             if (($resp = db_query($sql)) && db_num_rows($resp) && (list($subj, $body) = db_fetch_row($resp))) {
                 $body = $ticket->replaceTemplateVars($body);
                 $subj = $ticket->replaceTemplateVars($subj);
                 $body = str_replace('%message', $var['issue'] ? $var['issue'] : $var['message'], $body);
                 $body = str_replace('%signature', $dept && $dept->isPublic() ? $dept->getSignature() : '', $body);
                 if (!$dept || !($email = $dept->getAutoRespEmail())) {
                     $email = $cfg->getDefaultEmail();
                 }
                 if ($email) {
                     //Reply separator tag.
                     if ($cfg->stripQuotedReply() && ($tag = $cfg->getReplySeparator())) {
                         $body = "\n{$tag}\n\n" . $body;
                     }
                     $email->send($ticket->getEmail(), $subj, $body);
                 }
             } else {
                 Sys::log(LOG_WARNING, 'Template Fetch Error', "Unable to fetch autoresponse template #{$tplId}");
             }
         }
         //If enabled...send alert to staff (New Ticket Alert)
         if ($alertstaff && $cfg->alertONNewTicket() && is_object($ticket)) {
             $sql = 'SELECT ticket_alert_subj,ticket_alert_body FROM ' . EMAIL_TEMPLATE_TABLE . ' WHERE cfg_id=' . db_input($cfg->getId()) . ' AND tpl_id=' . db_input($tplId);
             if (($resp = db_query($sql)) && db_num_rows($resp) && (list($subj, $body) = db_fetch_row($resp))) {
                 $body = $ticket->replaceTemplateVars($body);
                 $subj = $ticket->replaceTemplateVars($subj);
                 $body = str_replace('%message', $var['issue'] ? $var['issue'] : $var['message'], $body);
                 if (!($email = $cfg->getAlertEmail())) {
                     $email = $cfg->getDefaultEmail();
                 }
                 if ($email && $email->getId()) {
                     $sentlist = array();
                     //Admin Alert.
                     if ($cfg->alertAdminONNewTicket()) {
                         $alert = str_replace("%staff", 'Admin', $body);
                         $email->send($cfg->getAdminEmail(), $subj, $alert);
                         $sentlist[] = $cfg->getAdminEmail();
                     }
                     //get the list
                     $recipients = array();
                     //Dept. Manager
                     if ($cfg->alertDeptManagerONNewTicket()) {
                         $recipients[] = $dept->getManager();
                     }
                     //Staff members
                     if ($cfg->alertDeptMembersONNewTicket()) {
                         $sql = 'SELECT staff_id FROM ' . STAFF_TABLE . ' WHERE onvacation=0 AND dept_id=' . db_input($dept->getId());
                         if (($users = db_query($sql)) && db_num_rows($users)) {
                             while (list($id) = db_fetch_row($users)) {
                                 $recipients[] = new Staff($id);
                             }
                         }
                     }
                     foreach ($recipients as $k => $staff) {
                         if (!$staff || !is_object($staff) || !$staff->isAvailable()) {
                             continue;
                         }
                         if (in_array($staff->getEmail(), $sentlist)) {
                             continue;
                         }
                         //avoid duplicate emails.
                         $alert = str_replace("%staff", $staff->getFirstName(), $body);
                         $email->send($staff->getEmail(), $subj, $alert);
                         $sentlist[] = $staff->getEmail();
                     }
                 }
             } else {
                 Sys::log(LOG_WARNING, 'Template Fetch Error', "Unable to fetch 'new ticket' alert template #{$tplId}");
             }
         }
     }
     return $ticket;
 }
Esempio n. 6
0
//We are ready baby...lets roll. Akon rocks!
$dept = $ticket->getDept();
//Dept
$staff = $ticket->getStaff();
//Assiged staff.
$lock = $ticket->getLock();
//Ticket lock obj
$id = $ticket->getId();
//Ticket ID.
if ($staff) {
    $warn .= '&nbsp;&nbsp;<span class="Icon assignedTicket">Ticket is assigned to ' . $staff->getName() . '</span>';
}
if (!$errors['err'] && ($lock && $lock->getStaffId() != $thisuser->getId())) {
    $errors['err'] = 'This ticket is currently locked by another staff member!';
}
if (!$errors['err'] && ($emailBanned = BanList::isbanned($ticket->getEmail()))) {
    $errors['err'] = 'Email is in banlist! Must be removed before any reply/response';
}
if ($ticket->isOverdue()) {
    $warn .= '&nbsp;&nbsp;<span class="Icon overdueTicket">Marked overdue!</span>';
}
?>
<table width="100%" cellpadding="2" cellspacing="0" border="0">
	<tr>
		<td class="msg" width=50%>Ticket #<?php 
echo $ticket->getExtId();
?>
&nbsp;<a
			href="tickets.php?id=<?php 
echo $id;
?>
Esempio n. 7
0
         $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 {
         $count = count($_POST['ids']);
         switch (strtolower($_POST['a'])) {
Esempio n. 8
0
/**
* @project ApPHP Business Directory
* @copyright (c) 2011 ApPHP
* @author ApPHP <*****@*****.**>
* @license http://www.gnu.org/licenses/
*/
// *** Make sure the file isn't accessed directly
defined('APPHP_EXEC') or die('Restricted Access');
//--------------------------------------------------------------------------
if ($objLogin->IsLoggedInAsAdmin()) {
    $action = MicroGrid::GetParameter('action');
    $rid = MicroGrid::GetParameter('rid');
    $mode = 'view';
    $msg = '';
    $objBanList = new BanList();
    if ($action == 'add') {
        $mode = 'add';
    } else {
        if ($action == 'create') {
            if ($objBanList->AddRecord()) {
                $msg = draw_success_message(_ADDING_OPERATION_COMPLETED, false);
                $mode = 'view';
            } else {
                $msg = draw_important_message($objBanList->error, false);
                $mode = 'add';
            }
        } else {
            if ($action == 'edit') {
                $mode = 'edit';
            } else {
Esempio n. 9
0
 function create($var, &$errors, $origin, $autorespond = true, $alertstaff = true)
 {
     global $cfg, $thisclient, $_FILES;
     $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');
     if (strcasecmp($origin, 'web') == 0) {
         //Help topic only applicable on web tickets.
         $fields['topicId'] = array('type' => 'int', 'required' => 1, 'error' => 'Select help topic');
     } elseif (strcasecmp($origin, 'staff') == 0) {
         //tickets created by staff...e.g on callins.
         $fields['deptId'] = array('type' => 'int', 'required' => 1, 'error' => 'Dept. required');
         $fields['source'] = array('type' => 'string', 'required' => 1, 'error' => 'Indicate source');
     } else {
         //Incoming emails (PIPE or POP.
         $fields['emailId'] = array('type' => 'int', 'required' => 1, 'error' => 'Email unknown');
     }
     $fields['pri'] = array('type' => 'int', 'required' => 0, 'error' => 'Invalid Priority');
     $fields['phone'] = array('type' => 'phone', 'required' => 0, 'error' => 'Phone # required');
     $validate = new Validator($fields);
     if (!$validate->validate($var)) {
         $errors = array_merge($errors, $validate->errors());
     }
     //Make sure the email is not banned
     if (!$errors && BanList::isbanned($var['email'])) {
         $errors['err'] = 'Ticket denied Error #403';
     }
     if (!$errors && $thisclient && strcasecmp($thisclient->getEmail(), $var['email'])) {
         $errors['email'] = 'Email mismatch.';
     }
     //check attachment..if any is set ...only set on webbased tickets..
     if ($_FILES['attachment']['name'] && $cfg->allowOnlineAttachments()) {
         if (!$cfg->canUploadFileType($_FILES['attachment']['name'])) {
             $errors['attachment'] = 'Invalid file type [ ' . $_FILES['attachment']['name'] . ' ]';
         } elseif ($_FILES['attachment']['size'] > $cfg->getMaxFileSize()) {
             $errors['attachment'] = 'File is too big. Max ' . $cfg->getMaxFileSize() . ' bytes allowed';
         }
     }
     //check ticket limits..if limit set is >0
     //TODO: Base ticket limits on SLA...
     if ($var['email'] && !$errors && $cfg->getMaxOpenTickets() > 0) {
         $openTickets = Ticket::getOpenTicketsByEmail($var['email']);
         if ($openTickets >= $cfg->getMaxOpenTickets()) {
             $errors['err'] = "You've reached the maximum open tickets allowed.";
             //Send the notice only once (when the limit is reached) incase of autoresponders at client end.
             if ($cfg->getMaxOpenTickets() == $openTickets && $cfg->sendOverlimitNotice()) {
                 $sql = 'SELECT ticket_overlimit_subj,ticket_overlimit_body FROM ' . EMAIL_TEMPLATE_TABLE . ' WHERE cfg_id=' . db_input($cfg->getId()) . ' AND tpl_id=' . db_input($cfg->getDefaultTemplateId());
                 $resp = db_query($sql);
                 if (db_num_rows($resp) && (list($subj, $body) = db_fetch_row($resp))) {
                     $body = str_replace("%name", $var['name'], $body);
                     $body = str_replace("%email", $var['email'], $body);
                     $body = str_replace("%url", $cfg->getBaseUrl(), $body);
                     Misc::sendmail($var['email'], $subj, $body, $cfg->getNoReplyEmail());
                 }
             }
             //Alert admin...this might be spammy (no option to disable)...but it is helpful..I think.
             $msg = 'Support ticket request denied for ' . $var['email'] . "\n" . 'Open ticket:' . $openTickets . "\n" . 'Max Allowed:' . $cfg->getMaxOpenTickets() . "\n";
             Misc::alertAdmin('Overlimit Notice', $msg);
         }
     }
     //Any error above is fatal.
     if ($errors) {
         return 0;
     }
     // OK...just do it.
     $deptId = $var['deptId'];
     //pre-selected Dept if any.
     $priorityId = $var['pri'];
     $source = ucfirst($var['source']);
     // Intenal mapping magic...see if we need to overwrite anything
     if (isset($var['topicId']) && !$var['deptId']) {
         //Ticket created via web by user
         if ($var['topicId'] && ($topic = new Topic($var['topicId'])) && $topic->getId()) {
             $deptId = $topic->getDeptId();
             $priorityId = $priorityId ? $priorityId : $topic->getPriorityId();
             $autorespond = $topic->autoRespond();
         }
         $topic = null;
         $source = 'Web';
     } elseif ($var['emailId'] && !$var['deptId']) {
         //Emailed Tickets
         $email = new Email($var['emailId']);
         if ($email && $email->getId()) {
             $deptId = $email->getDeptId();
             $autorespond = $email->autoRespond();
             $priorityId = $priorityId ? $priorityId : $email->getPriorityId();
         }
         $email = null;
         $source = 'Email';
     } elseif ($var['deptId']) {
         //Opened by staff.
         $deptId = $var['deptId'];
         $source = ucfirst($var['source']);
     }
     //Last minute checks
     $priorityId = $priorityId ? $priorityId : $cfg->getDefaultPriorityId();
     $deptId = $deptId ? $deptId : $cfg->getDefaultDeptId();
     $ipaddress = $var['ip'] ? $var['ip'] : $_SERVER['REMOTE_ADDR'];
     //We are ready son...hold on to the rails.
     $extId = Ticket::genExtRandID();
     $sql = 'INSERT INTO ' . TICKET_TABLE . ' SET created=NOW() ' . ',ticketID=' . db_input($extId) . ',dept_id=' . db_input($deptId) . ',priority_id=' . db_input($priorityId) . ',email=' . db_input($var['email']) . ',name=' . db_input(Format::striptags($var['name'])) . ',subject=' . db_input(Format::striptags($var['subject'])) . ',phone=' . db_input($var['phone']) . ',ip_address=' . db_input($ipaddress) . ',source=' . db_input($source);
     //echo $sql;
     $ticket = null;
     //return $ticket;
     if (db_query($sql) && ($id = db_insert_id())) {
         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);
             //TODO: RETHING what happens if this fails?? [At the moment on failure random ID is used...making stuff usable]
         }
         //Load newly created ticket.
         $ticket = new Ticket($id);
         //post the message.
         $msgid = $ticket->postMessage($var['message'], $var['header'], $source, true);
         //TODO: recover from postMessage error??
         //Upload attachments...web based.
         if ($_FILES['attachment']['name'] && $cfg->allowOnlineAttachments() && $msgid) {
             if (!$cfg->allowAttachmentsOnlogin() || $cfg->allowAttachmentsOnlogin() && ($thisclient && $thisclient->isValid())) {
                 $ticket->uploadAttachment($_FILES['attachment'], $msgid, 'M');
                 //TODO: recover from upload issues?
             }
         }
         $dept = $ticket->getDept();
         //SEND OUT NEW TICKET AUTORESP && ALERTS.
         //New Ticket AutoResponse..
         if ($autorespond && $cfg->autoRespONNewTicket() && $dept->autoRespONNewTicket()) {
             $sql = 'SELECT ticket_autoresp_subj,ticket_autoresp_body FROM ' . EMAIL_TEMPLATE_TABLE . ' WHERE cfg_id=' . db_input($cfg->getId()) . ' AND tpl_id=' . db_input($cfg->getDefaultTemplateId());
             $resp = db_query($sql);
             if ($resp && (list($subj, $body) = db_fetch_row($resp))) {
                 $subj = str_replace("%ticket", $ticket->getExtId(), $subj);
                 $body = str_replace("%ticket", $ticket->getExtId(), $body);
                 $body = str_replace("%name", $ticket->getName(), $body);
                 $body = str_replace("%email", $ticket->getEmail(), $body);
                 $body = str_replace("%url", $cfg->getBaseUrl(), $body);
                 $body = str_replace("%signature", $dept ? $dept->getSignature() : '', $body);
                 $email = $from = $fromName = null;
                 if (!$dept->noreplyAutoResp() && ($email = $dept->getEmail())) {
                     $from = $email->getEmail();
                     $fromName = $email->getName();
                     //Reply separator tag.
                     if ($cfg->stripQuotedReply() && ($tag = $cfg->getReplySeparator())) {
                         $body = "\n{$tag}\n\n" . $body;
                     }
                 } else {
                     $from = $cfg->getNoReplyEmail();
                 }
                 Misc::sendmail($ticket->getEmail(), $subj, $body, $from, $fromName);
             }
         }
         //If enabled...send alert to staff (New Ticket Alert)
         if ($alertstaff && $cfg->alertONNewTicket() && is_object($ticket)) {
             $sql = 'SELECT ticket_alert_subj,ticket_alert_body FROM ' . EMAIL_TEMPLATE_TABLE . ' WHERE cfg_id=' . db_input($cfg->getId()) . ' AND tpl_id=' . db_input($cfg->getDefaultTemplateId());
             $resp = db_query($sql);
             if ($resp && (list($subj, $body) = db_fetch_row($resp))) {
                 $body = str_replace("%ticket", $ticket->getExtId(), $body);
                 $body = str_replace("%name", $ticket->getName(), $body);
                 $body = str_replace("%email", $ticket->getEmail(), $body);
                 $body = str_replace("%subject", $ticket->getSubject(), $body);
                 $body = str_replace("%dept", $dept ? $dept->getName() : '', $body);
                 $body = str_replace("%message", $var['message'], $body);
                 $body = str_replace("%url", $cfg->getBaseUrl(), $body);
                 $sentlist = array();
                 //Admin Alert.
                 if ($cfg->alertAdminONNewTicket()) {
                     $alert = str_replace("%staff", 'Admin', $body);
                     Misc::sendmail($cfg->getAdminEmail(), $subj, $alert, $cfg->getAlertEmail());
                     $sentlist[] = $cfg->getAdminEmail();
                 }
                 //get the list
                 $recipients = array();
                 //Dept. Manager
                 if ($cfg->alertDeptManagerONNewTicket()) {
                     $recipients[] = $dept->getManager();
                 }
                 //Staff members
                 if ($cfg->alertDeptMembersONNewTicket()) {
                     $sql = 'SELECT staff_id FROM ' . STAFF_TABLE . ' WHERE onvacation=0 AND dept_id=' . db_input($dept->getId());
                     if (($users = db_query($sql)) && db_num_rows($users)) {
                         while (list($id) = db_fetch_row($users)) {
                             $recipients[] = new Staff($id);
                         }
                     }
                 }
                 //Ok...we are ready to go...baby!
                 foreach ($recipients as $k => $staff) {
                     if (!$staff || !is_object($staff) || !$staff->isAvailable()) {
                         continue;
                     }
                     if (in_array($staff->getEmail(), $sentlist)) {
                         continue;
                     }
                     //avoid duplicate emails.
                     $alert = str_replace("%staff", $staff->getFirstName(), $body);
                     Misc::sendmail($staff->getEmail(), $subj, $alert, $cfg->getAlertEmail());
                     $sentlist[] = $staff->getEmail();
                 }
             }
         }
     }
     return $ticket;
 }