Exemple #1
1
 /**
  * @return resource
  * @throws MailboxException
  */
 protected function initImapStream()
 {
     imap_timeout(IMAP_OPENTIMEOUT, 15);
     $imapStream = @imap_open($this->imapFullPath, $this->settings['user'], $this->settings['password'], $this->imapOptions, $this->imapRetriesNum, $this->imapParams);
     if (!$imapStream) {
         throw new MailboxException();
     }
     return $imapStream;
 }
Exemple #2
0
 /**
  * Opens an IMAP stream
  */
 public function __construct()
 {
     // Set Imap Timeouts
     imap_timeout(IMAP_OPENTIMEOUT, 90);
     imap_timeout(IMAP_READTIMEOUT, 90);
     // If SSL Enabled
     $ssl = Kohana::config('settings.email_ssl') == true ? "/ssl" : "";
     // Do not validate certificates (TLS/SSL server)
     //$novalidate = strtolower(Kohana::config('settings.email_servertype')) == "imap" ? "/novalidate-cert" : "";
     $novalidate = "/novalidate-cert";
     // If POP3 Disable TLS
     $notls = strtolower(Kohana::config('settings.email_servertype')) == "pop3" ? "/notls" : "";
     /*
     More Info about above options at:
     http://php.net/manual/en/function.imap-open.php
     */
     $service = "{" . Kohana::config('settings.email_host') . ":" . Kohana::config('settings.email_port') . "/" . Kohana::config('settings.email_servertype') . $notls . $ssl . $novalidate . "}";
     // Check if the host name is valid, if not, set imap_stream as false and return false
     if (count(dns_get_record("" . Kohana::config('settings.email_host') . "")) == 0) {
         $this->imap_stream = false;
         return false;
     }
     if ($imap_stream = @imap_open($service, Kohana::config('settings.email_username'), Kohana::config('settings.email_password'))) {
         $this->imap_stream = $imap_stream;
     } else {
         // We don't usually want to break the entire scheduler process if email settings are off
         //   so lets return false instead of halting the entire script with a Kohana Exception.
         $this->imap_stream = false;
         return false;
         //throw new Kohana_Exception('imap.imap_stream_not_opened', $throwing_error);
     }
 }
Exemple #3
0
 public function open()
 {
     $this->baseMailbox = '{' . $this->host . ':' . $this->port . '/' . $this->type;
     if (in_array($this->security, ['ssl', 'tls'])) {
         $this->baseMailbox .= '/' . $this->security;
     }
     if ($this->validateCertificate !== null) {
         if ($this->validateCertificate) {
             $this->baseMailbox .= '/validate-cert';
         } else {
             $this->baseMailbox .= '/novalidate-cert';
         }
     }
     $this->baseMailbox .= '}INBOX';
     imap_timeout(IMAP_OPENTIMEOUT, 3);
     imap_timeout(IMAP_READTIMEOUT, 3);
     imap_timeout(IMAP_WRITETIMEOUT, 3);
     imap_timeout(IMAP_CLOSETIMEOUT, 3);
     ini_set('default_socket_timeout', 3);
     //error_reporting(0);
     $this->connection = imap_open($this->baseMailbox, $this->username, $this->password, 0, 1);
     /*if(! $this->connection)
       {
           var_dump($this->baseMailbox);
       }*/
     //error_reporting(-1);
     return !$this->connection;
 }
Exemple #4
0
function imap_test_connect($host,$user,$pass,$timeout=-1,$protocol="imap",$port=-1,$ssl=false,$debug=false)
{
global $NATS;
if ($timeout>0) $timeout=$timeout; // use specific for test if set
else
	{
	// otherwise use system if available
	if (isset($NATS)) $timeout=$NATS->Cfg->Get("test.imap.timeout",0);
	if ($timeout<=0) $timeout=0; // unset specifically or in environment
	}
	
if ($timeout>0) imap_timeout(IMAP_OPENTIMEOUT,$timeout);

if ($port<=0)
	{
	$port=143; // default
	if ( ($protocol=="imap") && ($ssl) ) $port=993;
	else if ($protocol=="pop3")
		{
		if ($ssl) $port=995;
		else $port=110;
		}
	}

$mailbox="{".$host.":".$port."/service=".$protocol;
if ($ssl) $mailbox.="/ssl";
$mailbox.="/novalidate-cert";
$mailbox.="}INBOX";
if ($debug) echo $user.":".$pass."@".$mailbox."\n";
$imap=@imap_open($mailbox,$user,$pass);
if ($imap===false) return 0;

@imap_close($imap);
return 1;
}
 /**
  * @param Mirasvit_Helpdesk_Model_Gateway $gateway
  *
  * @return bool
  */
 public function connect($gateway)
 {
     $this->gateway = $gateway;
     $flags = sprintf('/%s', $gateway->getProtocol());
     if ($gateway->getEncryption() == 'ssl') {
         $flags .= '/ssl';
     }
     $flags .= '/novalidate-cert';
     // echo $flags;die;
     $server = new Mirasvit_Ddeboer_Imap_Server($gateway->getHost(), $gateway->getPort(), $flags);
     if (function_exists('imap_timeout')) {
         imap_timeout(1, 20);
     }
     if (!($this->connection = $server->authenticate($gateway->getLogin(), $gateway->getPassword()))) {
         return false;
     }
     $mailboxes = $this->connection->getMailboxNames();
     if (in_array('INBOX', $mailboxes)) {
         $mailboxName = 'INBOX';
     } elseif (in_array('Inbox', $mailboxes)) {
         $mailboxName = 'Inbox';
     } else {
         $mailboxName = $mailboxes[0];
     }
     $this->mailbox = $this->connection->getMailbox($mailboxName);
     return true;
 }
