Example #1
0
 function log($priority, $title, $message, $alert = true)
 {
     global $cfg;
     switch ($priority) {
         //We are providing only 3 levels of logs. Windows style.
         case LOG_EMERG:
         case LOG_ALERT:
         case LOG_CRIT:
         case LOG_ERR:
             $level = 1;
             if ($alert) {
                 Sys::alertAdmin($title, $message);
             }
             break;
         case LOG_WARN:
         case LOG_WARNING:
             //Warning...
             $level = 2;
             break;
         case LOG_NOTICE:
         case LOG_INFO:
         case LOG_DEBUG:
         default:
             $level = 3;
             //debug
     }
     //Save log based on system log level settings.
     if ($cfg && $cfg->getLogLevel() >= $level) {
         $loglevel = array(1 => 'Error', 'Warning', 'Debug');
         $sql = 'INSERT INTO ' . SYSLOG_TABLE . ' SET created=NOW(),updated=NOW() ' . ',title=' . db_input($title) . ',log_type=' . db_input($loglevel[$level]) . ',log=' . db_input($message) . ',ip_address=' . db_input($_SERVER['REMOTE_ADDR']);
         //echo $sql;
         mysql_query($sql);
         //don't use db_query to avoid possible loop.
     }
 }
Example #2
0
 function create_by_staff($var, &$errors)
 {
     global $_FILES, $thisuser, $cfg;
     //check if the staff is allowed to create tickets.
     if (!$thisuser || !$thisuser->getId() || !$thisuser->isStaff() || !$thisuser->canCreateTickets()) {
         $errors['err'] = 'Permission denied';
     }
     if (!$var['issue']) {
         $errors['issue'] = 'Summary of the issue required';
     }
     if ($var['source'] && !in_array(strtolower($var['source']), array('email', 'phone', 'other'))) {
         $errors['source'] = 'Invalid source - ' . Format::htmlchars($var['source']);
     }
     $var['emailId'] = 0;
     //clean crap.
     $var['message'] = 'Ticket created by staff';
     if ($ticket = Ticket::create($var, $errors, 'staff', false, !$var['staffId'])) {
         //Staff are alerted only IF the ticket is not being assigned.
         //post issue as a response...
         $msgId = $ticket->getLastMsgId();
         $issue = $ticket->replaceTemplateVars($var['issue']);
         if ($respId = $ticket->postResponse($msgId, $issue, 'none', null, false)) {
             //Note that we're overwriting alerts.
             //Mark the ticket unanswered - postResponse marks it answered which is not the desired state.
             $ticket->markUnAnswered();
             //Send Notice to user --- if requested AND enabled!!
             if ($cfg->notifyONNewStaffTicket() && isset($var['alertuser'])) {
                 $dept = $ticket->getDept();
                 if (!$dept || !($tplId = $dept->getTemplateId())) {
                     $tplId = $cfg->getDefaultTemplateId();
                 }
                 $sql = 'SELECT ticket_notice_subj,ticket_notice_body FROM ' . EMAIL_TEMPLATE_TABLE . ' WHERE cfg_id=' . db_input($cfg->getId()) . ' AND tpl_id=' . db_input($tplId);
                 if (($resp = db_query($sql)) && db_num_rows($resp) && (list($subj, $body) = db_fetch_row($resp))) {
                     $body = $ticket->replaceTemplateVars($body);
                     $subj = $ticket->replaceTemplateVars($subj);
                     $body = str_replace('%message', $var['issue'], $body);
                     //Figure out the signature to use...if any.
                     switch (strtolower($var['signature'])) {
                         case 'mine':
                             $signature = $thisuser->getSignature();
                             break;
                         case 'dept':
                             $signature = $dept && $dept->isPublic() ? $dept->getSignature() : '';
                             //make sure it is public
                             break;
                         case 'none':
                         default:
                             $signature = '';
                             break;
                     }
                     $body = str_replace("%signature", $signature, $body);
                     //Email attachment when attached AND if emailed attachments are allowed!
                     $file = null;
                     $attachment = $_FILES['attachment'];
                     if ($attachment && is_file($attachment['tmp_name']) && $cfg->emailAttachments()) {
                         $file = array('file' => $attachment['tmp_name'], 'name' => $attachment['name'], 'type' => $attachment['type']);
                     }
                     if ($cfg->stripQuotedReply() && ($tag = trim($cfg->getReplySeparator()))) {
                         $body = "\n{$tag}\n\n" . $body;
                     }
                     if (!$dept || !($email = $dept->getEmail())) {
                         $email = $cfg->getDefaultEmail();
                     }
                     if ($email && $email->getId()) {
                         $email->send($ticket->getEmail(), $subj, $body, $file);
                     }
                 } else {
                     //We have a big problem...alert admin...
                     $msg = 'Problems fetching response template for ticket#' . $ticket->getId() . ' Possible config error - template #' . $tplId;
                     Sys::alertAdmin('System Error', $msg);
                 }
             }
             //Send send alert.
             //Upload attachment if any...
             if ($_FILES['attachment'] && $_FILES['attachment']['size']) {
                 $ticket->uploadAttachment($_FILES['attachment'], $respId, 'R');
             }
         } else {
             //end post response
             $errors['err'] = 'Internal error - message/response post error.';
         }
         //post create actions
         if ($var['staffId']) {
             //Assign ticket to staff if any. (internal note as message)
             $ticket->assignStaff($var['staffId'], $var['note'], isset($var['alertstaff']));
         } elseif ($var['note']) {
             //Not assigned...save optional note if any
             $ticket->postNote('New Ticket', $var['note'], false);
         } else {
             //Not assignment and no internal note - log activity
             $ticket->logActivity('New Ticket by Staff', 'Ticket created by staff -' . $thisuser->getName());
         }
     } else {
         $errors['err'] = $errors['err'] ? $errors['err'] : 'Unable to create the ticket. Correct the error(s) and try again';
     }
     return $ticket;
 }
