function getdata($host, $login, $password, $savedirpath)
 {
     $mbox = imap_open($host, $login, $password) or die("can't connect: " . imap_last_error());
     $message = array();
     $message["attachment"]["type"][0] = "text";
     $message["attachment"]["type"][1] = "multipart";
     $message["attachment"]["type"][2] = "message";
     $message["attachment"]["type"][3] = "application";
     $message["attachment"]["type"][4] = "audio";
     $message["attachment"]["type"][5] = "image";
     $message["attachment"]["type"][6] = "video";
     $message["attachment"]["type"][7] = "other";
     $buzon_destino = "cfdi";
     echo imap_createmailbox($mbox, imap_utf7_encode("{$buzon_destino}"));
     echo imap_num_msg($mbox);
     for ($jk = 1; $jk <= imap_num_msg($mbox); $jk++) {
         $structure = imap_fetchstructure($mbox, $jk);
         $parts = $structure->parts;
         $fpos = 2;
         for ($i = 1; $i < count($parts); $i++) {
             $message["pid"][$i] = $i;
             $part = $parts[$i];
             if (strtolower($part->disposition) == "attachment") {
                 $message["type"][$i] = $message["attachment"]["type"][$part->type] . "/" . strtolower($part->subtype);
                 $message["subtype"][$i] = strtolower($part->subtype);
                 $ext = $part->subtype;
                 $params = $part->dparameters;
                 $filename = $part->dparameters[0]->value;
                 if (!($ext == 'xml' or $ext == 'XML' or $ext == 'PDF' or $ext == 'pdf')) {
                     continue;
                 }
                 $mege = "";
                 $data = "";
                 $mege = imap_fetchbody($mbox, $jk, $fpos);
                 $data = $this->getdecodevalue($mege, $part->type);
                 $fp = fopen($filename, 'w');
                 fputs($fp, $data);
                 fclose($fp);
                 $fpos += 1;
                 /* Se mueve el archiv descargado al directorio de recibidos */
                 //                    rename($filename, $savedirpath.$filename);
                 //                    printf("\nSe movio el archivo $filename");
             }
         }
         $result = imap_fetch_overview($mbox, $jk);
         echo $result[0]->from;
         //            imap_mail_move($mbox, $jk, $buzon_destino);
         //imap_delete tags a message for deletion
         //    imap_delete($mbox,$jk);
     }
     // imap_expunge deletes all tagged messages
     //                    imap_expunge($mbox);
     imap_close($mbox);
 }
 /**
  * Get a mailbox by its name
  *
  * @param string $name Mailbox name
  *
  * @return Mailbox
  * @throws Mirasvit_Ddeboer_Imap_Exception_MailboxDoesNotExistException If mailbox does not exist
  */
 public function getMailbox($name)
 {
     if (!in_array($name, $this->getMailboxNames())) {
         throw new Mirasvit_Ddeboer_Imap_Exception_MailboxDoesNotExistException($name);
     }
     return new Mirasvit_Ddeboer_Imap_Mailbox($this->server . imap_utf7_encode($name), $this);
 }
Example #3
0
 /**
  * Get a mailbox by its name
  *
  * @param string $name Mailbox name
  *
  * @return Mailbox
  * @throws MailboxDoesNotExistException If mailbox does not exist
  */
 public function getMailbox($name)
 {
     if (!\in_array($name, $this->getMailboxNames())) {
         throw new MailboxDoesNotExistException($name);
     }
     return new Mailbox($this->server . \imap_utf7_encode($name), $this);
 }
Example #4
0
 /**
  * Get a mailbox by its name
  *
  * @param string $name Mailbox name
  *
  * @return Mailbox
  * @throws MailboxDoesNotExistException If mailbox does not exist
  */
 public function getMailbox($name)
 {
     if (!$this->hasMailbox($name)) {
         throw new MailboxDoesNotExistException($name);
     }
     return new Mailbox($this->server . imap_utf7_encode($name), $this);
 }