Exemple #6
0
    function MailFetcher($username,$password,$hostname,$port,$protocol,$encryption='') {

        if(!strcasecmp($protocol,'pop')) //force pop3
            $protocol='pop3';

        $this->hostname=$hostname;
        $this->username=$username;
        $this->password=$password;
        $this->protocol=strtolower($protocol);
        $this->port = $port;
        $this->encryption = $encryption;

        $this->serverstr=sprintf('{%s:%d/%s',$this->hostname,$this->port,strtolower($this->protocol));
        if(!strcasecmp($this->encryption,'SSL')){
            $this->serverstr.='/ssl';
        }
        $this->serverstr.='/novalidate-cert}INBOX'; //add other flags here as needed.

        //echo $this->serverstr;
        //Charset to convert the mail to.
        $this->charset='UTF-8';
        //Set timeouts 
        if(function_exists('imap_timeout'))
            imap_timeout(1,20); //Open timeout.
    }
 /**
  * Primary method for downloading and processing email replies
  */
 public function download_and_process_email_replies($connection_details)
 {
     imap_timeout(IMAP_OPENTIMEOUT, apply_filters('supportflow_imap_open_timeout', 5));
     $ssl = $connection_details['imap_ssl'] ? '/ssl' : '';
     $ssl = apply_filters('supportflow_imap_ssl', $ssl, $connection_details['imap_host']);
     $mailbox = "{{$connection_details['imap_host']}:{$connection_details['imap_port']}{$ssl}}";
     $inbox = "{$mailbox}{$connection_details['inbox']}";
     $archive_box = "{$mailbox}{$connection_details['archive']}";
     $imap_connection = imap_open($mailbox, $connection_details['username'], $connection_details['password']);
     $redacted_connection_details = $connection_details;
     $redacted_connection_details['password'] = '******';
     // redact the password to avoid unnecessarily exposing it in logs
     $imap_errors = imap_errors();
     SupportFlow()->extend->logger->log('email_retrieve', __METHOD__, $imap_connection ? __('Successfully opened IMAP connection.', 'supportflow') : __('Failed to open IMAP connection.', 'supportflow'), compact('redacted_connection_details', 'mailbox', 'imap_errors'));
     if (!$imap_connection) {
         return new WP_Error('connection-error', __('Error connecting to mailbox', 'supportflow'));
     }
     // Check to see if the archive mailbox exists, and create it if it doesn't
     $mailboxes = imap_getmailboxes($imap_connection, $mailbox, '*');
     if (!wp_filter_object_list($mailboxes, array('name' => $archive_box))) {
         imap_createmailbox($imap_connection, $archive_box);
     }
     // Make sure here are new emails to process
     $email_count = imap_num_msg($imap_connection);
     if ($email_count < 1) {
         SupportFlow()->extend->logger->log('email_retrieve', __METHOD__, __('No new messages to process.', 'supportflow'), compact('mailboxes'));
         return false;
     }
     $emails = imap_search($imap_connection, 'ALL', SE_UID);
     $email_count = min($email_count, apply_filters('supportflow_max_email_process_count', 20));
     $emails = array_slice($emails, 0, $email_count);
     $processed = 0;
     // Process each new email and put it in the archive mailbox when done.
     foreach ($emails as $uid) {
         $email = new stdClass();
         $email->uid = $uid;
         $email->msgno = imap_msgno($imap_connection, $email->uid);
         $email->headers = imap_headerinfo($imap_connection, $email->msgno);
         $email->structure = imap_fetchstructure($imap_connection, $email->msgno);
         $email->body = $this->get_body_from_connection($imap_connection, $email->msgno);
         if (0 === strcasecmp($connection_details['username'], $email->headers->from[0]->mailbox . '@' . $email->headers->from[0]->host)) {
             $connection_details['password'] = '******';
             // redact the password to avoid unnecessarily exposing it in logs
             SupportFlow()->extend->logger->log('email_retrieve', __METHOD__, __('Skipping message because it was sent from a SupportFlow account.', 'supportflow'), compact('email'));
             continue;
         }
         // @todo Confirm this a message we want to process
         $result = $this->process_email($imap_connection, $email, $email->msgno, $connection_details['username'], $connection_details['account_id']);
         // If it was successful, move the email to the archive
         if ($result) {
             imap_mail_move($imap_connection, $email->uid, $connection_details['archive'], CP_UID);
             $processed++;
         }
     }
     imap_close($imap_connection, CL_EXPUNGE);
     $status_message = sprintf(__('Processed %d emails', 'supportflow'), $processed);
     SupportFlow()->extend->logger->log('email_retrieve', __METHOD__, $status_message);
     return $status_message;
 }
Exemple #8
0
 public function __construct($mailbox, $username, $password, $timeout = 30)
 {
     imap_timeout(IMAP_OPENTIMEOUT, $timeout);
     imap_timeout(IMAP_READTIMEOUT, $timeout);
     imap_timeout(IMAP_WRITETIMEOUT, $timeout);
     try {
         $this->count = imap_num_msg($this->imap = imap_open(\Zeyon\convert($mailbox, 'UTF7-IMAP'), \Zeyon\convert($username, 'UTF7-IMAP'), \Zeyon\convert($password, 'UTF7-IMAP'), OP_SILENT, 1));
     } catch (\Exception $e) {
         throw new \Exception('IMAP: ' . (($error = imap_last_error()) === false ? $e->getMessage() : $error));
     }
 }
Exemple #9
0
 /**
  * Opens an IMAP stream
  */
 public function __construct()
 {
     // Set Imap Timeouts
     imap_timeout(IMAP_OPENTIMEOUT, 90);
     imap_timeout(IMAP_READTIMEOUT, 90);
     $ssl = Kohana::config('settings.email_ssl') == true ? "ssl/novalidate-cert" : "";
     $service = "{" . Kohana::config('settings.email_host') . ":" . Kohana::config('settings.email_port') . "/" . Kohana::config('settings.email_servertype') . "/" . $ssl . "}";
     $imap_stream = imap_open($service, Kohana::config('settings.email_username'), Kohana::config('settings.email_password'));
     if (!$imap_stream) {
         throw new Kohana_Exception('imap.imap_stream_not_opened', imap_last_error());
     }
     $this->imap_stream = $imap_stream;
 }
Exemple #10
0
 /**
  * Opens an IMAP stream
  */
 public function __construct()
 {
     // Set Imap Timeouts
     imap_timeout(IMAP_OPENTIMEOUT, 90);
     imap_timeout(IMAP_READTIMEOUT, 90);
     $config = Kohana::config('email');
     $ssl = $config['ssl'] == true ? "ssl/novalidate-cert" : "";
     $service = "{" . $config['server'] . ":" . $config['port'] . "/" . $config['servertype'] . "/" . $ssl . "}";
     $imap_stream = imap_open($service, $config['username'], $config['password']);
     if (!$imap_stream) {
         throw new Kohana_Exception('imap.imap_stream_not_opened', imap_last_error());
     }
     $this->imap_stream = $imap_stream;
 }
Exemple #11
0
 /**
  * constructor
  *
  * @param CSourcePOP $source Source POP
  */
 function __construct($source)
 {
     //stock the source
     $this->source = $source;
     if (!function_exists("imap_open")) {
         CModelObject::error("FE-IMAP-support-not-available");
     }
     //initialise open TIMEOUT
     imap_timeout(1, $this->source->timeout);
     //lets create the string for stream
     $type = $this->source->type == "pop3" ? "/" . $this->source->type : "";
     $ssl = $this->source->auth_ssl == "SSL/TLS" ? "/ssl/novalidate-cert" : "/notls";
     $port = $this->source->port ? ":" . $this->source->port : "";
     $extension = $this->source->extension ? $this->source->extension : "";
     return $this->_server = "{" . $this->source->host . $port . $type . $ssl . "}" . $extension;
 }