Example #3
0
 function onOpenLimit($sendNotice = true)
 {
     global $cfg;
     //Log the limit notice as a warning for admin.
     $msg = sprintf('Max open tickets (%d) reached  for %s ', $cfg->getMaxOpenTickets(), $this->getEmail());
     sys::log(LOG_WARNING, 'Max. Open Tickets Limit (' . $this->getEmail() . ')', $msg);
     if (!$sendNotice || !$cfg->sendOverlimitNotice()) {
         return true;
     }
     //Send notice to user.
     $dept = $this->getDept();
     if (!$dept || !($tpl = $dept->getTemplate())) {
         $tpl = $cfg->getDefaultTemplate();
     }
     if (!$dept || !($email = $dept->getAutoRespEmail())) {
         $email = $cfg->getDefaultEmail();
     }
     if ($tpl && ($msg = $tpl->getOverlimitMsgTemplate()) && $email) {
         $body = $this->replaceTemplateVars($msg['body']);
         $subj = $this->replaceTemplateVars($msg['subj']);
         $body = str_replace('%signature', $dept && $dept->isPublic() ? $dept->getSignature() : '', $body);
         $email->send($this->getEmail(), $subj, $body);
     }
     $client = $this->getClient();
     //Alert admin...this might be spammy (no option to disable)...but it is helpful..I think.
     $msg = 'Max. open tickets reached for ' . $this->getEmail() . "\n" . 'Open ticket: ' . $client->getNumOpenTickets() . "\n" . 'Max Allowed: ' . $cfg->getMaxOpenTickets() . "\n\nNotice sent to the user.";
     Sys::alertAdmin('Overlimit Notice', $msg);
     return true;
 }