function store_email_into_folder($msg, $folder = 'SentFromDolibarr')
{
    global $user, $db;
    $mailboxconfig = new Usermailboxconfig($db);
    $mailboxconfig->fetch_from_user($user->id);
    $user->mailbox_imap_login = $mailboxconfig->mailbox_imap_login;
    $user->mailbox_imap_password = $mailboxconfig->mailbox_imap_password;
    $user->mailbox_imap_host = $mailboxconfig->mailbox_imap_host;
    $user->mailbox_imap_port = $mailboxconfig->mailbox_imap_port;
    $user->mailbox_imap_ssl = $mailboxconfig->mailbox_imap_ssl;
    $user->mailbox_imap_ssl_novalidate_cert = $mailboxconfig->mailbox_imap_ssl_novalidate_cert;
    $user->mailbox_imap_ref = $mailboxconfig->get_ref();
    $user->mailbox_imap_connector_url = $mailboxconfig->get_connector_url();
    $mbox = imap_open($user->mailbox_imap_connector_url . $folder, $user->mailbox_imap_login, $user->mailbox_imap_password);
    $check = imap_check($mbox);
    $before = $check->Nmsgs;
    $result = imap_append($mbox, $user->mailbox_imap_connector_url . $folder, $msg);
    $check = imap_check($mbox);
    $after = $check->Nmsgs;
    if ($result == FALSE) {
        if (imap_createmailbox($mbox, imap_utf7_encode($user->mailbox_imap_ref . $folder))) {
            $mbox = imap_open($user->mailbox_imap_connector_url . $folder, $user->mailbox_imap_login, $user->mailbox_imap_password);
            $check = imap_check($mbox);
            $before = $check->Nmsgs;
            $result = imap_append($mbox, $user->mailbox_imap_connector_url . $folder, $msg);
            $check = imap_check($mbox);
            $after = $check->Nmsgs;
        }
    }
    imap_close($mbox);
}
 function encodeFolderName($_folderName)
 {
     if ($this->mbAvailable) {
         return mb_convert_encoding($_folderName, "UTF7-IMAP", "ISO_8859-1");
     }
     // if not
     return imap_utf7_encode($_folderName);
 }
Example #7
0
 /**
  * Create mailbox
  *
  * @param $name
  *
  * @return Mailbox
  * @throws Exception
  */
 public function createMailbox($name)
 {
     // Add support for International characters
     if (\imap_createmailbox($this->resource, \imap_utf7_encode($this->server . $name))) {
         $this->mailboxNames = $this->mailboxes = null;
         return $this->getMailbox($name);
     }
     throw new Exception("Can not create '{$name}' mailbox at '{$this->server}'");
 }
 function encodeFolderName($_folderName)
 {
     if ($this->mbAvailable) {
         return mb_convert_encoding($_folderName, "UTF7-IMAP", $GLOBALS['phpgw']->translation->charset());
     }
     // if not
     // can only encode from ISO 8559-1
     return imap_utf7_encode($_folderName);
 }
Example #9
0
 public function createFolder($name = NULL)
 {
     $nameArr = explode(".", $name);
     $folders = $this->getFoldersList();
     $createName = NULL;
     foreach ($nameArr as $v) {
         $createName .= !is_null($createName) ? "." : $this->getMailbox();
         $createName .= $v;
         if (!in_array($createName, $folders)) {
             imap_createmailbox($this->imapStream, imap_utf7_encode($createName));
         }
     }
 }