Exemple #12
0
 function connect()
 {
     ob_start();
     $buff = imap_alerts();
     $buff = imap_errors();
     $timeout = $this->config->get('bounce_timeout');
     if (!empty($timeout)) {
         imap_timeout(IMAP_OPENTIMEOUT, $timeout);
     }
     $port = $this->config->get('bounce_port', '');
     $secure = $this->config->get('bounce_secured', '');
     $protocol = $this->config->get('bounce_connection', '');
     $serverName = '{' . $this->config->get('bounce_server');
     if (empty($port)) {
         if ($secure == 'ssl' && $protocol == 'imap') {
             $port = '993';
         } elseif ($protocol == 'imap') {
             $port = '143';
         } elseif ($protocol == 'pop3') {
             $port = '110';
         }
     }
     if (!empty($port)) {
         $serverName .= ':' . $port;
     }
     if (!empty($secure)) {
         $serverName .= '/' . $secure;
     }
     if ($this->config->get('bounce_certif', false)) {
         $serverName .= '/novalidate-cert';
     }
     if (!empty($protocol)) {
         $serverName .= '/service=' . $protocol;
     }
     $serverName .= '}';
     $this->mailbox = imap_open($serverName, $this->config->get('bounce_username'), $this->config->get('bounce_password'));
     $warnings = ob_get_clean();
     if (!empty($warnings) && $this->report) {
         acymailing::display($warnings, 'warning');
     }
     return $this->mailbox ? true : false;
 }
 function MailFetcher($email, $charset = 'UTF-8')
 {
     if ($email && is_numeric($email)) {
         //email_id
         $email = Email::lookup($email);
     }
     if (is_object($email)) {
         $this->ht = $email->getMailAccountInfo();
     } elseif (is_array($email) && $email['host']) {
         //hashtable of mail account info
         $this->ht = $email;
     } else {
         $this->ht = null;
     }
     $this->charset = $charset;
     if ($this->ht) {
         if (!strcasecmp($this->ht['protocol'], 'pop')) {
             //force pop3
             $this->ht['protocol'] = 'pop3';
         } else {
             $this->ht['protocol'] = strtolower($this->ht['protocol']);
         }
         //Max fetch per poll
         if (!$this->ht['max_fetch'] || !is_numeric($this->ht['max_fetch'])) {
             $this->ht['max_fetch'] = 20;
         }
         //Mail server string
         $this->srvstr = sprintf('{%s:%d/%s', $this->getHost(), $this->getPort(), $this->getProtocol());
         if (!strcasecmp($this->getEncryption(), 'SSL')) {
             $this->srvstr .= '/ssl';
         }
         $this->srvstr .= '/novalidate-cert}';
     }
     //Set timeouts
     if (function_exists('imap_timeout')) {
         imap_timeout(1, 20);
     }
 }
Exemple #14
0
 /**
  * Opens an IMAP stream
  */
 public function __construct()
 {
     // Set Imap Timeouts
     imap_timeout(IMAP_OPENTIMEOUT, 90);
     imap_timeout(IMAP_READTIMEOUT, 90);
     // If SSL Enabled
     $ssl = Kohana::config('settings.email_ssl') == true ? "/ssl" : "";
     // Do not validate certificates (TLS/SSL server)
     //$novalidate = strtolower(Kohana::config('settings.email_servertype')) == "imap" ? "/novalidate-cert" : "";
     $novalidate = "/novalidate-cert";
     // If POP3 Disable TLS
     $notls = strtolower(Kohana::config('settings.email_servertype')) == "pop3" ? "/notls" : "";
     /*
     More Info about above options at:
     http://php.net/manual/en/function.imap-open.php
     */
     $service = "{" . Kohana::config('settings.email_host') . ":" . Kohana::config('settings.email_port') . "/" . Kohana::config('settings.email_servertype') . $notls . $ssl . $novalidate . "}";
     $imap_stream = imap_open($service, Kohana::config('settings.email_username'), Kohana::config('settings.email_password'));
     if (!$imap_stream) {
         throw new Kohana_Exception('imap.imap_stream_not_opened', imap_last_error());
     }
     $this->imap_stream = $imap_stream;
 }