Example #4
0
    function fetchMail(){
        global $cfg;
      
        if(!$cfg->canFetchMail())
            return;

        //We require imap ext to fetch emails via IMAP/POP3
        if(!function_exists('imap_open')) {
            $msg='PHP must be compiled with IMAP extension enabled for IMAP/POP3 fetch to work!';
            Sys::log(LOG_WARN,'Mail Fetch Error',$msg);
            return;
        }

        $MAX_ERRORS=5; //Max errors before we start delayed fetch attempts - hardcoded for now.

        $sql=' SELECT email_id,mail_host,mail_port,mail_protocol,mail_encryption,mail_delete,mail_errors,userid,userpass FROM '.EMAIL_TABLE.
             ' WHERE mail_active=1 AND (mail_errors<='.$MAX_ERRORS.' OR (TIME_TO_SEC(TIMEDIFF(NOW(),mail_lasterror))>5*60) )'.
             ' AND (mail_lastfetch IS NULL OR TIME_TO_SEC(TIMEDIFF(NOW(),mail_lastfetch))>mail_fetchfreq*60) ';
        //echo $sql;
        if(!($accounts=db_query($sql)) || !db_num_rows($accounts))
            return;

        //TODO: Lock the table here??
        while($row=db_fetch_array($accounts)) {
            $fetcher = new MailFetcher($row['userid'],Misc::decrypt($row['userpass'],SECRET_SALT),
                                       $row['mail_host'],$row['mail_port'],$row['mail_protocol'],$row['mail_encryption']);
            if($fetcher->connect()){   
                $fetcher->fetchTickets($row['email_id'],$row['mail_fetchmax'],$row['mail_delete']?true:false);
                $fetcher->close();
                db_query('UPDATE '.EMAIL_TABLE.' SET mail_errors=0, mail_lastfetch=NOW() WHERE email_id='.db_input($row['email_id']));
            }else{
                $errors=$row['mail_errors']+1;
                db_query('UPDATE '.EMAIL_TABLE.' SET mail_errors=mail_errors+1, mail_lasterror=NOW() WHERE email_id='.db_input($row['email_id']));
                if($errors>=$MAX_ERRORS){
                    //We've reached the MAX consecutive errors...will attempt logins at delayed intervals
                    $msg="\nThe system is having trouble fetching emails from the following mail account: \n".
                        "\nUser: "******"\nHost: ".$row['mail_host'].
                        "\nError: ".$fetcher->getLastError().
                        "\n\n ".$errors.' consecutive errors. Maximum of '.$MAX_ERRORS. ' allowed'.
                        "\n\n This could be connection issues related to the host. Next delayed login attempt in aprox. 10 minutes";
                    Sys::alertAdmin('Mail Fetch Failure Alert',$msg,true);
                }
            }
        }
    }
Example #5
0
    define('BANLIST_TABLE',TABLE_PREFIX.'email_banlist');
    define('API_KEY_TABLE',TABLE_PREFIX.'api_key');
    define('TIMEZONE_TABLE',TABLE_PREFIX.'timezone'); 
   
    #Connect to the DB && get configuration from database
    $ferror=null;
    if (!db_connect(DBHOST,DBUSER,DBPASS) || !db_select_database(DBNAME)) {
        $ferror='Unable to connect to the database';
    }elseif(!($cfg=Sys::getConfig())){
        $ferror='Unable to load config info from DB. Get tech support.';
    }elseif(!ini_get('short_open_tag')) {
        $ferror='Short open tag disabled! - osTicket requires it turned ON.';
    }

    if($ferror){ //Fatal error
        Sys::alertAdmin('osTicket Fatal Error',$ferror); //try alerting admin.
        die("<b>Fatal Error:</b> Contact system adminstrator."); //Generic error.
        exit;
    }
    //Init
    $cfg->init();
    //Set default timezone...staff will overwrite it.
    $_SESSION['TZ_OFFSET']=$cfg->getTZoffset();
    $_SESSION['daylight']=$cfg->observeDaylightSaving();

    #Cleanup magic quotes crap.
    if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) {
        $_POST=Format::strip_slashes($_POST);
        $_GET=Format::strip_slashes($_GET);
        $_REQUEST=Format::strip_slashes($_REQUEST);
    }
Example #6
0
define('API_KEY_TABLE', TABLE_PREFIX . 'api_key');
define('TIMEZONE_TABLE', TABLE_PREFIX . 'timezone');
/*
 * this line not can translated, because the translate object need acess 
 * config object and use the database information.
 */