Example #10
0
/**
* Check the username / password against the IMAP server
*/
function RIMAP_check($username, $password)
{
    global $c;
    $imap_username = $username;
    if (function_exists('mb_convert_encoding')) {
        $imap_username = mb_convert_encoding($imap_username, "UTF7-IMAP", mb_detect_encoding($imap_username));
    } else {
        $imap_username = imap_utf7_encode($imap_username);
    }
    //$imap_url = '{localhost:143/imap/notls}';
    //$imap_url = '{localhost:993/imap/ssl/novalidate-cert}';
    $imap_url = $c->authenticate_hook['config']['imap_url'];
    $auth_result = "ERR";
    $imap_stream = @imap_open($imap_url, $imap_username, $password, OP_HALFOPEN);
    //print_r(imap_errors());
    if ($imap_stream) {
        // disconnect
        imap_close($imap_stream);
        // login ok
        $auth_result = "OK";
    }
    if ($auth_result == "OK") {
        $principal = new Principal('username', $username);
        if (!$principal->Exists()) {
            dbg_error_log("PAM", "Principal '%s' doesn't exist in local DB, we need to create it", $username);
            if (strstr($username, '@')) {
                $name_arr = explode('@', $username);
                $fullname = ucfirst(strtolower($name_arr[0]));
                $email = $username;
            } else {
                $fullname = ucfirst(strtolower($username));
                $email = $username . "@" . $c->authenticate_hook['config']['email_base'];
            }
            $principal->Create(array('username' => $username, 'user_active' => true, 'email' => $email, 'fullname' => ucfirst($fullname)));
            if (!$principal->Exists()) {
                dbg_error_log("PAM", "Unable to create local principal for '%s'", $username);
                return false;
            }
            CreateHomeCollections($username);
        }
        return $principal;
    } else {
        dbg_error_log("PAM", "User %s is not a valid username (or password was wrong)", $username);
        return false;
    }
}
Example #11
0
 private function read()
 {
     $allMails = imap_search($this->conn, 'ALL');
     if ($allMails) {
         rsort($allMails);
         foreach ($allMails as $email_number) {
             $overview = imap_fetch_overview($this->conn, $email_number, 0);
             $structure = imap_fetchstructure($this->conn, $email_number);
             $body = '';
             if (isset($structure->parts) && is_array($structure->parts) && isset($structure->parts[1])) {
                 $part = $structure->parts[1];
                 $body = imap_fetchbody($this->conn, $email_number, 2);
                 if ($part->encoding == 3) {
                     $body = imap_base64($body);
                 } else {
                     if ($part->encoding == 1) {
                         $body = imap_8bit($body);
                     } else {
                         $body = imap_qprint($body);
                     }
                 }
             }
             $body = utf8_decode($body);
             $fromaddress = utf8_decode(imap_utf7_encode($overview[0]->from));
             $subject = mb_decode_mimeheader($overview[0]->subject);
             $date = utf8_decode(imap_utf8($overview[0]->date));
             $date = date('Y-m-d H:i:s', strtotime($date));
             $key = md5($fromaddress . $subject . $body);
             //save to MySQL
             $sql = "SELECT count(*) FROM EMAIL_INFORMATION WHERE IDMAIL = " . $this->id . " AND CHECKVERS = \"" . $key . "\"";
             $resul = $this->pdo->query($sql)->fetch();
             if ($resul[0] == 0) {
                 $this->pdo->prepare("INSERT INTO EMAIL_INFORMATION (IDMAIL,FROMADDRESS,SUBJECT,DATE,BODY,CHECKVERS) VALUES (?,?,?,?,?,?)");
                 $this->pdo->execute(array($this->id, $fromaddress, $subject, $date, $body, $key));
             }
         }
     }
 }
Example #12
0
 /**
  * This method creates, renames and deletes mailboxes from the server.
  *
  * @param    string $action
  *   One of create|rename|delete, this tells the method what you want to
  *    do with a mailbox.
  * @param    string $mb_name
  *   The name of the mailbox to create, delete or rename.
  * @param    string $mb_rename
  *   (optional) New name for the mailbox, if it is being renamed.
  *
  * @return   BOOL
  * @access   public
  * @see      imap_createmailbox
  * @see      imap_renamemailbox
  * @see      imap_deletemailbox
  * @tutorial http://www.smilingsouls.net/Mail_IMAP?content=Mail_IMAP_ManageMB/manageMB
  */
 function manageMB($action, $mb_name, $mb_rename = NULL)
 {
     switch ($action) {
         case 'create':
             if (@imap_createmailbox($this->mailbox, imap_utf7_encode($this->mailboxInfo['host'] . 'INBOX.' . $mb_name))) {
                 $ret = TRUE;
             } else {
                 $this->error->push(Mail_IMAPv2_ERROR, 'error', NULL, 'Unable to create MB: ' . $mb_name);
                 $ret = FALSE;
             }
             break;
         case 'rename':
             if (empty($mb_rename)) {
                 $this->error->push(Mail_IMAPv2_ERROR, 'error', NULL, 'No mailbox provided to rename.');
             }
             if (@imap_renamemailbox($this->mailbox, $this->mailboxInfo['host'] . 'INBOX.' . $mb_name, $this->mailboxInfo['host'] . 'INBOX.' . $mb_rename)) {
                 $ret = TRUE;
             } else {
                 $this->error->push(Mail_IMAPv2_ERROR, 'error', NULL, 'Unable to rename MB: ' . $mb_name);
                 $ret = FALSE;
             }
             break;
         case 'delete':
             if (@imap_deletemailbox($this->mailbox, $this->mailboxInfo['host'] . 'INBOX.' . $mb_name)) {
                 $ret = TRUE;
             } else {
                 $this->error->push(Mail_IMAPv2_ERROR, 'error', NULL, 'Unable to delete MB: ' . $mb_name);
                 $ret = FALSE;
             }
             break;
         default:
             $this->error->push(Mail_IMAPv2_ERROR_INVALID_ACTION, 'error', array('action' => $action, 'arg' => '$action'));
             $ret = FALSE;
             return $ret;
     }
 }