Exemple #15
0
$download_data = explode("::", base64_decode($_POST["download_data"]));
$download_dir = $_POST["download_dir"];
//print_r($download_data);
$mbox_name = $download_data[0];
$use_ssl = $download_data[1];
$validate_cert = $download_data[2];
$username = $download_data[3];
$password = $download_data[4];
$use_tls = $download_data[5];
$folder = $download_data[6];
$msg_number = (int) $download_data[7];
$attachment_name = $download_data[8];
imap_timeout(15, IMAP_OPENTIMEOUT);
imap_timeout(15, IMAP_READTIMEOUT);
imap_timeout(15, IMAP_WRITETIMEOUT);
imap_timeout(15, IMAP_CLOSETIMEOUT);
$use_ssl_flag = $use_ssl == "true" ? "/ssl" : "";
$validate_cert_flag = $validate_cert == "true" ? "" : "/novalidate-cert";
$use_tls_flag = $use_tls == "true" ? "/tls" : "";
$mbox = imap_open("{" . $mbox_name . $use_ssl_flag . $validate_cert_flag . $use_tls_flag . "}{$folder}", $username, $password);
//print_r(imap_errors());
$message = new MailMessage($mbox, $msg_number);
//print_r($message);
$attachments = $message->getAttachments();
//print_r($attachments);
$download_data = null;
if ($attachment_name == '*') {
    if (class_exists("ZipArchive")) {
        $attachment_name = "{$download_dir}/attachments-{$msg_number}.zip";
        $zip = new ZipArchive();
        $zip->open($attachment_name, ZipArchive::CREATE);
Exemple #16
0
 public static function imap_connect($user, $password, $folder = 'INBOX')
 {
     global $log;
     $log->debug("Entering OSSMail_Record_Model::imap_connect({$user} , {$password} , {$folder}) method ...");
     $roundcube_config = self::load_roundcube_config();
     $a_host = parse_url($roundcube_config['default_host']);
     $validatecert = '';
     if ($a_host['host']) {
         $host = $a_host['host'];
         $ssl_mode = isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl', 'imaps', 'tls')) ? $a_host['scheme'] : null;
         if (!empty($a_host['port'])) {
             $port = $a_host['port'];
         } else {
             if ($ssl_mode && $ssl_mode != 'tls' && (!$roundcube_config['default_port'] || $roundcube_config['default_port'] == 143)) {
                 $port = 993;
             }
         }
     } else {
         $host = $roundcube_config['default_host'];
         if ($roundcube_config['default_port'] == 993) {
             $ssl_mode = 'ssl';
         } else {
             $ssl_mode = 'tls';
         }
         $port = $roundcube_config['default_port'];
     }
     if (empty($port)) {
         $port = $roundcube_config['default_port'];
     }
     if (!$roundcube_config['validate_cert']) {
         $validatecert = '/novalidate-cert';
     }
     imap_timeout(IMAP_OPENTIMEOUT, 5);
     $log->debug("imap_open({" . $host . ":" . $port . "/imap/" . $ssl_mode . $validatecert . "}{$folder}, {$user} , {$password}) method ...");
     $mbox = @imap_open("{" . $host . ":" . $port . "/imap/" . $ssl_mode . $validatecert . "}{$folder}", $user, $password) or die(self::imap_open_error(imap_last_error()));
     $log->debug("Exit OSSMail_Record_Model::imap_connect() method ...");
     return $mbox;
 }
Exemple #17
0
 /**
  * Function to process each individual message
  * @param int    $pos            (message number)
  * @param string $type           (DNS or BODY type)
  * @param string $totalFetched   (total number of messages in mailbox)
  * @return boolean
  */
 function processBounce($pos, $type, $totalFetched)
 {
     $header = imap_header($this->_mailbox_link, $pos);
     $subject = strip_tags($header->subject);
     $met = ini_get('max_execution_time');
     if ($met < 6000 && $met != 0) {
         set_time_limit(6000);
     }
     imap_timeout(IMAP_READTIMEOUT, 6000);
     imap_timeout(IMAP_WRITETIMEOUT, 6000);
     if ($type == 'DSN') {
         // first part of DSN (Delivery Status Notification), human-readable explanation
         $dsn_msg = imap_fetchbody($this->_mailbox_link, $pos, "1");
         $dsn_msg_structure = imap_bodystruct($this->_mailbox_link, $pos, "1");
         if ($dsn_msg_structure->encoding == 4) {
             $dsn_msg = quoted_printable_decode($dsn_msg);
         } elseif ($dsn_msg_structure->encoding == 3) {
             $dsn_msg = base64_decode($dsn_msg);
         }
         // second part of DSN (Delivery Status Notification), delivery-status
         $dsn_report = imap_fetchbody($this->_mailbox_link, $pos, "2");
         // process bounces by rules
         $result = bmhDSNRules($dsn_msg, $dsn_report, $this->debug_dsn_rule);
     } elseif ($type == 'BODY') {
         $structure = imap_fetchstructure($this->_mailbox_link, $pos);
         switch ($structure->type) {
             case 0:
                 // Content-type = text
             // Content-type = text
             case 1:
                 // Content-type = multipart
                 $body = imap_fetchbody($this->_mailbox_link, $pos, "1");
                 // Detect encoding and decode - only base64
                 if (!empty($structure->parts[0]->encoding) && $structure->parts[0]->encoding == 4) {
                     $body = quoted_printable_decode($body);
                 } elseif (!empty($structure->parts[0]->encoding) && $structure->parts[0]->encoding == 3) {
                     $body = base64_decode($body);
                 }
                 $result = bmhBodyRules($body, $structure, $this->debug_body_rule);
                 break;
             case 2:
                 // Content-type = message
                 $body = imap_body($this->_mailbox_link, $pos);
                 if ($structure->encoding == 4) {
                     $body = quoted_printable_decode($body);
                 } elseif ($structure->encoding == 3) {
                     $body = base64_decode($body);
                 }
                 $body = substr($body, 0, 1000);
                 $result = bmhBodyRules($body, $structure, $this->debug_body_rule);
                 break;
             default:
                 // unsupport Content-type
                 $this->output('Msg #' . $pos . ' is unsupported Content-Type:' . $structure->type, VERBOSE_REPORT);
                 return false;
         }
     } else {
         // internal error
         $this->error_msg = 'Internal Error: unknown type';
         return false;
     }
     $email = $result['email'];
     $bounce_type = $result['bounce_type'];
     if ($this->moveHard && $result['remove'] == 1) {
         $remove = 'moved (hard)';
     } elseif ($this->moveSoft && $result['remove'] == 1) {
         $remove = 'moved (soft)';
     } elseif ($this->disable_delete) {
         $remove = 0;
     } else {
         $remove = $result['remove'];
     }
     $rule_no = $result['rule_no'];
     $rule_cat = $result['rule_cat'];
     $xheader = false;
     if ($rule_no == '0000') {
         // internal error      return false;
         // code below will use the Callback function, but return no value
         if (trim($email) == '') {
             $email = $header->fromaddress;
         }
         $params = array($pos, $body, $bounce_type, $email, $subject, $xheader, $remove, $rule_no, $rule_cat, $totalFetched);
         call_user_func_array($this->action_function, $params);
     } else {
         // match rule, do bounce action
         if ($this->testmode) {
             $this->output('Match: ' . $rule_no . ':' . $rule_cat . '; ' . $bounce_type . '; ' . $email);
             return true;
         } else {
             $params = array($pos, $body, $bounce_type, $email, $subject, $xheader, $remove, $rule_no, $rule_cat, $totalFetched);
             return call_user_func_array($this->action_function, $params);
         }
     }
 }
Exemple #18
0
/**
 * Generate Mail accounts list
 *
 * @param iMSCP_pTemplate $tpl reference to the template object
 * @param int $mainDmnId Customer main domain unique identifier
 * @return int number of subdomain mails addresses
 */
function _client_generateMailAccountsList($tpl, $mainDmnId)
{
    /** @var $cfg iMSCP_Config_Handler_File */
    $cfg = iMSCP_Registry::get('config');
    $stmt = exec_query("\n\t\t\tSELECT\n\t\t\t\t`mail_id`, `mail_pass`,\n\t\t\t \tCONCAT(LEFT(`mail_forward`, 30), IF(LENGTH(`mail_forward`) > 30, '...', '')) AS `mail_forward`,\n\t\t\t \t`mail_type`, `status`, `mail_auto_respond`, `quota`, `mail_addr`\n\t\t\tFROM\n\t\t\t\t`mail_users`\n\t\t\tWHERE\n\t\t\t\t`domain_id` = ?\n\t\t\tAND\n\t\t\t\t`mail_type` NOT LIKE '%catchall%'\n\t\t\tORDER BY\n\t\t\t\t`mail_addr` ASC, `mail_type` DESC\n\t\t", $mainDmnId);
    $rowCount = $stmt->rowCount();
    if (!$rowCount) {
        return 0;
    } else {
        $mainDmnProps = get_domain_default_props($_SESSION['user_id']);
        $mailQuotaLimit = $mainDmnProps['mail_quota'] ? bytesHuman($mainDmnProps['mail_quota']) : 0;
        $imapAvailable = function_exists('imap_open');
        if ($imapAvailable) {
            imap_timeout(IMAP_OPENTIMEOUT, 1);
            imap_timeout(IMAP_READTIMEOUT, 2);
            imap_timeout(IMAP_CLOSETIMEOUT, 4);
        }
        $imapTimeoutReached = false;
        while ($row = $stmt->fetchRow(PDO::FETCH_ASSOC)) {
            list($mailDelete, $mailDeleteScript, $mailEdit, $mailEditScript) = _client_generateUserMailAction($row['mail_id'], $row['status']);
            $mailAddr = $row['mail_addr'];
            $mailTypes = explode(',', $row['mail_type']);
            $mailType = '';
            $isMailbox = 0;
            foreach ($mailTypes as $type) {
                $mailType .= user_trans_mail_type($type);
                if (strpos($type, '_forward') !== false) {
                    $mailType .= ': ' . str_replace(',', ', ', $row['mail_forward']);
                } else {
                    $isMailbox = 1;
                }
                $mailType .= '<br />';
            }
            if ($isMailbox && $row['status'] == 'ok') {
                if ($imapAvailable) {
                    $quotaMax = $row['quota'];
                    if ($quotaMax) {
                        if (!$imapTimeoutReached && ($imapStream = @imap_open("{localhost/notls}", $mailAddr, $row['mail_pass'], OP_HALFOPEN))) {
                            $quotaUsage = imap_get_quotaroot($imapStream, 'INBOX');
                            imap_close($imapStream);
                            if (!empty($quotaUsage)) {
                                $quotaUsage = $quotaUsage['usage'] * 1024;
                            } else {
                                $quotaUsage = 0;
                            }
                            $quotaMax = bytesHuman($quotaMax);
                            $txtQuota = $mailQuotaLimit ? tr('%s / %s of %s', bytesHuman($quotaUsage), $quotaMax, $mailQuotaLimit) : sprintf('%s / %s', bytesHuman($quotaUsage), $quotaMax);
                        } else {
                            $imapTimeoutReached = true;
                            $txtQuota = tr('Info Unavailable');
                        }
                    } else {
                        $txtQuota = tr('unlimited');
                    }
                } else {
                    $txtQuota = tr('Info Unavailable');
                }
            } else {
                $txtQuota = '---';
            }
            $tpl->assign(array('MAIL_ADDR' => tohtml(decode_idna($mailAddr)), 'MAIL_TYPE' => $mailType, 'MAIL_STATUS' => translate_dmn_status($row['status']), 'MAIL_DELETE' => $mailDelete, 'MAIL_DELETE_SCRIPT' => $mailDeleteScript, 'MAIL_EDIT' => $mailEdit, 'MAIL_EDIT_SCRIPT' => $mailEditScript, 'MAIL_QUOTA_VALUE' => $txtQuota, 'DEL_ITEM' => $row['mail_id'], 'DISABLED_DEL_ITEM' => $row['status'] != 'ok' ? $cfg->HTML_DISABLED : ''));
            _client_generateUserMailAutoRespond($tpl, $row['mail_id'], $row['status'], $row['mail_auto_respond']);
            $tpl->parse('MAIL_ITEM', '.mail_item');
        }
        return $rowCount;
    }
}
Exemple #19
0
<?php

echo "Checking with no parameters\n";
imap_timeout();
echo "Checking with incorrect parameter type\n";
imap_timeout('');
imap_timeout(false);
echo "GET values:\n";
var_dump(imap_timeout(IMAP_OPENTIMEOUT));
var_dump(imap_timeout(IMAP_READTIMEOUT));
var_dump(imap_timeout(IMAP_WRITETIMEOUT));
var_dump(imap_timeout(IMAP_CLOSETIMEOUT));
echo "SET values:\n";
var_dump(imap_timeout(IMAP_OPENTIMEOUT, 10));
var_dump(imap_timeout(IMAP_READTIMEOUT, 10));
var_dump(imap_timeout(IMAP_WRITETIMEOUT, 10));
//IMAP_CLOSETIMEOUT not implemented
//var_dump(imap_timeout(IMAP_CLOSETIMEOUT, 10));
echo "CHECK values:\n";
var_dump(imap_timeout(IMAP_OPENTIMEOUT));
var_dump(imap_timeout(IMAP_READTIMEOUT));
var_dump(imap_timeout(IMAP_WRITETIMEOUT));
//IMAP_CLOSETIMEOUT not implemented
//var_dump(imap_timeout(IMAP_CLOSETIMEOUT));
Exemple #20
0
function mailcwp_handler($atts, $content, $tag)
{
    $smarty = new Smarty();
    $smarty->setTemplateDir(plugin_dir_path(__FILE__) . 'templates');
    $smarty->setCompileDir(plugin_dir_path(__FILE__) . 'templates_c');
    $smarty->setCacheDir(plugin_dir_path(__FILE__) . '/cache');
    if (!is_user_logged_in()) {
        //wp_die(__("Please login to view this page.", "mailcwp"));
        //wp_redirect(wp_login_url("$_SERVER[PHP_SELF]"));
        echo "<p>Please login to view this page.</p><p>You will be redirected in a moment. If you are not redirected click <a href=\"#\" onclick=\"window.location = '" . wp_login_url() . "?redirect_to=' + window.location.href;\">here</a>.<script type=\"text/javascript\">window.location = '" . wp_login_url() . "?redirect_to=' + window.location.href;</script>";
        exit;
    }
    //add_filter( 'show_admin_bar', '__return_false' );
    $options = get_option("mailcwp_settings", array());
    $hide_admin_bar = isset($options["hide_admin_bar"]) ? $options["hide_admin_bar"] : true;
    $hide_page_title = isset($options["hide_page_title"]) ? $options["hide_page_title"] : true;
    if (isset($options) && !empty($options)) {
        imap_timeout(isset($options["imap_open_timeout"]) ? $options["imap_open_timeout"] : 15, IMAP_OPENTIMEOUT);
        imap_timeout(isset($options["imap_read_timeout"]) ? $options["imap_read_timeout"] : 15, IMAP_READTIMEOUT);
        imap_timeout(isset($options["imap_write_timeout"]) ? $options["imap_write_timeout"] : 15, IMAP_WRITETIMEOUT);
        imap_timeout(isset($options["imap_close_timeout"]) ? $options["imap_close_timeout"] : 15, IMAP_CLOSETIMEOUT);
        //write_log("TIMEZONE SET " . date_default_timezone_set('Australia/Melbourne'));
    }
    $current_user = wp_get_current_user();
    $accounts = get_user_meta($current_user->ID, "mailcwp_accounts", true);
    $default_account_id = get_user_meta($current_user->ID, "mailcwp_account_default", true);
    //write_log("CURRENT USER " . print_r($current_user, true));
    //write_log("Accounts " . print_r($accounts, true));
    $smarty->assign('labels', array("compose" => __("Compose New Message", "mailcwp"), "refresh" => __("Refresh Folders", "mailcwp"), "options" => __("Options", "mailcwp"), "themes" => __("Theme", "mailcwp"), "mark_read" => __("Mark Read", "mailcwp"), "mark_unread" => __("Mark Unread", "mailcwp"), "delete" => __("Delete", "mailcwp"), "search" => __("Find Messages", "mailcwp")));
    $smarty->assign('user_change_theme', isset($options) && isset($options["user_change_theme"]) ? $options["user_change_theme"] : true);
    $smarty->assign('set1_extensions', apply_filters("mailcwp_toolbar_set1", ""));
    $smarty->assign('set2_extensions', apply_filters("mailcwp_toolbar_set2", ""));
    $smarty->assign('set_search_extensions', apply_filters("mailcwp_toolbar_set_search", ""));
    $smarty->assign('progress_bar_src', plugins_url("/img/ajax_loading.gif", __FILE__));
    echo apply_filters("mailcwp_toolbar", $smarty->fetch('toolbar.tpl'));
    //$smarty->clear_all_assign();
    delete_user_meta($current_user->ID, 'mailcwp_session');
    $mailcwp_session = null;
    /*$smarty->assign('accounts', $accounts);
      $passwords = array();
      $folders = array();
      if (is_array($accounts)) {
        foreach ($accounts as $account) {
          if (isset($account["id"])) {
            $password = mailcwp_get_account_password($account);
            $passwords[$account["id"]] = $password;
          }
        }
      }
      $smarty->assign('passwords', $passwords);*/
    ?>
  <div id="mailcwp_container" class="ui-widget-content">
    <div id="mailcwp_accounts" class="ui-widget-content">
      <?php 
    if (is_array($accounts)) {
        for ($mode = 0; $mode <= 1; $mode++) {
            foreach ($accounts as $account) {
                if (isset($account["id"])) {
                    if ($mode == 0 && isset($default_account_id) && $account["id"] == $default_account_id || $mode == 1 && isset($default_account_id) && $account["id"] != $default_account_id || !isset($default_account_id)) {
                        ?>
	      <h3 id="<?php 
                        echo $account["id"];
                        ?>
"><?php 
                        echo $account["name"];
                        ?>
</h3>
	      <div>
		<?php 
                        $password = mailcwp_get_account_password($account);
                        //present password page
                        if (empty($password)) {
                            echo mailcwp_login_dialog($account["id"]);
                            echo "</div>";
                        } else {
                            $mbox_name = $account["host"] . ":" . $account["port"];
                            $use_ssl_flag = $account["use_ssl"] ? "/ssl" : "";
                            $use_tls_flag = $account["use_tls"] ? "/tls" : "";
                            //write_log("ACCOUNT $account[name]: $account[use_ssl]");
                            $mbox = mailcwp_imap_connect($account, OP_HALFOPEN, "");
                            if (isset($mbox)) {
                                $folders = imap_listmailbox($mbox, "{" . $mbox_name . $use_ssl_flag . "}", "*");
                                if ($folders === false) {
                                    echo __("No folders found.", "mailcwp");
                                } else {
                                    $folder_tree = array();
                                    foreach ($folders as $folder) {
                                        $folder_name = substr($folder, strlen($mbox_name) + strlen($use_ssl_flag) + 2);
                                        if ($mailcwp_session == null) {
                                            $mailcwp_session = array();
                                            $mailcwp_session["account"] = $account;
                                            $mailcwp_session["folder"] = $folder_name;
                                            update_user_meta($current_user->ID, "mailcwp_session", $mailcwp_session);
                                        }
                                        add_folder_to_tree($folder_tree, $folder_name);
                                    }
                                    ?>
			<?php 
                                    echo folder_menu($account["id"], $folder_tree, "", true);
                                    ?>
			<?php 
                                }
                                //$headers = imap_headers($mbox);
                                imap_close($mbox);
                            } else {
                                echo __("Unable to open mailbox. Please check the username and password.", "mailcwp");
                            }
                            /*$folder_toolbar_html = "  <div id=\"mailcwp_folder_toolbar_$account[name]\" class=\"mailcwp_folder_toolbar ui-widget-header ui-corner-all\">" .
                              (isset($options["user_manage_accounts"]) && $options["user_manage_accounts"] == true ? 
                               "    <button id=\"mailcwp_folder_settings_$account[id]\" class=\"mailcwp_folder_settings\">" . __("Account Settings", "mailcwp") . "</button>" .
                               "    <button id=\"mailcwp_close_account_$account[id]\" data=\"" . str_replace(" ", "_", $account["name"]) . "\" class=\"mailcwp_close_account\">" . __("Remove Account", "mailcwp") . "</button>" : "") .
                               "  </div>";
                               echo $folder_toolbar_html;*/
                            ?>
		</div>
	      <?php 
                        }
                    }
                }
            }
        }
        /*if (isset($options["user_manage_accounts"]) && $options["user_manage_accounts"] == true) {
          ?>
          <h3 id="mailcwp_add_account">Add Account</h3>
          <?php
          }*/
    }
    ?>
    </div>
    <div id="mailcwp_headers" class="ui-widget-content ui-corner-bottom">
       <?php 
    _e(is_array($accounts) && count($accounts) > 0 ? "No messages found." : "No accounts found. Please contact the sysadmin administrator for assistance.", "mailcwp");
    ?>
    </div>
  </div>
  <div id="mailcwp_prologue">
    <span><a href="http://cadreworks.com/mailcwp-plugin">MailCWP version <?php 
    echo MAILCWP_VERSION;
    ?>
 by CadreWorks Pty Ltd, <?php 
    echo date("Y");
    ?>
</a></span>
  </div>
  <span id="dummy" style="height:0"></span>
  <script type="text/javascript">
    <?php 
    if ($hide_admin_bar) {
        ?>
      jQuery(document).ready(function() {
        jQuery("#wpadminbar").toggle();
        jQuery(document.body).offset({top: 0});
      });
    <?php 
    }
    ?>
    <?php 
    if ($hide_page_title) {
        ?>
      jQuery(document).ready(function() {
        jQuery("h1").toggle();
      });
    <?php 
    }
    ?>
    <?php 
    if (!isset($options["user_manage_accounts"]) || $options["user_manage_accounts"] === true) {
        ?>
    <?php 
        if (!is_array($accounts) || count($accounts) == 0) {
            ?>
        //jQuery(document).ready(editAccount(null, null, null, false));
        jQuery(document).ready(function(){jQuery("#mailcwp_options").click()});
    <?php 
        }
        ?>
    <?php 
    }
    ?>
    <?php 
    if (isset($options["auto_refresh"]) && $options["auto_refresh"] == true && isset($options["refresh_interval"])) {
        ?>
      mRefreshInterval = <?php 
        echo $options["refresh_interval"];
        ?>
;
    <?php 
    } else {
        ?>
      mRefreshInterval = 0;
    <?php 
    }
    $mailcwp_options = get_user_meta($current_user->ID, "mailcwp_options", true);
    //write_log("MAILCWP OPTIONS: " . print_r($mailcwp_options, true));
    if (is_array($mailcwp_options) && isset($mailcwp_options["theme"])) {
        ?>
      mThemeURL = "<?php 
        echo $mailcwp_options["theme"];
        ?>
";
      mThemeName = "<?php 
        echo $mailcwp_options["theme_name"];
        ?>
";
    <?php 
    }
    ?>
  </script>
<?php 
    //mailcwp_get_unseen_messages();
}
 public static function imapConnect($user, $password, $host = false, $folder = 'INBOX', $dieOnError = true)
 {
     $log = vglobal('log');
     $log->debug("Entering OSSMail_Record_Model::imapConnect({$user} , {$password} , {$folder}) method ...");
     $rcConfig = self::load_roundcube_config();
     if (!$host) {
         $host = key($rcConfig['default_host']);
     }
     $parseHost = parse_url($host);
     $validatecert = '';
     if ($parseHost['host']) {
         $host = $parseHost['host'];
         $sslMode = isset($a_host['scheme']) && in_array($parseHost['scheme'], ['ssl', 'imaps', 'tls']) ? $parseHost['scheme'] : null;
         if (!empty($parseHost['port'])) {
             $port = $parseHost['port'];
         } else {
             if ($sslMode && $sslMode != 'tls' && (!$rcConfig['default_port'] || $rcConfig['default_port'] == 143)) {
                 $port = 993;
             }
         }
     } else {
         if ($rcConfig['default_port'] == 993) {
             $sslMode = 'ssl';
         } else {
             $sslMode = 'tls';
         }
     }
     if (empty($port)) {
         $port = $rcConfig['default_port'];
     }
     if (!$rcConfig['validate_cert']) {
         $validatecert = '/novalidate-cert';
     }
     if ($rcConfig['imap_open_add_connection_type']) {
         $sslMode = '/' . $sslMode;
     } else {
         $sslMode = '';
     }
     imap_timeout(IMAP_OPENTIMEOUT, 5);
     $log->debug("imap_open({" . $host . ":" . $port . "/imap" . $sslMode . $validatecert . "}{$folder}, {$user} , {$password}) method ...");
     if ($dieOnError) {
         $mbox = @imap_open("{" . $host . ":" . $port . "/imap" . $sslMode . $validatecert . "}{$folder}", $user, $password) or die(self::imapThrowError(imap_last_error()));
     } else {
         $mbox = @imap_open("{" . $host . ":" . $port . "/imap" . $sslMode . $validatecert . "}{$folder}", $user, $password);
     }
     $log->debug("Exit OSSMail_Record_Model::imapConnect() method ...");
     return $mbox;
 }
 /**
  * Add a new E-Mail account to database
  */
 function add_email_account($imap_host, $imap_port, $imap_ssl, $smtp_host, $smtp_port, $smtp_ssl, $username, $password, $test_login = true)
 {
     global $phpmailer;
     $email_accounts =& $this->email_accounts;
     $imap_host = sanitize_text_field($imap_host);
     $imap_port = intval($imap_port);
     $imap_ssl = (bool) $imap_ssl;
     $smtp_host = sanitize_text_field($smtp_host);
     $smtp_port = intval($smtp_port);
     $smtp_ssl = (bool) $smtp_ssl;
     $username = sanitize_text_field($username);
     $password = sanitize_text_field($password);
     if ($this->email_account_exists($imap_host, $smtp_host, $username)) {
         SupportFlow()->extend->logger->log('email_accounts', __METHOD__, __('Account already exists.', 'supportflow'), compact('imap_host', 'imap_port', 'imap_ssl', 'smtp_host', 'smtp_port', 'smtp_ssl', 'username'));
         return self::ACCOUNT_EXISTS;
     }
     if ($test_login) {
         imap_timeout(IMAP_OPENTIMEOUT, apply_filters('supportflow_imap_open_timeout', 5));
         $ssl = $imap_ssl ? '/ssl' : '';
         $ssl = apply_filters('supportflow_imap_ssl', $ssl, $imap_host);
         $mailbox = '{' . $imap_host . ':' . $imap_port . $ssl . '}';
         if ($imap_stream = imap_open($mailbox, $username, $password, 0, 0)) {
             SupportFlow()->extend->logger->log('email_accounts', __METHOD__, __('Successfully opened IMAP connection.', 'supportflow'), compact('imap_host', 'imap_port', 'imap_ssl', 'smtp_host', 'smtp_port', 'smtp_ssl', 'username', 'mailbox'));
             imap_close($imap_stream);
         } else {
             $imap_errors = imap_errors();
             $error = $imap_errors[0];
             SupportFlow()->extend->logger->log('email_accounts', __METHOD__, __('Failed to open IMAP connection.', 'supportflow'), compact('imap_host', 'imap_port', 'imap_ssl', 'smtp_host', 'smtp_port', 'smtp_ssl', 'username', 'mailbox', 'imap_errors'));
             if ((string) strpos($error, 'Host not found') != '') {
                 return self::IMAP_HOST_NOT_FOUND;
             } elseif ((string) strpos($error, 'Timed out') != '') {
                 return self::IMAP_TIME_OUT;
             } elseif ((string) strpos($error, 'Invalid credentials') != '') {
                 return self::IMAP_INVALID_CREDENTIALS;
             } else {
                 return self::IMAP_CONNECTION_FAILED;
             }
         }
         // Initialize PHPMailer
         wp_mail('', '', '');
         // Set PHPMailer SMTP settings
         $phpmailer->IsSMTP();
         $phpmailer->Host = $smtp_host;
         $phpmailer->Port = $smtp_port;
         $phpmailer->SMTPSecure = $smtp_ssl ? 'ssl' : '';
         $phpmailer->SMTPAutoTLS = $smtp_ssl;
         $phpmailer->Username = $username;
         $phpmailer->Password = $password;
         $phpmailer->SMTPAuth = true;
         // $phpmail raise fatal error on SMTP connect failure
         try {
             $smtp_authentication = $phpmailer->smtpConnect();
         } catch (Exception $e) {
             $smtp_authentication = false;
             SupportFlow()->extend->logger->log('email_accounts', __METHOD__, sprintf(__('PHPMailer exception: %s.', 'supportflow'), $e->getMessage()), compact('smtp_host', 'smtp_port', 'smtp_ssl', 'username'));
         }
         SupportFlow()->extend->logger->log('email_accounts', __METHOD__, $smtp_authentication ? __('Successfully authenticated with SMTP server.', 'supportflow') : __('Failed to authenticate with SMTP server.', 'supportflow'), compact('imap_host', 'imap_port', 'imap_ssl', 'smtp_host', 'smtp_port', 'smtp_ssl', 'username', 'mailbox'));
         if (!$smtp_authentication) {
             return self::SMTP_AUTHENTICATION_FAILED;
         }
     }
     $email_accounts[] = array('imap_host' => $imap_host, 'imap_port' => $imap_port, 'imap_ssl' => $imap_ssl, 'smtp_host' => $smtp_host, 'smtp_port' => $smtp_port, 'smtp_ssl' => $smtp_ssl, 'username' => $username, 'password' => $password);
     update_option('sf_email_accounts', $email_accounts);
     return self::SUCCESS;
 }
 /**
  * @param $email
  *
  * @return resource
  * @throws \MailChecker\Exceptions\MailProviderException
  */
 private function openMailbox($email)
 {
     if (!isset($this->credentials[$email])) {
         throw new MailProviderException("Email address: '{$email}' does not found in credentials config");
     }
     imap_timeout(IMAP_OPENTIMEOUT, 5);
     codecept_debug('Open email box: ' . $this->mailbox);
     $mailboxResource = imap_open($this->mailbox, $email, $this->credentials[$email], OP_SILENT);
     if ($mailboxResource === false) {
         throw new MailProviderException('Can not open mailbox: ' . imap_last_error());
     }
     return $mailboxResource;
 }
Exemple #24
0
 public function setTimeout($secs)
 {
     imap_timeout(IMAP_OPENTIMEOUT, $secs);
     imap_timeout(IMAP_CLOSETIMEOUT, $secs);
     imap_timeout(IMAP_READTIMEOUT, $secs);
     imap_timeout(IMAP_WRITETIMEOUT, $secs);
 }
Exemple #25
0
 public static function imap_connect($user, $password, $folder = 'INBOX')
 {
     global $log;
     $log->debug("Entering OSSMail_Record_Model::imap_connect({$user} , {$password} , {$folder}) method ...");
     $roundcube_config = self::load_roundcube_config();
     $a_host = parse_url($roundcube_config['default_host']);
     $validatecert = '';
     if ($a_host['host']) {
         $host = $a_host['host'];
         $ssl_mode = isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl', 'imaps', 'tls')) ? $a_host['scheme'] : null;
         if (!empty($a_host['port'])) {
             $port = $a_host['port'];
         } else {
             if ($ssl_mode && $ssl_mode != 'tls' && (!$roundcube_config['default_port'] || $roundcube_config['default_port'] == 143)) {
                 $port = 993;
             }
         }
     } else {
         $host = $roundcube_config['default_host'];
         if ($roundcube_config['default_port'] == 993) {
             $ssl_mode = 'ssl';
         } else {
             $ssl_mode = 'tls';
         }
         $port = $roundcube_config['default_port'];
     }
     if (!$port) {
         $port = $roundcube_config['default_port'];
     }
     if (!$roundcube_config['validate_cert']) {
         $validatecert = '/novalidate-cert';
     }
     imap_timeout(IMAP_OPENTIMEOUT, 5);
     try {
         $mbox = imap_open("{" . $host . ":" . $port . "/imap/" . $ssl_mode . $validatecert . "}{$folder}", $user, $password);
     } catch (Exception $e) {
         $log->debug("Error OSSMail_Record_Model::imap_connect(): " . imap_last_error() . ' [' . $e->getMessage() . ']');
         die(self::createdAlert(vtranslate('IMAP_ERROR', 'OSSMailScanner') . ': ' . imap_last_error() . ' [' . $e->getMessage() . ']'));
     }
     $log->debug("Exit OSSMail_Record_Model::imap_connect() method ...");
     return $mbox;
 }
 /**
  * Connects to mailserver.  If an existing IMAP resource is available, it
  * will attempt to reuse the connection, updating the mailbox path.
  *
  * @param bool test Flag to test connection
  * @param bool force Force reconnect
  * @return string "true" on success, "false" or $errorMessage on failure
  */
 function connectMailserver($test = false, $force = false)
 {
     global $mod_strings;
     if (!function_exists("imap_open")) {
         $GLOBALS['log']->debug('------------------------- IMAP libraries NOT available!!!! die()ing thread.----');
         return $mod_strings['LBL_WARN_NO_IMAP'];
     }
     imap_errors();
     // clearing error stack
     error_reporting(0);
     // turn off notices from IMAP
     // tls::ca::ssl::protocol::novalidate-cert::notls
     $useSsl = $_REQUEST['ssl'] == 'true' ? true : false;
     if ($test) {
         imap_timeout(1, 15);
         // 60 secs is the default
         imap_timeout(2, 15);
         imap_timeout(3, 15);
         $opts = $this->findOptimumSettings($useSsl);
         if (isset($opts['good']) && empty($opts['good'])) {
             return array_pop($opts['err']);
         } else {
             $service = $opts['service'];
             $service = str_replace('foo', '', $service);
             // foo there to support no-item explodes
         }
     } else {
         $service = $this->getServiceString();
     }
     $connectString = $this->getConnectString($service, $this->mailbox);
     /*
      * Try to recycle the current connection to reduce response times
      */
     if (is_resource($this->conn)) {
         if ($force) {
             // force disconnect
             imap_close($this->conn);
         }
         if (imap_ping($this->conn)) {
             // we have a live connection
             imap_reopen($this->conn, $connectString, CL_EXPUNGE);
         }
     }
     // final test
     if (!is_resource($this->conn) && !$test) {
         $this->conn = imap_open($connectString, $this->email_user, $this->email_password, CL_EXPUNGE);
     }
     if ($test) {
         if ($opts == false && !is_resource($this->conn)) {
             $this->conn = imap_open($connectString, $this->email_user, $this->email_password, CL_EXPUNGE);
         }
         $errors = '';
         $alerts = '';
         $successful = false;
         if (($errors = imap_last_error()) || ($alerts = imap_alerts())) {
             if ($errors == 'Mailbox is empty') {
                 // false positive
                 $successful = true;
             } else {
                 $msg .= $errors;
                 $msg .= '<p>' . $alerts . '<p>';
                 $msg .= '<p>' . $mod_strings['ERR_TEST_MAILBOX'];
             }
         } else {
             $successful = true;
         }
         if ($successful) {
             if ($this->protocol == 'imap') {
                 $msg .= $mod_strings['LBL_TEST_SUCCESSFUL'];
                 /*
                 $testConnectString = '{'.$this->server_url.':'.$this->port.'/service='.$this->protocol.$service.'}';
                 if (!is_resource($this->conn)) {
                 	$this->conn = imap_open($connectString, $this->email_user, $this->email_password, CL_EXPUNGE);
                 }
                 $list = imap_getmailboxes($this->conn, $testConnectString, "*");
                 if(isset($_REQUEST['personal']) && $_REQUEST['personal'] == 'true') {
                 	$msg .= $mod_strings['LBL_TEST_SUCCESSFUL'];
                 } elseif (is_array($list)) {
                 	sort($list);
                 	_ppd($boxes);
                 
                 	$msg .= '<b>'.$mod_strings['LBL_FOUND_MAILBOXES'].'</b><p>';
                 	foreach ($list as $key => $val) {
                 		$mb = imap_utf7_decode(str_replace($testConnectString,'',$val->name));
                 		$msg .= '<a onClick=\'setMailbox(\"'.$mb.'\"); window.close();\'>';
                 		$msg .= $mb;
                 		$msg .= '</a><br>';
                 	}
                 } else {
                 	$msg .= $errors;
                 	$msg .= '<p>'.$mod_strings['ERR_MAILBOX_FAIL'].imap_last_error().'</p>';
                 	$msg .= '<p>'.$mod_strings['ERR_TEST_MAILBOX'].'</p>';
                 }
                 */
             } else {
                 $msg .= $mod_strings['LBL_POP3_SUCCESS'];
             }
         }
         imap_errors();
         // collapse error stack
         imap_close($this->conn);
         return $msg;
     } elseif (!is_resource($this->conn)) {
         return "false";
     } else {
         return "true";
     }
 }
Exemple #27
0
 function _connectimap()
 {
     ob_start();
     //First we reset the buffer or errors and warnings
     $buff = imap_alerts();
     $buff = imap_errors();
     $timeout = $this->config->getValue('bounce_timeout');
     if (!empty($timeout)) {
         imap_timeout(IMAP_OPENTIMEOUT, $timeout);
     }
     $port = $this->config->getValue('bounce_port', '');
     $secure = $this->config->getValue('bounce_connection_secure', '');
     $protocol = $this->config->getValue('bounce_connection_method', '');
     $serverName = '{' . $this->config->getValue('bounce_host');
     if (empty($port)) {
         if ($secure == 'ssl' && $protocol == 'imap') {
             $port = '993';
         } elseif ($protocol == 'imap') {
             $port = '143';
         } elseif ($protocol == 'pop3') {
             $port = '110';
         }
     }
     if (!empty($port)) {
         $serverName .= ':' . $port;
     }
     //Add the secure protocol (TLS or SSL)
     if (!empty($secure)) {
         $serverName .= '/' . $secure;
     }
     if ($this->config->getValue('bounce_selfsigned', false)) {
         $serverName .= '/novalidate-cert';
     }
     //Add the method (imap by default) ex : pop3
     if (!empty($protocol)) {
         $serverName .= '/service=' . $protocol;
     }
     $serverName .= '}';
     $this->mailbox = imap_open($serverName, trim($this->config->getValue('bounce_login')), trim($this->config->getValue('bounce_password')));
     $warnings = ob_get_clean();
     if ($this->report) {
         if (!$this->mailbox) {
             $this->error('Error connecting to ' . $serverName, true);
         }
         if (!empty($warnings)) {
             $this->error($warnings, true);
         }
     }
     return $this->mailbox ? true : false;
 }