#Connect to the DB && get configuration from database
$ferror = null;
if (!db_connect(DBHOST, DBUSER, DBPASS) || !db_select_database(DBNAME)) {
    $ferror = 'Unable to connect to the database';
} elseif (!($cfg = Sys::getConfig())) {
    $ferror = 'Unable to load config info from DB. Get tech support.';
}
if ($ferror) {
    //Fatal error
    Sys::alertAdmin('osTicket Fatal Error', $ferror);
    //try alerting admin.
    die("<b>Fatal Error:</b> Contact system adminstrator.");
    //Generic error.
    exit;
}
//Init
$cfg->init();
//Set default timezone...staff will overwrite it.
$_SESSION['TZ_OFFSET'] = $cfg->getTZoffset();
$_SESSION['daylight'] = $cfg->observeDaylightSaving();
#Cleanup magic quotes crap.
if (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) {
    $_POST = Format::strip_slashes($_POST);
    $_GET = Format::strip_slashes($_GET);
    $_REQUEST = Format::strip_slashes($_REQUEST);
define('EMAIL_TEMPLATE_TABLE', TABLE_PREFIX . 'email_template');
define('BANLIST_TABLE', TABLE_PREFIX . 'email_banlist');
define('API_KEY_TABLE', TABLE_PREFIX . 'api_key');
define('TIMEZONE_TABLE', TABLE_PREFIX . 'timezone');
#Connect to the DB && get configuration from database
$ferror = null;
if (!db_connect(DBHOST, DBUSER, DBPASS) || !db_select_database(DBNAME)) {
    $ferror = 'Não foi possível conectar ao banco de dados.';
} elseif (!($cfg = Sys::getConfig())) {
    $ferror = 'Não foi possível carregar as informações de configuração do banco de dados. Obtenha suporte técnico.';
} elseif (!ini_get('short_open_tag')) {
    $ferror = 'Abertura de tag curta desativada! - osTicket necessita dela ligada.';
}
if ($ferror) {
    //Fatal error
    Sys::alertAdmin('osTicket Erro Fatal', $ferror);
    //try alerting admin.
    die("<b>Erro Fatal:</b> Contate o administrador do sistema.");
    //Generic error.
    exit;
}
//Init
$cfg->init();
//Set default timezone...staff will overwrite it.
$_SESSION['TZ_OFFSET'] = $cfg->getTZoffset();
$_SESSION['daylight'] = $cfg->observeDaylightSaving();
#Cleanup magic quotes crap.
if (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) {
    $_POST = Format::strip_slashes($_POST);
    $_GET = Format::strip_slashes($_GET);
    $_REQUEST = Format::strip_slashes($_REQUEST);
 function fetchMail()
 {
     global $cfg;
     if (!$cfg->canFetchMail()) {
         return;
     }
     //We require imap ext to fetch emails via IMAP/POP3
     if (!function_exists('imap_open')) {
         $msg = 'PHP deve ser compilado com extensão IMAP habilitado para buscar a trabalhar IMAP/POP3!';
         Sys::log(LOG_WARN, 'Erro em buscar o email', $msg);
         return;
     }
     $MAX_ERRORS = 5;
     //Max errors before we start delayed fetch attempts - hardcoded for now.
     $sql = ' SELECT email_id,mail_host,mail_port,mail_protocol,mail_encryption,mail_delete,mail_errors,userid,userpass FROM ' . EMAIL_TABLE . ' WHERE mail_active=1 AND (mail_errors<=' . $MAX_ERRORS . ' OR (TIME_TO_SEC(TIMEDIFF(NOW(),mail_lasterror))>5*60) )' . ' AND (mail_lastfetch IS NULL OR TIME_TO_SEC(TIMEDIFF(NOW(),mail_lastfetch))>mail_fetchfreq*60) ';
     //echo $sql;
     if (!($accounts = db_query($sql)) || !db_num_rows($accounts)) {
         return;
     }
     //TODO: Lock the table here??
     while ($row = db_fetch_array($accounts)) {
         $fetcher = new MailFetcher($row['userid'], Misc::decrypt($row['userpass'], SECRET_SALT), $row['mail_host'], $row['mail_port'], $row['mail_protocol'], $row['mail_encryption']);
         if ($fetcher->connect()) {
             $fetcher->fetchTickets($row['email_id'], $row['mail_fetchmax'], $row['mail_delete'] ? true : false);
             $fetcher->close();
             db_query('UPDATE ' . EMAIL_TABLE . ' SET mail_errors=0, mail_lastfetch=NOW() WHERE email_id=' . db_input($row['email_id']));
         } else {
             $errors = $row['mail_errors'] + 1;
             db_query('UPDATE ' . EMAIL_TABLE . ' SET mail_errors=mail_errors+1, mail_lasterror=NOW() WHERE email_id=' . db_input($row['email_id']));
             if ($errors >= $MAX_ERRORS) {
                 //We've reached the MAX consecutive errors...will attempt logins at delayed intervals
                 $msg = "\nO sistema está tendo problemas para coletar e-mails da conta do e-mail seguinte: \n" . "\nUsuário: " . $row['userid'] . "\nHost: " . $row['mail_host'] . "\nErro: " . $fetcher->getLastError() . "\n\n " . $errors . ' erros consecutivos. Máximo de ' . $MAX_ERRORS . ' permitido' . "\n\n Isso pode ser problemas de conexão relacionados ao hospedeiro. Próxima tentativa de login em aprox. 10 minutos";
                 Sys::alertAdmin('Alerta de falha na busca por email', $msg, true);
             }
         }
     }
 }
define('BANLIST_TABLE', TABLE_PREFIX . 'email_banlist');
define('API_KEY_TABLE', TABLE_PREFIX . 'api_key');
define('TIMEZONE_TABLE', TABLE_PREFIX . 'timezone');
#Connect to the DB && get configuration from database
$ferror = null;
if (!db_connect(DBHOST, DBUSER, DBPASS, DBNAME)) {
    $ferror = 'Unable to connect to the database';
} elseif (!($cfg = Sys::getConfig())) {
    $ferror = 'Unable to load config info from DB.';
} elseif (!ini_get('short_open_tag') && (double) phpversion() < 5.4) {
    // PHP ver. < 5.4 requires short_open_tag enabled
    $ferror = 'Short open tag disabled! - Katak-support requires it is turned ON.';
}
if ($ferror) {
    //Fatal error
    Sys::alertAdmin('Katak-support fatal error', 'Server ' . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'] . ': ' . $ferror);
    //try alerting sysadmin.
    die("<br /><b>Fatal error!</b> Contact system adminstrator.");
    //Generic error message.
    exit;
}
//Init
$cfg->init();
//Set default timezone and store it in the session array...staff will overwrite it.
$_SESSION['TZ_OFFSET'] = $cfg->getTZoffset();
$_SESSION['daylight'] = $cfg->observeDaylightSaving();
#Cleanup magic quotes crap.
if (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) {
    $_POST = Format::strip_slashes($_POST);
    $_GET = Format::strip_slashes($_GET);
    $_REQUEST = Format::strip_slashes($_REQUEST);
 function fetchMail()
 {
     global $cfg;
     if (!$cfg->canFetchMail()) {
         return;
     }
     //We require imap ext to fetch emails via IMAP/POP3
     if (!function_exists('imap_open')) {
         $msg = 'PHP debe ser compilado con la extensi&oacute;n IMAP habilitada para IMAP/POP3 fetch(captura de correo) para que funcione';
         Sys::log(LOG_WARN, 'Error de captura de correo', $msg);
         return;
     }
     $MAX_ERRORS = 5;
     //Max errors before we start delayed fetch attempts - hardcoded for now.
     $sql = ' SELECT email_id,mail_host,mail_port,mail_protocol,mail_encryption,mail_delete,mail_errors,userid,userpass FROM ' . EMAIL_TABLE . ' WHERE mail_active=1 AND (mail_errors<=' . $MAX_ERRORS . ' OR (TIME_TO_SEC(TIMEDIFF(NOW(),mail_lasterror))>5*60) )' . ' AND (mail_lastfetch IS NULL OR TIME_TO_SEC(TIMEDIFF(NOW(),mail_lastfetch))>mail_fetchfreq*60) ';
     //echo $sql;
     if (!($accounts = db_query($sql)) || !db_num_rows($accounts)) {
         return;
     }
     //TODO: Lock the table here??
     while ($row = db_fetch_array($accounts)) {
         $fetcher = new MailFetcher($row['userid'], Misc::decrypt($row['userpass'], SECRET_SALT), $row['mail_host'], $row['mail_port'], $row['mail_protocol'], $row['mail_encryption']);
         if ($fetcher->connect()) {
             $fetcher->fetchTickets($row['email_id'], $row['mail_fetchmax'], $row['mail_delete'] ? true : false);
             $fetcher->close();
             db_query('UPDATE ' . EMAIL_TABLE . ' SET mail_errors=0, mail_lastfetch=NOW() WHERE email_id=' . db_input($row['email_id']));
         } else {
             $errors = $row['mail_errors'] + 1;
             db_query('UPDATE ' . EMAIL_TABLE . ' SET mail_errors=mail_errors+1, mail_lasterror=NOW() WHERE email_id=' . db_input($row['email_id']));
             if ($errors >= $MAX_ERRORS) {
                 //We've reached the MAX consecutive errors...will attempt logins at delayed intervals
                 $msg = "\nEl sistema est&aacute; teniendo problemas para obtener los correos electr&oacute;nicos de la cuenta de correo siguiente: \n" . "\nUsuario: " . $row['userid'] . "\nHost: " . $row['mail_host'] . "\nError: " . $fetcher->getLastError() . "\n\n " . $errors . ' errores consecutivos. M&aacute;ximo de ' . $MAX_ERRORS . ' permitidos' . "\n\n Esto podría ser una cuesti&oacute;n relacionada con la conexi&oacute;n al host. Siguiente intento en aprox. 10 min";
                 Sys::alertAdmin('Alerta de fallo en la captura de correo', $msg, true);
             }
         }
     }
 }