Example #13
0
 function mailbox_encode($mailbox)
 {
     if (!$mailbox) {
         return null;
     } elseif (function_exists('mb_convert_encoding')) {
         return mb_convert_encoding($mailbox, 'UTF7-IMAP', 'utf-8');
     } else {
         // XXX: This function has some issues on some versions of PHP
         return imap_utf7_encode($mailbox);
     }
 }
 function utf7_encode_string($data_str)
 {
     $name = array();
     $name['folder_before'] = '';
     $name['folder_after'] = '';
     $name['translated'] = '';
     if (strstr($data_str, '}')) {
         // folder name at this stage is  {SERVER_NAME:PORT}FOLDERNAME
         // get everything to the right of the bracket "}", INCLUDES the bracket itself
         $name['folder_before'] = strstr($data_str, '}');
         // get rid of that 'needle' "}"
         $name['folder_before'] = substr($name['folder_before'], 1);
         // translate
         if (function_exists('recode_string') == False) {
             $name['folder_after'] = imap_utf7_encode($name['folder_before']);
         } else {
             // Modif UTF-8 by Sam Przyswa so now compatible with MS-Outlook and Netscape accentued folder name
             $name_tmp = recode_string("ISO-8859-1..UTF-7", $name['folder_before']);
             $name['folder_after'] = str_replace("+", "&", $name_tmp);
         }
         // replace old folder name with new folder name
         $name['translated'] = str_replace($name['folder_before'], $name['folder_after'], $data_str);
     } else {
         // folder name at this stage is  FOLDERNAME
         // there is NO {SERVER} part in this name, this is OK some commands do not require it (mail_move same acct)
         $name['folder_before'] = $data_str;
         // translate
         $name['folder_after'] = imap_utf7_encode($name['folder_before']);
         $name['translated'] = $name['folder_after'];
     }
     if ($this->debug_utf7 > 1) {
         echo ' _ mail_dcom_base: utf7_encode_string (' . __LINE__ . '): $name DUMP: [' . htmlspecialchars(serialize($name)) . ']<br>';
     }
     return $name['translated'];
 }
 function createMailbox($folder)
 {
     if (!$folder) {
         return false;
     }
     return imap_createmailbox($this->mbox, imap_utf7_encode($this->srvstr . trim($folder)));
 }
 /**
  * Function to check if a mailbox exists
  * - if not found, it will create it
  *
  * @param string  $mailbox the mailbox name, must be in 'INBOX.checkmailbox' format
  * @param boolean $create  whether or not to create the checkmailbox if not found, defaults to true
  *
  * @return boolean
  */
 public function mailboxExist($mailbox, $create = true)
 {
     if (trim($mailbox) == '' || !strstr($mailbox, ' INBOX.')) {
         // this is a critical error with either the mailbox name blank or an invalid mailbox name
         // need to stop processing and exit at this point
         echo "Invalid mailbox name for move operation. Cannot continue.<br />\n";
         echo "TIP: the mailbox you want to move the message to must include 'INBOX.' at the start.<br />\n";
         exit;
     }
     $port = $this->port . '/' . $this->service . '/' . $this->serviceOption;
     $mbox = imap_open('{' . $this->mailhost . ":" . $port . '}', $this->mailboxUserName, $this->mailboxPassword, OP_HALFOPEN);
     $list = imap_getmailboxes($mbox, '{' . $this->mailhost . ":" . $port . '}', "*");
     $mailboxFound = false;
     if (is_array($list)) {
         foreach ($list as $key => $val) {
             // get the mailbox name only
             $nameArr = split('}', imap_utf7_decode($val->name));
             $nameRaw = $nameArr[count($nameArr) - 1];
             if ($mailbox == $nameRaw) {
                 $mailboxFound = true;
             }
         }
         if ($mailboxFound === false && $create) {
             @imap_createmailbox($mbox, imap_utf7_encode('{' . $this->mailhost . ":" . $port . '}' . $mailbox));
             imap_close($mbox);
             return true;
         } else {
             imap_close($mbox);
             return false;
         }
     } else {
         imap_close($mbox);
         return false;
     }
 }
Example #17
0
 function GetFolderList()
 {
     $folders = array();
     $list = @imap_getmailboxes($this->_mbox, $this->_server, "*");
     if (is_array($list)) {
         // reverse list to obtain folders in right order
         $list = array_reverse($list);
         foreach ($list as $val) {
             $box = array();
             // cut off serverstring
             $box["id"] = imap_utf7_decode(substr($val->name, strlen($this->_server)));
             // always use "." as folder delimiter
             $box["id"] = imap_utf7_encode(str_replace($val->delimiter, ".", $box["id"]));
             // explode hierarchies
             $fhir = explode(".", $box["id"]);
             if (count($fhir) > 1) {
                 $box["mod"] = imap_utf7_encode(array_pop($fhir));
                 // mod is last part of path
                 $box["parent"] = imap_utf7_encode(implode(".", $fhir));
                 // parent is all previous parts of path
             } else {
                 $box["mod"] = imap_utf7_encode($box["id"]);
                 $box["parent"] = "0";
             }
             $folders[] = $box;
         }
     } else {
         debugLog("GetFolderList: imap_list failed: " . imap_last_error());
     }
     return $folders;
 }
Example #18
0
}
define('CID', false);
define('READ_ONLY_SESSION', true);
require_once '../../../include.php';
ModuleManager::load_modules();
if (!Acl::is_user()) {
    die('not logged');
}
@set_time_limit(0);
$rec = Utils_RecordBrowserCommon::get_record('rc_accounts', $_POST['acc_id']);
if ($rec['epesi_user'] !== Acl::get_user()) {
    die('invalid account id');
}
$port = $rec['security'] == 'ssl' ? 993 : 143;
$server_str = '{' . $rec['server'] . '/imap/readonly/novalidate-cert' . ($rec['security'] ? '/' . $rec['security'] : '') . ':' . $port . '}';
$mailbox = @imap_open(imap_utf7_encode($server_str), imap_utf7_encode($rec['login']), imap_utf7_encode($rec['password']), OP_READONLY || OP_SILENT);
$err = imap_errors();
if (!$mailbox || $err) {
    die(Utils_TooltipCommon::create(__('Connection error'), $err, false));
}
$uns = @imap_search($mailbox, 'UNSEEN ALL');
$unseen = array();
if ($uns) {
    $l = @imap_fetch_overview($mailbox, implode(',', $uns), 0);
    $err = imap_errors();
    if (!$l || $err) {
        die('error reading messages overview');
    }
    foreach ($l as $msg) {
        $from = isset($msg->from) ? $msg->from : '<unknown>';
        $subject = isset($msg->subject) ? $msg->subject : '<no subject>';
 function iso8859Decode($text)
 {
     return imap_utf7_encode($text);
 }
 static function convert_encoding($string, $to, $from = '')
 {
     // Convert string to ISO_8859-1
     if ($from == "UTF-8") {
         $iso_string = utf8_decode($string);
     } else {
         if ($from == "UTF7-IMAP") {
             $iso_string = imap_utf7_decode($string);
         } else {
             $iso_string = $string;
         }
     }
     // Convert ISO_8859-1 string to result coding
     if ($to == "UTF-8") {
         return utf8_encode($iso_string);
     } else {
         if ($to == "UTF7-IMAP") {
             return imap_utf7_encode($iso_string);
         } else {
             return $iso_string;
         }
     }
 }
 function encodeFolderName($_folderName)
 {
     if ($this->mbAvailable) {
         return mb_convert_encoding($_folderName, "UTF7-IMAP", $this->displayCharset);
     }
     // if not
     return imap_utf7_encode($_folderName);
 }
 function updateAccount($_hookValues)
 {
     #_debug_array($_hookValues);
     $username = $_hookValues['account_lid'];
     if (isset($_hookValues['new_passwd'])) {
         $userPassword = $_hookValues['new_passwd'];
     }
     #_debug_array($this->profileData);
     $imapAdminUsername = $this->profileData['imapAdminUsername'];
     $imapAdminPW = $this->profileData['imapAdminPW'];
     $folderNames = array("user.{$username}", "user.{$username}.Trash", "user.{$username}.Sent");
     // create the mailbox
     if ($mbox = @imap_open($this->getMailboxString(), $imapAdminUsername, $imapAdminPW)) {
         // create the users folders
         foreach ($folderNames as $mailBoxName) {
             if (imap_createmailbox($mbox, imap_utf7_encode("{" . $this->profileData['imapServer'] . "}{$mailBoxName}"))) {
                 if (!imap_setacl($mbox, $mailBoxName, $username, "lrswipcd")) {
                     # log error message
                 }
             }
         }
         imap_close($mbox);
     } else {
         return false;
     }
     // we can only subscribe to the folders, if we have the users password
     if (isset($_hookValues['new_passwd'])) {
         if ($mbox = @imap_open($this->getMailboxString(), $username, $userPassword)) {
             imap_subscribe($mbox, $this->getMailboxString('INBOX'));
             imap_subscribe($mbox, $this->getMailboxString('INBOX.Sent'));
             imap_subscribe($mbox, $this->getMailboxString('INBOX.Trash'));
             imap_close($mbox);
         } else {
             # log error message
         }
     }
 }
Example #23
0
 /**
  * Move message to another mailbox
  *
  * @param integer $msgno Message number to move
  * @param string $mbox Mailbox to move message to
  * @return boolean
  */
 function move($msgno, $mbox)
 {
     // Only imap supports moving of mesages
     if ($server_type == "imap") {
         $list = imap_list($this->conn, $this->server, "*");
         if (!in_array($mbox, $list)) {
             if (!imap_createmailbox($this->conn, imap_utf7_encode($this->server . $mbox))) {
                 // $_ENV['api']['sys']->log("Creation of $mbox mailbox failed!","mailer");
             }
         }
         return imap_mail_move($this->conn, $msgno, $mbox);
     } else {
         return imap_delete($this->conn, $msgno);
     }
 }
Example #24
0
 private function GetFolderListFoMode()
 {
     $folders = array();
     $list = @imap_getmailboxes($this->_mbox, $this->_server, "*");
     $this->hasDefaultEventFolder = false;
     $this->hasDefaultContactFolder = false;
     $this->hasDefaultTaskFolder = false;
     if (is_array($list)) {
         //create the
         // reverse list to obtain folders in right order
         $list = array_reverse($list);
         foreach ($list as $val) {
             $box = array();
             // cut off serverstring
             $box["flags"] = 0;
             //$box["id"] = imap_utf7_decode(substr($val->name, strlen($this->_server)));
             $box["id"] = substr($val->name, strlen($this->_server));
             //determine the type en default folder
             $isUser = false;
             $isShared = false;
             $isInbox = false;
             //rerid the annotations
             $this->saveFolderAnnotation($box["id"]);
             $foldertype = $this->readFolderAnnotation($box["id"]);
             $defaultfolder = false;
             //defaultfolder ?
             if ($foldertype == "event.default") {
                 $this->hasDefaultEventFolder = true;
                 $defaultfolder = true;
             }
             if ($foldertype == "contact.default") {
                 $this->hasDefaultContactFolder = true;
                 $defaultfolder = true;
             }
             if ($foldertype == "task.default") {
                 $this->hasDefaultTaskFolder = true;
                 $defaultfolder = true;
             }
             // workspace of the folder;
             if (substr($box["id"], 0, 6) == "shared") {
                 //this is a shared folder
                 $isShared = true;
             }
             if (substr($box["id"], 0, 4) == "user") {
                 //this is a User shared folder
                 $isUser = true;
             }
             if (substr($box["id"], 0, 5) == "INBOX") {
                 $isInbox = true;
             }
             //selection of the folder depending to the setup
             if (!$defaultfolder) {
                 //test annotation
                 $fa = $this->kolabReadFolderParam($box["id"]);
                 //for later use (in getMessage)
                 $this->CacheWriteFolderParam($box["id"], $fa);
                 $fa->setfolder($box["id"]);
                 if (!$fa->isForSync($this->_devid)) {
                     //not set to sync
                     continue;
                 }
             }
             $this->Log("NOTICE SyncFolderList Add folder " . $box["id"]);
             //$box["id"] = imap_utf7_encode( $box["id"]);
             if ($isShared) {
                 $fhir = explode(".", $box["id"]);
                 $box["mod"] = imap_utf7_encode($fhir[1]);
                 $box["parent"] = "shared";
             } elseif ($isUser) {
                 $box["mod"] = imap_utf7_encode(array_pop($fhir));
                 $box["parent"] = "user";
             } else {
                 // explode hierarchies
                 $fhir = explode("/", $box["id"]);
                 $t = count($fhir);
                 if (count($fhir) > 1) {
                     $box["mod"] = imap_utf7_encode(array_pop($fhir));
                     // mod is last part of path
                     $box["parent"] = imap_utf7_encode(implode("/", $fhir));
                     // parent is all previous parts of path
                 } else {
                     $box["mod"] = imap_utf7_encode($box["id"]);
                     $box["parent"] = "0";
                 }
             }
             $folders[] = $box;
         }
     } else {
         debugLog("GetFolderList: imap_list failed: " . imap_last_error());
     }
     return $folders;
 }
Example #25
0
 /**
  * Wrapper for imap_utf7_encode().
  * @param string $mailbox
  * @return string
  */
 public function utf7Encode($mailbox)
 {
     return imap_utf7_encode($mailbox);
 }
 /**
  * encode foldername given by user (convert to UTF7-IMAP)
  * 
  * @param string $_folderName
  * @return string
  */
 public static function encodeFolderName($_folderName)
 {
     if (extension_loaded('mbstring')) {
         $result = mb_convert_encoding($_folderName, "UTF7-IMAP", "utf-8");
     } else {
         if (extension_loaded('imap')) {
             $result = imap_utf7_encode(iconv('utf-8', 'ISO-8859-1', $_folderName));
         } else {
             // fallback
             $result = Tinebase_Helper::replaceSpecialChars($_folderName);
         }
     }
     return $result;
 }
 /**
  * Creates a new mailbox specified by mailbox.
  *
  * @return bool
  */
 public function createMailbox()
 {
     return imap_createmailbox($this->getImapStream(), imap_utf7_encode($this->imapPath));
 }
Example #28
0
 /**
  * Moves a msg to a different folder
  *
  * @param <int> $msgId id number of the msg in current mailbox
  * @param <string> $new_folder new folder's name
  * @param <bool> $create create folder if doesn't exist ?
  * @return <bool> true/false according to success
  */
 public function moveMsg($msgId, $new_folder, $create = true)
 {
     if (!$this->connectIfNeeded()) {
         return false;
     }
     if ($create) {
         @imap_createmailbox($this->connection, imap_utf7_encode('{' . $this->hostname . '}' . $new_folder));
     }
     $success = @imap_mail_move($this->connection, $msgId, $new_folder, CP_UID);
     @imap_expunge($this->connection);
     return $success;
 }
 /**
  * Saves new folders
  * @param string $name Name of new IMAP mailbox
  * @param string $mbox "::" delimited IMAP mailbox path, ie, INBOX.saved.stuff
  * @return bool True on success
  */
 function saveNewFolder($name, $mbox)
 {
     global $sugar_config;
     //Remove Folder cache
     global $sugar_config;
     //unlink("{$this->EmailCachePath}/{$this->id}/folders/folders.php");
     //$mboxImap = $this->getImapMboxFromSugarProprietary($mbox);
     $delimiter = $this->get_stored_options('folderDelimiter');
     if (!$delimiter) {
         $delimiter = '.';
     }
     $newFolder = $mbox . $delimiter . $name;
     $mbox .= $delimiter . str_replace($delimiter, "_", $name);
     $connectString = $this->getConnectString('', $mbox);
     if (imap_createmailbox($this->conn, imap_utf7_encode($connectString))) {
         imap_subscribe($this->conn, imap_utf7_encode($connectString));
         $status = imap_status($this->conn, str_replace("{$delimiter}{$name}", "", $connectString), SA_ALL);
         $this->mailbox = $this->mailbox . "," . $newFolder;
         $this->save();
         $sessionFoldersString = $this->getSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol);
         $sessionFoldersString = $sessionFoldersString . "," . $newFolder;
         $this->setSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol, $sessionFoldersString);
         echo json_encode($status);
         return true;
     } else {
         echo "NOOP: could not create folder";
         $GLOBALS['log']->error("*** ERROR: EMAIL2.0 - could not create IMAP mailbox with path: [ {$connectString} ]");
         return false;
     }
 }
Example #30
0
/**
 * postbyemail_imap()
 *
 * Grabs unread messages from an imap account and saves them as .eml files
 * Passes any new messages found to the postby email function for processing
 * Called by a scheduled task or cronjob
 */
function postbyemail_imap()
{
    global $modSettings;
    // No imap, why bother?
    if (!function_exists('imap_open')) {
        return false;
    }
    // Values used for the connection
    $hostname = !empty($modSettings['maillist_imap_host']) ? $modSettings['maillist_imap_host'] : '';
    $username = !empty($modSettings['maillist_imap_uid']) ? $modSettings['maillist_imap_uid'] : '';
    $password = !empty($modSettings['maillist_imap_pass']) ? $modSettings['maillist_imap_pass'] : '';
    $mailbox = !empty($modSettings['maillist_imap_mailbox']) ? $modSettings['maillist_imap_mailbox'] : 'INBOX';
    $type = !empty($modSettings['maillist_imap_connection']) ? $modSettings['maillist_imap_connection'] : '';
    // I suppose that without these informations we can't do anything.
    if (empty($hostname) || empty($username) || empty($password)) {
        return;
    }
    // Based on the type selected get/set the additional connection details
    $connection = port_type($type);
    $hostname .= strpos($hostname, ':') === false ? ':' . $connection['port'] : '';
    $server = '{' . $hostname . '/' . $connection['protocol'] . $connection['flags'] . '}';
    $mailbox = $server . imap_utf7_encode($mailbox);
    // Connect to the mailbox using the supplied credentials and protocol
    $inbox = @imap_open($mailbox, $username, $password);
    if ($inbox === false) {
        return false;
    }
    // If using gmail, we may need the trash bin name as well
    $trash_bin = '';
    if (!empty($modSettings['maillist_imap_delete']) && strpos($hostname, '.gmail.') !== false) {
        $trash_bin = get_trash_folder($inbox, $server);
    }
    // Grab all unseen emails, return by message ID
    $emails = imap_search($inbox, 'UNSEEN', SE_UID);
    // You've got mail,
    if ($emails) {
        // Initialize Emailpost controller
        require_once CONTROLLERDIR . '/Emailpost.controller.php';
        $controller = new Emailpost_Controller();
        // Make sure we work from the oldest to the newest message
        sort($emails);
        // For every email...
        foreach ($emails as $email_uid) {
            // Get the headers and prefetch the body as well to avoid a second request
            $headers = imap_fetchheader($inbox, $email_uid, FT_PREFETCHTEXT | FT_UID);
            $message = imap_body($inbox, $email_uid, FT_UID);
            // Create the save-as email
            if (!empty($headers) && !empty($message)) {
                $email = $headers . "\n" . $message;
                $controller->action_pbe_post($email);
                // Mark it for deletion?
                if (!empty($modSettings['maillist_imap_delete'])) {
                    // Gmail labels make this more complicated
                    if (strpos($hostname, '.gmail.') !== false) {
                        imap_mail_move($inbox, $email_uid, $trash_bin, CP_UID);
                    }
                    imap_delete($inbox, $email_uid, FT_UID);
                    imap_expunge($inbox);
                }
            }
        }
        // Close the connection
        imap_close($inbox);
        return true;
    } else {
        return false;
    }
}