]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/InboundEmail/InboundEmail.php
Release 6.1.4
[Github/sugarcrm.git] / modules / InboundEmail / InboundEmail.php
1 <?php
2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4  * SugarCRM is a customer relationship management program developed by
5  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6  * 
7  * This program is free software; you can redistribute it and/or modify it under
8  * the terms of the GNU Affero General Public License version 3 as published by the
9  * Free Software Foundation with the addition of the following permission added
10  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
13  * 
14  * This program is distributed in the hope that it will be useful, but WITHOUT
15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
17  * details.
18  * 
19  * You should have received a copy of the GNU Affero General Public License along with
20  * this program; if not, see http://www.gnu.org/licenses or write to the Free
21  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22  * 02110-1301 USA.
23  * 
24  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
26  * 
27  * The interactive user interfaces in modified source and object code versions
28  * of this program must display Appropriate Legal Notices, as required under
29  * Section 5 of the GNU Affero General Public License version 3.
30  * 
31  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32  * these Appropriate Legal Notices must retain the display of the "Powered by
33  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34  * technical reasons, the Appropriate Legal Notices must display the words
35  * "Powered by SugarCRM".
36  ********************************************************************************/
37
38 /*********************************************************************************
39
40  * Description:  TODO: To be written.
41  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
42  * All Rights Reserved.
43  * Contributor(s): ______________________________________..
44  ********************************************************************************/
45
46
47
48 require_once('include/OutboundEmail/OutboundEmail.php');
49 require_once('include/Pear/HTML_Safe/Safe.php');
50
51 function this_callback($str) {
52         foreach($str as $match) {
53                 $ret .= chr(hexdec(str_replace("%","",$match)));
54         }
55         return $ret;
56 }
57
58 /**
59  * Stub for certain interactions;
60  */
61 class temp {
62         var $name;
63 }
64
65 class InboundEmail extends SugarBean {
66         // module specific
67         var $conn;
68         var $purifier; // HTMLPurifier object placeholder
69         var $email;
70
71         // fields
72         var $id;
73         var $deleted;
74         var $date_entered;
75         var $date_modified;
76         var $modified_user_id;
77         var $created_by;
78         var $created_by_name;
79         var $modified_by_name;
80         var $name;
81         var $status;
82         var $server_url;
83         var $email_user;
84         var $email_password;
85         var $port;
86         var $service;
87         var $mailbox;
88         var $mailboxarray;
89         var $delete_seen;
90         var $mailbox_type;
91         var $template_id;
92         var $stored_options;
93         var $group_id;
94         var $is_personal;
95         var $groupfolder_id;
96
97         // email 2.0
98         var $pop3socket;
99         var $outboundInstance; // id to outbound_email instance
100         var $autoImport;
101         var $iconFlagged = "F";
102         var $iconDraft = "D";
103         var $iconAnswered = "A";
104         var $iconDeleted = "del";
105         var $isAutoImport = false;
106         var $smarty;
107         var $attachmentCount = 0;
108         var $tempAttachment = array();
109         var $unsafeChars = array("&", "!", "'", '"', '\\', '/', '<', '>', '|', '$',);
110         var $currentCache;
111         var $defaultSort = 'date';
112         var $defaultDirection = "DESC";
113         var $hrSort = array(
114                         0 => 'flagged',
115                         1 => 'status',
116                         2 => 'from',
117                         3 => 'subj',
118                         4 => 'date',
119                 );
120         var $hrSortLocal = array(
121                         'flagged' => 'flagged',
122                         'status'  => 'answered',
123                         'from'    => 'fromaddr',
124                         'subject' => 'subject',
125                         'date'    => 'senddate',
126                 );
127
128         // default attributes
129         var $transferEncoding                             = array(0 => '7BIT',
130                                                                                                 1 => '8BIT',
131                                                                                                 2 => 'BINARY',
132                                                                                                 3 => 'BASE64',
133                                                                                                 4 => 'QUOTED-PRINTABLE',
134                                                                                                 5 => 'OTHER'
135                                                                                         );
136         // object attributes
137         var $safe; // place holder for HTML_Safe class
138         var $compoundMessageId; // concatenation of messageID and deliveredToEmail
139         var $serverConnectString;
140         var $disable_row_level_security = true;
141         var $InboundEmailCachePath;
142         var $InboundEmailCacheFile                      = 'InboundEmail.cache.php';
143         var $object_name                                        = 'InboundEmail';
144         var $module_dir                                 = 'InboundEmail';
145         var $table_name                                 = 'inbound_email';
146         var $new_schema                                 = true;
147         var $process_save_dates                         = true;
148         var $order_by;
149         var $db;
150         var $dbManager;
151         var $field_defs;
152         var $column_fields;
153         var $required_fields                            = array('name'                  => 'name',
154                                                                                                 'server_url'    => 'server_url',
155                                                                                                 'mailbox'               => 'mailbox',
156                                                                                                 'user'                  => 'user',
157                                                                                                 'port'                  => 'port',
158                                                                                         );
159         var $imageTypes                                 = array("JPG", "JPEG", "GIF");
160         var $inlineImages                                       = array();  // temporary space to store ID of inlined images
161         var $defaultEmailNumAutoreplies24Hours = 10;
162         var $maxEmailNumAutoreplies24Hours = 10;
163         // custom ListView attributes
164         var $mailbox_type_name;
165         var $global_personal_string;
166         // service attributes
167         var $tls;
168         var $ca;
169         var $ssl;
170         var $protocol;
171         var $keyForUsersDefaultIEAccount = 'defaultIEAccount';
172
173         /**
174          * Sole constructor
175          */
176         function InboundEmail() {
177             $this->InboundEmailCachePath = $GLOBALS['sugar_config']['cache_dir'].'modules/InboundEmail';
178                 parent::SugarBean();
179                 if(function_exists("imap_timeout")) {
180                         /*
181                          * 1: Open
182                          * 2: Read
183                          * 3: Write
184                          * 4: Close
185                          */
186                         imap_timeout(1, 60);
187                         imap_timeout(2, 60);
188                         imap_timeout(3, 60);
189                 }
190
191                 $this->safe = new HTML_Safe();
192                 $this->safe->clear();
193                 $this->smarty = new Sugar_Smarty();
194                 $this->overview = new Overview();
195         }
196
197         /**
198          * retrieves I-E bean
199          * @param string id
200          * @return object Bean
201          */
202         function retrieve($id) {
203                 $ret = parent::retrieve($id);
204                 $this->email_password = blowfishDecode(blowfishGetKey('InboundEmail'), $this->email_password);
205                 $this->retrieveMailBoxFolders();
206                 return $ret;
207         }
208
209         /**
210          * wraps SugarBean->save()
211          * @param string ID of saved bean
212          */
213         function save($check_notify=false) {
214                 // generate cache table for email 2.0
215                 $multiDImArray = $this->generateMultiDimArrayFromFlatArray(explode(",", $this->mailbox), $this->retrieveDelimiter());
216                 $raw = $this->generateFlatArrayFromMultiDimArray($multiDImArray, $this->retrieveDelimiter());
217                 sort($raw);
218                 //_pp(explode(",", $this->mailbox));
219                 //_ppd($raw);
220                 $raw = $this->filterMailBoxFromRaw(explode(",", $this->mailbox), $raw);
221                 $this->mailbox = implode(",", $raw);
222                 $this->email_password = blowfishEncode(blowfishGetKey('InboundEmail'), $this->email_password);
223                 $ret = parent::save($check_notify);
224                 return $ret;
225         }
226
227         function filterMailBoxFromRaw($mailboxArray, $rawArray) {
228                 $newArray = array_intersect($mailboxArray, $rawArray);
229                 sort($newArray);
230                 return $newArray;
231         } // fn
232
233         /**
234          * Overrides SugarBean's mark_deleted() to drop the related cache table
235          * @param string $id GUID of I-E instance
236          */
237         function mark_deleted($id) {
238                 parent::mark_deleted($id);
239                 $q = "update inbound_email set groupfolder_id = null WHERE id = $id";
240                 $r = $this->db->query($q);
241                 $this->deleteCache();
242         }
243
244         /**
245          * Mark cached email answered (replied)
246          * @param string $mailid (uid for imap, message_id for pop3)
247          */
248         function mark_answered($mailid, $type = 'smtp') {
249                 switch ($type) {
250                         case 'smtp' :
251                                 $q = "update email_cache set answered = 1 WHERE imap_uid = $mailid and ie_id = '$this->id'";
252                                 $this->db->query($q);
253                                 break;
254                         case 'pop3' :
255                                 $q = "update email_cache set answered = 1 WHERE message_id = '$mailid' and ie_id = '$this->id'";
256                                 $this->db->query($q);
257                                 break;
258                 }
259         }
260
261         /**
262          * Renames an IMAP mailbox
263          * @param string $newName
264          */
265         function renameFolder($oldName, $newName) {
266                 //$this->mailbox = "INBOX"
267                 $this->connectMailserver();
268         $oldConnect = $this->getConnectString('', $oldName);
269         $newConnect = $this->getConnectString('', $newName);
270                 if(!imap_renamemailbox($this->conn, $oldConnect , $newConnect)) {
271                         $GLOBALS['log']->debug("***INBOUNDEMAIL: failed to rename mailbox [ {$oldConnect} ] to [ {$newConnect} ]");
272                 } else {
273                 $this->mailbox = str_replace($oldName, $newName, $this->mailbox);
274                 $this->save();
275                 $sessionFoldersString  = $this->getSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol);
276                 $sessionFoldersString = str_replace($oldName, $newName, $sessionFoldersString);
277                         $this->setSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol, $sessionFoldersString);
278
279                 }
280         }
281
282         ///////////////////////////////////////////////////////////////////////////
283         ////    CUSTOM LOGIC HOOKS
284         /**
285          * Called from $this->getMessageText()
286          * Allows upgrade-safe custom processing of message text.
287          *
288          * To use:
289          * 1. Create a directory path: ./custom/modules/InboundEmail if it does not exist
290          * 2. Create a file in the ./custom/InboundEmail/ folder called "getMessageText.php"
291          * 3. Define a function named "custom_getMessageText()" that takes a string as an argument and returns a string
292          *
293          * @param string $msgPart
294          * @return string
295          */
296         function customGetMessageText($msgPart) {
297                 $custom = "custom/modules/InboundEmail/getMessageText.php";
298
299                 if(file_exists($custom)) {
300                         include_once($custom);
301
302                         if(function_exists("custom_getMessageText")) {
303                                 $GLOBALS['log']->debug("*** INBOUND EMAIL-CUSTOM_LOGIC: calling custom_getMessageText()");
304                                 $msgPart = custom_getMessageText($msgPart);
305                         }
306                 }
307
308                 return $msgPart;
309         }
310         ////    END CUSTOM LOGIC HOOKS
311         ///////////////////////////////////////////////////////////////////////////
312
313
314
315         ///////////////////////////////////////////////////////////////////////////
316         ////    EMAIL 2.0 SPECIFIC
317         /**
318          * constructs a nicely formatted version of raw source
319          * @param int $uid UID of email
320          * @return string
321          */
322         function getFormattedRawSource($uid) {
323                 global $app_strings;
324
325                 //if($this->protocol == 'pop3') {
326                 //$raw = $app_strings['LBL_EMAIL_VIEW_UNSUPPORTED'];
327                 //} else {
328                         $raw;
329                         if (empty($this->id)) {
330                                 $q = "SELECT raw_source FROM emails_text WHERE email_id = '{$uid}'";
331                                 $r = $this->db->query($q);
332                                 $a = $this->db->fetchByAssoc($r);
333                                 $ret = array();
334                                 $raw = utf8_encode($a['raw_source']);
335                                 if (empty($raw)) {
336                                         $raw = $app_strings['LBL_EMAIL_ERROR_VIEW_RAW_SOURCE'];
337                                 }
338                         } else {
339                                 if ($this->isPop3Protocol()) {
340                                         $uid = $this->getCorrectMessageNoForPop3($uid);
341                                 }
342                                 $raw  = imap_fetchheader($this->conn, $uid, FT_UID+FT_PREFETCHTEXT);
343                                 $raw .= utf8_encode(imap_body($this->conn, $uid, FT_UID));
344                         } // else
345                         $raw = to_html($raw);
346                         $raw = nl2br($raw);
347                 //}
348
349                 return $raw;
350         }
351
352         /**
353          * constructs a nicely formatted version of email headers.
354          * @param int $uid
355          * @return string
356          */
357         function getFormattedHeaders($uid) {
358                 global $app_strings;
359
360                 //if($this->protocol == 'pop3') {
361                 //      $header = $app_strings['LBL_EMAIL_VIEW_UNSUPPORTED'];
362                 //} else {
363                         if ($this->isPop3Protocol()) {
364                                 $uid = $this->getCorrectMessageNoForPop3($uid);
365                         }
366                         $headers = imap_fetchheader($this->conn, $uid, FT_UID);
367
368                         $lines = explode("\n", $headers);
369
370                         $header = "<table cellspacing='0' cellpadding='2' border='0' width='100%'>";
371
372                         foreach($lines as $line) {
373                                 $line = trim($line);
374
375                                 if(!empty($line)) {
376                                         $key = trim(substr($line, 0, strpos($line, ":")));
377                                         $value = trim(substr($line, strpos($line, ":") + 1));
378                                         $value = to_html($value);
379
380                                         $header .= "<tr>";
381                                         $header .= "<td class='displayEmailLabel' NOWRAP><b>{$key}</b>&nbsp;</td>";
382                                         $header .= "<td class='displayEmailValueWhite'>{$value}&nbsp;</td>";
383                                         $header .= "</tr>";
384                                 }
385                         }
386
387                         $header .= "</table>";
388                 //}
389                 return $header;
390         }
391
392         /**
393          * Empties Trash folders
394          */
395         function emptyTrash() {
396                 global $sugar_config;
397
398                 $this->mailbox = $this->get_stored_options("trashFolder");
399                 if (empty($this->mailbox)) {
400                         $this->mailbox = 'INBOX.Trash';
401                 }
402                 $this->connectMailserver();
403
404                 $uids = imap_search($this->conn, "ALL", SE_UID);
405
406                 foreach($uids as $uid) {
407                         if(!imap_delete($this->conn, $uid, FT_UID)) {
408                                 $lastError = imap_last_error();
409                                 $GLOBALS['log']->warn("INBOUNDEMAIL: emptyTrash() Could not delete message [ {$uid} ] from [ {$this->mailbox} ].  IMAP_ERROR [ {$lastError} ]");
410                         }
411                 }
412
413                 // remove local cache file
414                 $q = "DELETE FROM email_cache WHERE mbox = '{$this->mailbox}' AND ie_id = '{$this->id}'";
415                 $r = $this->db->query($q);
416         }
417
418         /**
419          * Fetches a timestamp
420          */
421         function getCacheTimestamp($mbox) {
422                 $key = $this->db->quote("{$this->id}_{$mbox}");
423                 $q = "SELECT ie_timestamp FROM inbound_email_cache_ts WHERE id = '{$key}'";
424                 $r = $this->db->query($q);
425                 $a = $this->db->fetchByAssoc($r);
426
427                 if(empty($a)) {
428                         return -1;
429                 }
430                 return $a['ie_timestamp'];
431         }
432
433         /**
434          * sets the cache timestamp
435          * @param string mbox
436          */
437         function setCacheTimestamp($mbox) {
438                 $key = $this->db->quote("{$this->id}_{$mbox}");
439                 $ts = mktime();
440                 $tsOld = $this->getCacheTimestamp($mbox);
441
442                 if($tsOld < 0) {
443                         $q = "INSERT INTO inbound_email_cache_ts (id, ie_timestamp) VALUES ('{$key}', {$ts})";
444                 } else {
445                         $q = "UPDATE inbound_email_cache_ts SET ie_timestamp = {$ts} WHERE id = '{$key}'";
446                 }
447
448                 $r = $this->db->query($q, true);
449                 $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: setting timestamp query [ {$q} ]");
450         }
451
452
453         /**
454          * Gets a count of all rows that are flagged seen = 0
455          * @param string $mbox
456          * @return int
457          */
458         function getCacheUnreadCount($mbox) {
459                 $q = "SELECT count(*) c FROM email_cache WHERE mbox = '{$mbox}' AND seen = 0 AND ie_id = '{$this->id}'";
460                 $r = $this->db->query($q);
461                 $a = $this->db->fetchByAssoc($r);
462
463                 return $a['c'];
464         }
465
466         /**
467          * Returns total number of emails for a mailbox
468          * @param string mbox
469          * @return int
470          */
471         function getCacheCount($mbox) {
472                 $q = "SELECT count(*) c FROM email_cache WHERE mbox = '{$mbox}' AND ie_id = '{$this->id}'";
473                 $r = $this->db->query($q);
474                 $a = $this->db->fetchByAssoc($r);
475
476                 return $a['c'];
477         }
478
479     function getCacheUnread($mbox) {
480         $q = "SELECT count(*) c FROM email_cache WHERE mbox = '{$mbox}' AND ie_id = '{$this->id}' AND seen = '0'";
481         $r = $this->db->query($q);
482         $a = $this->db->fetchByAssoc($r);
483
484         return $a['c'];
485     }
486
487
488         /**
489          * Deletes all rows for a given instance
490          */
491         function deleteCache() {
492                 $q = "DELETE FROM email_cache WHERE ie_id = '{$this->id}'";
493
494                 $GLOBALS['log']->info("INBOUNDEMAIL: deleting cache using query [ {$q} ]");
495
496                 $r = $this->db->query($q);
497         }
498
499         /**
500          * Deletes all the pop3 data which has been deleted from server
501          */
502         function deletePop3Cache() {
503                 global $sugar_config;
504                 $UIDLs = $this->pop3_getUIDL();
505                 $cacheUIDLs = $this->pop3_getCacheUidls();
506                 foreach($cacheUIDLs as $msgNo => $msgId) {
507                         if (!in_array($msgId, $UIDLs)) {
508                                 $md5msgIds = md5($msgId);
509                                 $file = "{$sugar_config['cache_dir']}modules/Emails/{$this->id}/messages/INBOX{$md5msgIds}.PHP";
510                                 $GLOBALS['log']->debug("INBOUNDEMAIL: deleting file [ {$file} ] ");
511                                 if(file_exists($file)) {
512                                         if(!unlink($file)) {
513                                                 $GLOBALS['log']->debug("INBOUNDEMAIL: Could not delete [ {$file} ] ");
514                                         } // if
515                                 } // if
516                                 $q = "DELETE from email_cache where imap_uid = {$msgNo} AND msgno = {$msgNo} AND ie_id = '{$this->id}' AND message_id = '{$msgId}'";
517                                 $r = $this->db->query($q);
518                         } // if
519                 } // for
520         } // fn
521
522         /**
523          * Retrieves cached headers
524          * @return array
525          */
526         function getCacheValueForUIDs($mbox, $UIDs) {
527                 if (!is_array($UIDs) || empty($UIDs)) {
528                         return array();
529                 }
530
531                 $q = "SELECT * FROM email_cache WHERE ie_id = '{$this->id}' AND mbox = '{$mbox}' AND ";
532                 $startIndex = 0;
533                 $endIndex = 5;
534
535                 $slicedArray = array_slice($UIDs, $startIndex ,$endIndex);
536                 $columnName = ($this->isPop3Protocol() ? "message_id" : "imap_uid");
537                 $ret = array(
538                         'timestamp'     => $this->getCacheTimestamp($mbox),
539                         'uids'          => array(),
540                         'retArr'        => array(),
541                 );
542                 while (!empty($slicedArray)) {
543                         $messageIdString = implode(',', $slicedArray);
544                         $GLOBALS['log']->debug("sliced array = {$messageIdString}");
545                         $extraWhere = "{$columnName} IN (";
546                         $i = 0;
547                         foreach($slicedArray as $UID) {
548                                 if($i != 0) {
549                                         $extraWhere = $extraWhere . ",";
550                                 } // if
551                                 $i++;
552                                 $extraWhere = "{$extraWhere} '{$UID}'";
553                         } // foreach
554                         $newQuery = $q . $extraWhere . ")";
555                         $r = $this->db->query($newQuery);
556
557                         while($a = $this->db->fetchByAssoc($r)) {
558                                 if (isset($a['uid'])) {
559                                         if ($this->isPop3Protocol()) {
560                                                 $ret['uids'][] = $a['message_id'];
561                                         } else {
562                                         $ret['uids'][] = $a['uid'];
563                                         }
564                                 }
565
566                                 $overview = new Overview();
567
568                                 foreach($a as $k => $v) {
569                                         $k=strtolower($k);
570                                         switch($k) {
571                                                 case "imap_uid":
572                                                         $overview->imap_uid = $v;
573                                                         if ($this->isPop3Protocol()) {
574                                                                 $overview->uid = $a['message_id'];
575                                                         } else {
576                                                                 $overview->uid = $v;
577                                                         }
578                                                 break;
579                                                 case "toaddr":
580                                                         $overview->to = from_html($v);
581                                                 break;
582
583                                                 case "fromaddr":
584                                                         $overview->from = from_html($v);
585                                                 break;
586
587                                                 case "mailsize":
588                                                         $overview->size = $v;
589                                                 break;
590
591                                                 case "senddate":
592                                                         //$overview->date = strtotime(date('r', strtotime($v)));
593                                                         $overview->date = $v;
594                                                 break;
595
596                                                 default:
597                                                         $overview->$k = from_html($v);
598                                                 break;
599                                         } // switch
600                                 } // foreach
601                                 $ret['retArr'][] = $overview;
602                         } // while
603                         $startIndex = $startIndex + $endIndex;
604                         $slicedArray = array_slice($UIDs, $startIndex ,$endIndex);
605                         $messageIdString = implode(',', $slicedArray);
606                         $GLOBALS['log']->debug("sliced array = {$messageIdString}");
607                 } // while
608                 return $ret;
609         }
610
611         /**
612          * Retrieves cached headers
613          * @return array
614          */
615         function getCacheValue($mbox, $limit = 20, $page = 1, $sort='', $direction='') {
616                 // try optimizing this call as we don't want repeat queries
617                 if(!empty($this->currentCache)) {
618                         return $this->currentCache;
619                 }
620
621                 $sort = (empty($sort)) ? $this->defaultSort : $sort;
622                 $direction = (empty($direction)) ? $this->defaultDirection : $direction;
623                 $order = " ORDER BY {$this->hrSortLocal[$sort]} {$direction}";
624
625                 $q = "SELECT * FROM email_cache WHERE ie_id = '{$this->id}' AND mbox = '{$mbox}' {$order}";
626
627                 if(!empty($limit)) {
628                         $start = ( $page - 1 ) * $limit;
629                         $r = $this->db->limitQuery($q, $start, $limit);
630                 } else {
631                         $r = $this->db->query($q);
632                 }
633
634                 $ret = array(
635                         'timestamp'     => $this->getCacheTimestamp($mbox),
636                         'uids'          => array(),
637                         'retArr'        => array(),
638                 );
639
640                 while($a = $this->db->fetchByAssoc($r)) {
641                         if (isset($a['uid'])) {
642                                 if ($this->isPop3Protocol()) {
643                                         $ret['uids'][] = $a['message_id'];
644                                 } else {
645                                 $ret['uids'][] = $a['uid'];
646                                 }
647                         }
648
649                         $overview = new Overview();
650
651                         foreach($a as $k => $v) {
652                                 $k=strtolower($k);
653                                 switch($k) {
654                                         case "imap_uid":
655                                                 $overview->imap_uid = $v;
656                                                 if ($this->isPop3Protocol()) {
657                                                         $overview->uid = $a['message_id'];
658                                                 } else {
659                                                         $overview->uid = $v;
660                                                 }
661                                         break;
662                                         case "toaddr":
663                                                 $overview->to = from_html($v);
664                                         break;
665
666                                         case "fromaddr":
667                                                 $overview->from = from_html($v);
668                                         break;
669
670                                         case "mailsize":
671                                                 $overview->size = $v;
672                                         break;
673
674                                         case "senddate":
675                                                 //$overview->date = strtotime(date('r', strtotime($v)));
676                                                 $overview->date = $v;
677                                         break;
678
679                                         default:
680                                                 $overview->$k = from_html($v);
681                                         break;
682                                 }
683                         }
684                         $ret['retArr'][] = $overview;
685                 }
686
687                 $this->currentCache = $ret;
688
689                 return $ret;
690         }
691
692         /**
693          * Sets cache values
694          */
695         function setCacheValue($mbox, $insert, $update=array(), $remove=array()) {
696                 if(empty($mbox)) {
697                         return;
698                 }
699                 global $timedate;
700
701
702                 // reset in-memory cache
703                 $this->currentCache = null;
704
705                 $table = 'email_cache';
706                 $where = "WHERE ie_id = '{$this->id}' AND mbox = '{$mbox}'";
707
708                 // handle removed rows
709                 if(!empty($remove)) {
710                         $removeIds = '';
711                         foreach($remove as $overview) {
712                                 if(!empty($removeIds)) {
713                                         $removeIds .= ",";
714                                 }
715
716                                 $removeIds .= "'{$overview->imap_uid}'";
717                         }
718
719                         $q = "DELETE FROM {$table} {$where} AND imap_uid IN ({$removeIds})";
720
721                         $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: delete query [ {$q} ]");
722
723                         $r = $this->db->query($q, true, $q);
724                 }
725
726                 // handle insert rows
727                 if(!empty($insert)) {
728                         $q = "SELECT imap_uid FROM {$table} {$where}";
729                         $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: filter UIDs query [ {$q} ]");
730                         $r = $this->db->query($q);
731                         $uids = array();
732
733                         while($a = $this->db->fetchByAssoc($r)) {
734                                 $uids[] = $a['imap_uid'];
735                         }
736                         $count = count($uids);
737                         $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: found [ {$count} ] UIDs to filter against");
738
739                         $tmp = '';
740                         foreach($uids as $uid) {
741                                 if(!empty($tmp))
742                                         $tmp .= ", ";
743                                 $tmp .= "{$uid}";
744                         }
745                         $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: filter UIDs: [ {$tmp} ]");
746
747                         $cols = "";
748
749                         foreach($this->overview->fieldDefs as $colDef) {
750                                 if(!empty($cols))
751                                         $cols .= ",";
752
753                                 $cols .= "{$colDef['name']}";
754                         }
755                         foreach($insert as $overview) {
756                                 if(in_array($overview->imap_uid, $uids)) {
757                                         $update[] = $overview;
758                                         continue;
759                                 }
760
761                                 $values = '';
762
763                                 foreach($this->overview->fieldDefs as $colDef) {
764                                         if(!empty($values)) {
765                                                 $values .= ", ";
766                                         }
767
768                                         // trim values for Oracle/MSSql
769                                         if(     isset($colDef['len']) && !empty($colDef['len']) &&
770                                                 isset($colDef['type']) && !empty($colDef['type']) &&
771                                                 $colDef['type'] == 'varchar'
772                                         ) {
773                                                 $overview->$colDef['name'] = substr($overview->$colDef['name'], 0, $colDef['len']);
774                                         }
775
776                                         switch($colDef['name']) {
777                                                 case "imap_uid":
778                                                         if(isset($overview->uid) && !empty($overview->uid)) {
779                                                                 $this->imap_uid = $overview->uid;
780                                                         }
781                                                         $values .= "'{$this->imap_uid}'";
782                                                 break;
783
784                                                 case "ie_id":
785                                                         $values .= "'{$this->id}'";
786                                                 break;
787
788                                                 case "toaddr":
789                                                         $values .= "'".$this->db->helper->escape_quote($overview->to)."'";
790                                                 break;
791
792                                                 case "fromaddr":
793                                                         $values .= "'".$this->db->helper->escape_quote($overview->from)."'";
794                                                 break;
795
796                                                 case "message_id" :
797                                                         $values .= "'".$this->db->helper->escape_quote($overview->message_id)."'";
798                                                 break;
799
800                                                 case "mailsize":
801                                                         $values .= $overview->size;
802                                                 break;
803
804                                                 case "senddate":
805                                                         $conv=$this->getUnixHeaderDate($overview->date);
806                                                         if (!empty($conv)) {
807                                                                 $values .= "'" . date($timedate->get_db_date_time_format(), $conv) ."'";
808                                                         } else {
809                                                                 $values .= "NULL";
810                                                         }
811                                                 break;
812
813                                                 case "mbox":
814                                                         $values .= "'{$mbox}'";
815                                                 break;
816
817                                                 default:
818                                                         $overview->$colDef['name'] = from_html($overview->$colDef['name']);
819                                                         $overview->$colDef['name'] = $this->cleanContent($overview->$colDef['name']);
820                                                         $values .= "'".$this->db->helper->escape_quote($overview->$colDef['name'])."'";
821                                                 break;
822                                         }
823                                 }
824
825                                 $q = "INSERT INTO {$table} ({$cols}) VALUES ({$values})";
826                                 $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: insert query [ {$q} ]");
827                                 $r = $this->db->query($q, true, $q);
828                         }
829                 }
830
831                 // handle update rows
832                 if(!empty($update)) {
833                         $cols = "";
834                         foreach($this->overview->fieldDefs as $colDef) {
835                                 if(!empty($cols))
836                                         $cols .= ",";
837
838                                 $cols .= "{$colDef['name']}";
839                         }
840
841                         foreach($update as $overview) {
842                                 $q = "UPDATE {$table} SET ";
843
844                                 $set = '';
845                                 foreach($this->overview->fieldDefs as $colDef) {
846
847                                         switch($colDef['name']) {
848                                                 case "toaddr":
849                                                         //$set .= "toaddr = '".$this->db->helper->escape_quote($overview->to)."'";
850                                                 break;
851
852                                                 case "fromaddr":
853                                                         //$set .= "fromaddr = '".$this->db->helper->escape_quote($overview->from)."'";
854                                                 break;
855
856                                                 case "mailsize":
857                                                         //$set .= "mailsize = {$overview->size}";
858                                                 break;
859
860                                                 case "senddate":
861                                                         //$set .= "senddate = '".date("Y-m-d H:i:s", $overview->date)."'";
862                                                 break;
863
864                                                 case "mbox":
865                                                         //$set .= "mbox = '{$mbox}'";
866                                                 break;
867
868                                                 default:
869                                                         if(!empty($set)) {
870                                                                 $set .= ",";
871                                                         }
872                                                         $set .= "{$colDef['name']} = '".$this->db->helper->escape_quote($overview->$colDef['name'])."'";
873                                                 break;
874                                         }
875                                 }
876
877                                 $q .= $set . " WHERE ie_id = '{$this->id}' AND mbox = '{$overview->mbox}' AND imap_uid = '{$overview->imap_uid}'";
878                                 $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: update query [ {$q} ]");
879                                 $r = $this->db->query($q, true, $q);
880                         }
881                 }
882
883         }
884
885         /**
886          * Opens a socket connection to the pop3 server
887          * @return bool
888          */
889         function pop3_open() {
890                 if(!is_resource($this->pop3socket)) {
891                         $GLOBALS['log']->info("*** INBOUNDEMAIL: opening socket connection");
892                         $exServ = explode('::', $this->service);
893                         $socket  = ($exServ[2] == 'ssl') ? "ssl://" : "tcp://";
894                         $socket .= $this->server_url;
895                         $this->pop3socket = fsockopen($socket, $this->port);
896                 } else {
897                         $GLOBALS['log']->info("*** INBOUNDEMAIL: REUSING socket connection");
898                         return true;
899                 }
900
901                 if(!is_resource($this->pop3socket)) {
902                         $GLOBALS['log']->debug("*** INBOUNDEMAIL: unable to open socket connection");
903                         return false;
904                 }
905
906                 // clear buffer
907                 $ret = trim(fgets($this->pop3socket, 1024));
908                 $GLOBALS['log']->info("*** INBOUNDEMAIL: got socket connection [ {$ret} ]");
909                 return true;
910         }
911
912         /**
913          * Closes connections and runs clean-up routines
914          */
915         function pop3_cleanUp() {
916                 $GLOBALS['log']->info("*** INBOUNDEMAIL: cleaning up socket connection");
917                 fputs($this->pop3socket, "QUIT\r\n");
918                 $buf = fgets($this->pop3socket, 1024);
919                 fclose($this->pop3socket);
920         }
921
922         /**
923          * sends a command down to the POP3 server
924          * @param string command
925          * @param string args
926          * @param bool return
927          * @return string
928          */
929         function pop3_sendCommand($command, $args='', $return=true) {
930                 $command .= " {$args}";
931                 $command = trim($command);
932                 $GLOBALS['log']->info("*** INBOUNDEMAIL: pop3_sendCommand() SEND [ {$command} ]");
933                 $command .= "\r\n";
934
935                 fputs($this->pop3socket, $command);
936
937                 if($return) {
938                         $ret = trim(fgets($this->pop3socket, 1024));
939                         $GLOBALS['log']->info("*** INBOUNDEMAIL: pop3_sendCommand() RECEIVE [ {$ret} ]");
940                         return $ret;
941                 }
942         }
943
944         function getPop3NewMessagesToDownload() {
945                 $pop3UIDL = $this->pop3_getUIDL();
946                 $cacheUIDLs = $this->pop3_getCacheUidls();
947                 // new email cache values we should deal with
948                 $diff = array_diff_assoc($pop3UIDL, $cacheUIDLs);
949                 // this is msgNo to UIDL array
950                 $diff = $this->pop3_shiftCache($diff, $cacheUIDLs);
951                 // get all the keys which are msgnos;
952                 return array_keys($diff);
953         }
954
955         function getPop3NewMessagesToDownloadForCron() {
956                 $pop3UIDL = $this->pop3_getUIDL();
957                 $cacheUIDLs = $this->pop3_getCacheUidls();
958                 // new email cache values we should deal with
959                 $diff = array_diff_assoc($pop3UIDL, $cacheUIDLs);
960                 // this is msgNo to UIDL array
961                 $diff = $this->pop3_shiftCache($diff, $cacheUIDLs);
962                 // insert data into email_cache
963                 if ($this->groupfolder_id != null && $this->groupfolder_id != "" && $this->isPop3Protocol()) {
964                         $searchResults = array_keys($diff);
965                         $concatResults = implode(",", $searchResults);
966                         if ($this->connectMailserver() == 'true') {
967                                 $fetchedOverviews = imap_fetch_overview($this->conn, $concatResults);
968                                 // clean up cache entry
969                                 foreach($fetchedOverviews as $k => $overview) {
970                                         $overview->message_id = trim($diff[$overview->msgno]);
971                                         $fetchedOverviews[$k] = $overview;
972                                 }
973                                 $this->updateOverviewCacheFile($fetchedOverviews);
974                         }
975                 } // if
976                 return $diff;
977         }
978
979         /**
980          * This method returns all the UIDL for this account. This should be called if the protocol is pop3
981          * @return array od messageno to UIDL array
982          */
983         function pop3_getUIDL() {
984                 $UIDLs = array();
985                 if($this->pop3_open()) {
986                         // authenticate
987                         $this->pop3_sendCommand("USER", $this->email_user);
988                         $this->pop3_sendCommand("PASS", $this->email_password);
989
990                         // get UIDLs
991                         $this->pop3_sendCommand("UIDL", '', false); // leave socket buffer alone until the while()
992                         fgets($this->pop3socket, 1024); // handle "OK+";
993                         $UIDLs = array();
994
995                         $buf = '!';
996
997                         if(is_resource($this->pop3socket)) {
998                                 while(!feof($this->pop3socket)) {
999                                         $buf = fgets($this->pop3socket, 1024); // 8kb max buffer - shouldn't be more than 80 chars via pop3...
1000                                         //_pp(trim($buf));
1001
1002                                         if(trim($buf) == '.') {
1003                                                 $GLOBALS['log']->debug("*** GOT '.'");
1004                                                 break;
1005                                         }
1006
1007                                         // format is [msgNo] [UIDL]
1008                                         $exUidl = explode(" ", $buf);
1009                                         $UIDLs[$exUidl[0]] = trim($exUidl[1]);
1010                                 } // while
1011                         } // if
1012                         $this->pop3_cleanUp();
1013                 } // if
1014                 return $UIDLs;
1015         } // fn
1016
1017         /**
1018          * Special handler for POP3 boxes.  Standard IMAP commands are useless.
1019          * This will fetch only partial emails for POP3 and hence needs to be call again and again based on status it returns
1020          */
1021         function pop3_checkPartialEmail($synch = false) {
1022                 require_once('include/utils/array_utils.php');
1023                 global $current_user;
1024                 global $sugar_config;
1025
1026                 $cacheDataExists = false;
1027                 $diff = array();
1028                 $results = array();
1029                 $cacheFilePath = clean_path("{$sugar_config['cache_dir']}modules/Emails/{$this->id}/folders/MsgNOToUIDLData.php");
1030                 if(file_exists($cacheFilePath)) {
1031                         $cacheDataExists = true;
1032                         if($fh = @fopen($cacheFilePath, "rb")) {
1033                                 $data = "";
1034                                 $chunksize = 1*(1024*1024); // how many bytes per chunk
1035                                 while(!feof($fh)) {
1036                                         $buf = fgets($fh, $chunksize); // 8kb max buffer - shouldn't be more than 80 chars via pop3...
1037                                         $data = $data . $buf;
1038                                 flush();
1039                                 } // while
1040                                 fclose($fh);
1041                                 $diff = unserialize($data);
1042                                 if (!empty($diff)) {
1043                                         if (count($diff)> 50) {
1044                                 $newDiff = array_slice($diff, 50, count($diff), true);
1045                                         } else {
1046                                                 $newDiff=array();
1047                                         }
1048                         $results = array_slice(array_keys($diff), 0 ,50);
1049                                         $data = serialize($newDiff);
1050                                     if($fh = @fopen($cacheFilePath, "w")) {
1051                                         fputs($fh, $data);
1052                                         fclose($fh);
1053                                     } // if
1054                                 }
1055                         } // if
1056                 } // if
1057                 if (!$cacheDataExists) {
1058                         if ($synch) {
1059                             $this->deletePop3Cache();
1060                         }
1061                         $UIDLs = $this->pop3_getUIDL();
1062                         if(count($UIDLs) > 0) {
1063                                 // get cached UIDLs
1064                                 $cacheUIDLs = $this->pop3_getCacheUidls();
1065
1066                                 // new email cache values we should deal with
1067                                 $diff = array_diff_assoc($UIDLs, $cacheUIDLs);
1068                                 $diff = $this->pop3_shiftCache($diff, $cacheUIDLs);
1069                                 require_once('modules/Emails/EmailUI.php');
1070                                 EmailUI::preflightEmailCache("{$sugar_config['cache_dir']}modules/Emails/{$this->id}");
1071
1072                                 if (count($diff)> 50) {
1073                         $newDiff = array_slice($diff, 50, count($diff), true);
1074                                 } else {
1075                                         $newDiff=array();
1076                                 }
1077
1078                                 $results = array_slice(array_keys($diff), 0 ,50);
1079                                 $data = serialize($newDiff);
1080                             if($fh = @fopen($cacheFilePath, "w")) {
1081                                 fputs($fh, $data);
1082                                 fclose($fh);
1083                             } // if
1084                         } else {
1085                                 $GLOBALS['log']->debug("*** INBOUNDEMAIL: could not open socket connection to POP3 server");
1086                                 return "could not open socket connection to POP3 server";
1087                         } // else
1088                 } // if
1089
1090                 // build up msgNo request
1091                 if(count($diff) > 0) {
1092                         // remove dirty cache entries
1093                         $startingNo = 0;
1094                         if (isset($_REQUEST['currentCount']) && $_REQUEST['currentCount'] > -1) {
1095                              $startingNo = $_REQUEST['currentCount'];
1096                         }
1097
1098                         $this->mailbox = 'INBOX';
1099                         $this->connectMailserver();
1100                         //$searchResults = array_keys($diff);
1101                         //$fetchedOverviews = array();
1102                         //$chunkArraySerachResults = array_chunk($searchResults, 50);
1103                         $concatResults = implode(",", $results);
1104                         $GLOBALS['log']->info('$$$$ '.$concatResults);
1105                         $GLOBALS['log']->info("[EMAIL] Start POP3 fetch overview on mailbox [{$this->mailbox}] for user [{$current_user->user_name}] on 50 data");
1106                         $fetchedOverviews = imap_fetch_overview($this->conn, $concatResults);
1107                         $GLOBALS['log']->info("[EMAIL] End POP3 fetch overview on mailbox [{$this->mailbox}] for user [{$current_user->user_name}] on "
1108                         . sizeof($fetchedOverviews) . " data");
1109
1110                         // clean up cache entry
1111                         foreach($fetchedOverviews as $k => $overview) {
1112                                 $overview->message_id = trim($diff[$overview->msgno]);
1113                                 $fetchedOverviews[$k] = $overview;
1114                         }
1115
1116                         $GLOBALS['log']->info("[EMAIL] Start updating overview cache for pop3 mailbox [{$this->mailbox}] for user [{$current_user->user_name}]");
1117                         $this->updateOverviewCacheFile($fetchedOverviews);
1118                         $GLOBALS['log']->info("[EMAIL] Start updating overview cache for pop3 mailbox [{$this->mailbox}] for user [{$current_user->user_name}]");
1119                         return array('status' => "In Progress", 'mbox' => $this->mailbox, 'count'=> (count($results) + $startingNo), 'totalcount' => count($diff), 'ieid' => $this->id);
1120                 } // if
1121                 unlink($cacheFilePath);
1122                 return  array('status' => "done");
1123         }
1124
1125
1126         /**
1127          * Special handler for POP3 boxes.  Standard IMAP commands are useless.
1128          */
1129         function pop3_checkEmail() {
1130                 if($this->pop3_open()) {
1131                         // authenticate
1132                         $this->pop3_sendCommand("USER", $this->email_user);
1133                         $this->pop3_sendCommand("PASS", $this->email_password);
1134
1135                         // get UIDLs
1136                         $this->pop3_sendCommand("UIDL", '', false); // leave socket buffer alone until the while()
1137                         fgets($this->pop3socket, 1024); // handle "OK+";
1138                         $UIDLs = array();
1139
1140                         $buf = '!';
1141
1142                         if(is_resource($this->pop3socket)) {
1143                                 while(!feof($this->pop3socket)) {
1144                                         $buf = fgets($this->pop3socket, 1024); // 8kb max buffer - shouldn't be more than 80 chars via pop3...
1145                                         //_pp(trim($buf));
1146
1147                                         if(trim($buf) == '.') {
1148                                                 $GLOBALS['log']->debug("*** GOT '.'");
1149                                                 break;
1150                                         }
1151
1152                                         // format is [msgNo] [UIDL]
1153                                         $exUidl = explode(" ", $buf);
1154                                         $UIDLs[$exUidl[0]] = trim($exUidl[1]);
1155                                 }
1156                         }
1157
1158                         $this->pop3_cleanUp();
1159
1160                         // get cached UIDLs
1161                         $cacheUIDLs = $this->pop3_getCacheUidls();
1162 //                      _pp($UIDLs);_pp($cacheUIDLs);
1163
1164                         // new email cache values we should deal with
1165                         $diff = array_diff_assoc($UIDLs, $cacheUIDLs);
1166
1167                         // remove dirty cache entries
1168                         $diff = $this->pop3_shiftCache($diff, $cacheUIDLs);
1169
1170                         // build up msgNo request
1171                         if(!empty($diff)) {
1172                                 $this->mailbox = 'INBOX';
1173                                 $this->connectMailserver();
1174                                 $searchResults = array_keys($diff);
1175                                 $concatResults = implode(",", $searchResults);
1176                                 $fetchedOverviews = imap_fetch_overview($this->conn, $concatResults);
1177
1178                                 // clean up cache entry
1179                                 foreach($fetchedOverviews as $k => $overview) {
1180                                         $overview->message_id = trim($diff[$overview->msgno]);
1181                                         $fetchedOverviews[$k] = $overview;
1182                                 }
1183
1184                                 $this->updateOverviewCacheFile($fetchedOverviews);
1185                         }
1186                 } else {
1187                         $GLOBALS['log']->debug("*** INBOUNDEMAIL: could not open socket connection to POP3 server");
1188                         return false;
1189                 }
1190         }
1191
1192         /**
1193          * Iterates through msgno and message_id to remove dirty cache entries
1194          * @param array diff
1195          */
1196         function pop3_shiftCache($diff, $cacheUIDLs) {
1197                 $msgNos = "";
1198                 $msgIds = "";
1199                 $newArray = array();
1200                 foreach($diff as $msgNo => $msgId) {
1201                         if (in_array($msgId, $cacheUIDLs)) {
1202                                 $q1 = "UPDATE email_cache SET imap_uid = {$msgNo}, msgno = {$msgNo} WHERE ie_id = '{$this->id}' AND message_id = '{$msgId}'";
1203                                 $this->db->query($q1);
1204                         } else {
1205                                 $newArray[$msgNo] = $msgId;
1206                         }
1207                 }
1208                 return $newArray;
1209                 /*
1210                 foreach($diff as $msgNo => $msgId) {
1211                         if(!empty($msgNos)) {
1212                                 $msgNos .= ", ";
1213                         }
1214                         if(!empty($msgIds)) {
1215                                 $msgIds .= ", ";
1216                         }
1217
1218                         $msgNos .= $msgNo;
1219                         $msgIds .= "'{$msgId}'";
1220                 }
1221
1222                 if(!empty($msgNos)) {
1223                         $q1 = "DELETE FROM email_cache WHERE ie_id = '{$this->id}' AND msgno IN ({$msgNos})";
1224                         $this->db->query($q1);
1225                 }
1226                 if(!empty($msgIds)) {
1227                         $q2 = "DELETE FROM email_cache WHERE ie_id = '{$this->id}' AND message_id IN ({$msgIds})";
1228                         $this->db->query($q2);
1229                 }
1230                 */
1231         }
1232
1233         /**
1234          * retrieves cached uidl values.
1235          * When dealing with POP3 accounts, the message_id column in email_cache will contain the UIDL.
1236          * @return array
1237          */
1238         function pop3_getCacheUidls() {
1239                 $q = "SELECT msgno, message_id FROM email_cache WHERE ie_id = '{$this->id}'";
1240                 $r = $this->db->query($q);
1241
1242                 $ret = array();
1243                 while($a = $this->db->fetchByAssoc($r)) {
1244                         $ret[$a['msgno']] = $a['message_id'];
1245                 }
1246
1247                 return $ret;
1248         }
1249
1250         /**
1251          * This function is used by cron job for group mailbox without group folder
1252          * @param string $msgno for pop
1253          * @param string $uid for imap
1254          */
1255         function getMessagesInEmailCache($msgno, $uid) {
1256                 $fetchedOverviews = array();
1257                 if ($this->isPop3Protocol()) {
1258                         $fetchedOverviews = imap_fetch_overview($this->conn, $msgno);
1259                         foreach($fetchedOverviews as $k => $overview) {
1260                                 $overview->message_id = $uid;
1261                                 $fetchedOverviews[$k] = $overview;
1262                         }
1263                 } else {
1264                         $fetchedOverviews = imap_fetch_overview($this->conn, $uid, FT_UID);
1265                 } // else
1266                 $this->updateOverviewCacheFile($fetchedOverviews);
1267
1268         } // fn
1269
1270         /**
1271          * Checks email (local caching too) for one mailbox
1272          * @param string $mailbox IMAP Mailbox path
1273          * @param bool $prefetch Flag to prefetch email body on check
1274          */
1275         function checkEmailOneMailbox($mailbox, $prefetch=true, $synchronize=false) {
1276                 global $sugar_config;
1277                 global $current_user;
1278                 global $app_strings;
1279
1280                 $GLOBALS['log']->info("INBOUNDEMAIL: checking mailbox [ {$mailbox} ]");
1281                 $this->mailbox = $mailbox;
1282                 $this->connectMailserver();
1283
1284                 $checkTime = '';
1285                 $shouldProcessRules = true;
1286
1287                 $timestamp = $this->getCacheTimestamp($mailbox);
1288
1289                 if($timestamp > 0) {
1290                         $checkTime = date('r', $timestamp);
1291                 }
1292
1293                 /* first time through, process ALL emails */
1294                 if(empty($checkTime) || $synchronize) {
1295                         // do not process rules for the first time or sunchronize
1296                         $shouldProcessRules = false;
1297                         $criteria = "ALL UNDELETED";
1298                         $prefetch = false; // do NOT prefetch emails on a brand new account - timeouts happen.
1299                         $GLOBALS['log']->info("INBOUNDEMAIL: new account detected - not prefetching email bodies.");
1300                 } else {
1301                         $criteria = "SINCE \"{$checkTime}\" UNDELETED"; // not using UNSEEN
1302                 }
1303                 $this->setCacheTimestamp($mailbox);
1304                 $GLOBALS['log']->info("[EMAIL] Performing IMAP search using criteria [{$criteria}] on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1305                 $searchResults = imap_search($this->conn, $criteria, SE_UID);
1306                 $GLOBALS['log']->info("[EMAIL] Done IMAP search on mailbox [{$mailbox}] for user [{$current_user->user_name}]. Result count = ".count($searchResults));
1307
1308                 if(!empty($searchResults)) {
1309
1310                         $concatResults = implode(",", $searchResults);
1311                         $GLOBALS['log']->info("[EMAIL] Start IMAP fetch overview on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1312                         $fetchedOverview = imap_fetch_overview($this->conn, $concatResults, FT_UID);
1313                         $GLOBALS['log']->info("[EMAIL] Done IMAP fetch overview on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1314
1315                         $GLOBALS['log']->info("[EMAIL] Start updating overview cache for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1316                         $this->updateOverviewCacheFile($fetchedOverview);
1317                         $GLOBALS['log']->info("[EMAIL] Done updating overview cache for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1318
1319                         // prefetch emails
1320                         if($prefetch == true) {
1321                                 $GLOBALS['log']->info("[EMAIL] Start fetching emails for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1322                                 $this->fetchCheckedEmails($fetchedOverview);
1323                                 $GLOBALS['log']->info("[EMAIL] Done fetching emails for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1324                         }
1325                 } else {
1326                         $GLOBALS['log']->info("INBOUNDEMAIL: no results for mailbox [ {$mailbox} ]");
1327                 }
1328
1329                 /**
1330                  * To handle the use case where an external client is also connected, deleting emails, we need to clear our
1331                  * local cache of all emails with the "DELETED" flag
1332                  */
1333                 $criteria  = 'DELETED';
1334                 $criteria .= (!empty($checkTime)) ? " SINCE \"{$checkTime}\"" : "";
1335                 $GLOBALS['log']->info("INBOUNDEMAIL: checking for deleted emails using [ {$criteria} ]");
1336
1337                 $trashFolder = $this->get_stored_options("trashFolder");
1338                 if (empty($trashFolder)) {
1339                         $trashFolder = "INBOX.Trash";
1340                 }
1341
1342                 if($this->mailbox != $trashFolder) {
1343                         $searchResults = imap_search($this->conn, $criteria, SE_UID);
1344                         if(!empty($searchResults)) {
1345                                 $uids = implode($app_strings['LBL_EMAIL_DELIMITER'], $searchResults);
1346                                 $GLOBALS['log']->info("INBOUNDEMAIL: removing UIDs found deleted [ {$uids} ]");
1347                                 $this->getOverviewsFromCacheFile($uids, $mailbox, true);
1348                         }
1349                 }
1350         }
1351
1352            /**
1353      * Checks email (local caching too) for one mailbox
1354      * @param string $mailbox IMAP Mailbox path
1355      * @param bool $prefetch Flag to prefetch email body on check
1356      */
1357     function checkEmailOneMailboxPartial($mailbox, $prefetch=true, $synchronize=false, $start = 0, $max = -1) {
1358         global $sugar_config;
1359         global $current_user;
1360         global $app_strings;
1361
1362         $GLOBALS['log']->info("INBOUNDEMAIL: checking mailbox [ {$mailbox} ]");
1363         $this->mailbox = $mailbox;
1364         $this->connectMailserver();
1365
1366         $checkTime = '';
1367         $shouldProcessRules = true;
1368
1369         $timestamp = $this->getCacheTimestamp($mailbox);
1370
1371         if($timestamp > 0) {
1372             $checkTime = date('r', $timestamp);
1373         }
1374
1375         /* first time through, process ALL emails */
1376         if(empty($checkTime) || $synchronize) {
1377             // do not process rules for the first time or sunchronize
1378             $shouldProcessRules = false;
1379             $criteria = "ALL UNDELETED";
1380             $prefetch = false; // do NOT prefetch emails on a brand new account - timeouts happen.
1381             $GLOBALS['log']->info("INBOUNDEMAIL: new account detected - not prefetching email bodies.");
1382         } else {
1383             $criteria = "SINCE \"{$checkTime}\" UNDELETED"; // not using UNSEEN
1384         }
1385         $this->setCacheTimestamp($mailbox);
1386         $GLOBALS['log']->info("[EMAIL] Performing IMAP search using criteria [{$criteria}] on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1387         $searchResults = $this->getCachedIMAPSearch($criteria);
1388
1389         if(!empty($searchResults)) {
1390
1391             $total = sizeof($searchResults);
1392             $searchResults = array_slice($searchResults, $start, $max);
1393
1394             $GLOBALS['log']->info("INBOUNDEMAIL: there are  $total messages in [{$mailbox}], we are on $start");
1395             $GLOBALS['log']->info("INBOUNDEMAIL: getting the next " . sizeof($searchResults) . " messages");
1396             $concatResults = implode(",", $searchResults);
1397             $GLOBALS['log']->info("INBOUNDEMAIL: Start IMAP fetch overview on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1398             $fetchedOverview = imap_fetch_overview($this->conn, $concatResults, FT_UID);
1399             $GLOBALS['log']->info("INBOUNDEMAIL: Done IMAP fetch overview on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1400
1401             $GLOBALS['log']->info("INBOUNDEMAIL: Start updating overview cache for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1402             $this->updateOverviewCacheFile($fetchedOverview);
1403             $GLOBALS['log']->info("INBOUNDEMAIL: Done updating overview cache for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1404
1405             // prefetch emails
1406             if($prefetch == true) {
1407                 $GLOBALS['log']->info("INBOUNDEMAIL: Start fetching emails for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1408                 $this->fetchCheckedEmails($fetchedOverview);
1409                 $GLOBALS['log']->info("INBOUNDEMAIL: Done fetching emails for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1410             }
1411             $status = ($total > $start + sizeof($searchResults)) ? 'continue' : 'done';
1412             $ret = array('status' => $status, 'count' => $start + sizeof($searchResults), 'mbox' => $mailbox, 'totalcount' => $total);
1413             $GLOBALS['log']->info("INBOUNDEMAIL: $status : Downloaded " . $start + sizeof($searchResults) . "messages of $total");
1414
1415         } else {
1416             $GLOBALS['log']->info("INBOUNDEMAIL: no results for mailbox [ {$mailbox} ]");
1417             $ret = array('status' =>'done');
1418         }
1419
1420         if ($ret['status'] == 'done') {
1421                 //Remove the cached search if we are done with this mailbox
1422                 $cacheFilePath = clean_path("{$sugar_config['cache_dir']}modules/Emails/{$this->id}/folders/SearchData.php");
1423             unlink($cacheFilePath);
1424                 /**
1425                  * To handle the use case where an external client is also connected, deleting emails, we need to clear our
1426                  * local cache of all emails with the "DELETED" flag
1427                  */
1428                 $criteria  = 'DELETED';
1429                 $criteria .= (!empty($checkTime)) ? " SINCE \"{$checkTime}\"" : "";
1430                 $GLOBALS['log']->info("INBOUNDEMAIL: checking for deleted emails using [ {$criteria} ]");
1431
1432                         $trashFolder = $this->get_stored_options("trashFolder");
1433                         if (empty($trashFolder)) {
1434                                 $trashFolder = "INBOX.Trash";
1435                         }
1436
1437                 if($this->mailbox != $trashFolder) {
1438                     $searchResults = imap_search($this->conn, $criteria, SE_UID);
1439                     if(!empty($searchResults)) {
1440                         $uids = implode($app_strings['LBL_EMAIL_DELIMITER'], $searchResults);
1441                         $GLOBALS['log']->info("INBOUNDEMAIL: removing UIDs found deleted [ {$uids} ]");
1442                         $this->getOverviewsFromCacheFile($uids, $mailbox, true);
1443                     }
1444                 }
1445         }
1446         return $ret;
1447     }
1448
1449     function getCachedIMAPSearch($criteria) {
1450         global $current_user;
1451         global $sugar_config;
1452
1453         $cacheDataExists = false;
1454         $diff = array();
1455         $results = array();
1456         $cacheFolderPath = clean_path("{$sugar_config['cache_dir']}modules/Emails/{$this->id}/folders");
1457         if (!file_exists($cacheFolderPath)) {
1458                 mkdir_recursive($cacheFolderPath);
1459         }
1460         $cacheFilePath = $cacheFolderPath . '/SearchData.php';
1461         $GLOBALS['log']->info("INBOUNDEMAIL: Cache path is $cacheFilePath");
1462         if(file_exists($cacheFilePath)) {
1463             $cacheDataExists = true;
1464             if($fh = @fopen($cacheFilePath, "rb")) {
1465                 $data = "";
1466                 $chunksize = 1*(1024*1024); // how many bytes per chunk
1467                 while(!feof($fh)) {
1468                     $buf = fgets($fh, $chunksize); // 8kb max buffer - shouldn't be more than 80 chars via pop3...
1469                     $data = $data . $buf;
1470                     flush();
1471                 } // while
1472                 fclose($fh);
1473                 $results = unserialize($data);
1474             } // if
1475         } // if
1476         if (!$cacheDataExists) {
1477             $searchResults = imap_search($this->conn, $criteria, SE_UID);
1478             if(count($searchResults) > 0) {
1479                 $results = $searchResults;
1480                 $data = serialize($searchResults);
1481                 if($fh = @fopen($cacheFilePath, "w")) {
1482                     fputs($fh, $data);
1483                     fclose($fh);
1484                 } // if
1485             }
1486         } // if
1487         return $results;
1488     }
1489
1490     function checkEmailIMAPPartial($prefetch=true, $synch = false) {
1491         $GLOBALS['log']->info("*****************INBOUNDEMAIL: at IMAP check partial");
1492         global $sugar_config;
1493         $this->connectMailserver();
1494         $mailboxes = $this->getMailboxes(true);
1495         if (!in_array('INBOX', $mailboxes)) {
1496             $mailboxes[] = 'INBOX';
1497         }
1498         sort($mailboxes);
1499         if (isset($_REQUEST['mbox']) && !empty($_REQUEST['mbox']) && isset($_REQUEST['currentCount'])) {
1500                 $GLOBALS['log']->info("INBOUNDEMAIL: Picking up from where we left off");
1501             $mbox = $_REQUEST['mbox'];
1502             $count = $_REQUEST['currentCount'];
1503         } else {
1504                 if ($synch) {
1505                         $GLOBALS['log']->info("INBOUNDEMAIL: Cleaning out the cache");
1506                         $this->cleanOutCache();
1507                 }
1508             $mbox = $mailboxes[0];
1509             $count = 0;
1510         }
1511         $GLOBALS['log']->info("INBOUNDEMAIL:found " . sizeof($mailboxes) . " Mailboxes");
1512         $index = array_search($mbox, $mailboxes) + 1;
1513         $ret = $this->checkEmailOneMailboxPartial($mbox, $prefetch, $synch, $count, 100);
1514         while($ret['status'] == 'done' && $index < sizeof($mailboxes)) {
1515             if ($ret['count'] > 100) {
1516                 $ret['mbox'] = $mailboxes[$index];
1517                 $ret['status'] = 'continue';
1518                 return $ret;
1519             }
1520             $GLOBALS['log']->info("INBOUNDEMAIL: checking account [ $index => $mbox : $count]");
1521             $mbox = $mailboxes[$index];
1522             $ret = $this->checkEmailOneMailboxPartial($mbox, $prefetch, $synch, 0, 100);
1523             $index++;
1524         }
1525
1526         return $ret;
1527     }
1528
1529         function checkEmail2_meta() {
1530                 global $sugar_config;
1531
1532                 $this->connectMailserver();
1533                 $mailboxes = $this->getMailboxes(true);
1534                 $mailboxes[] = 'INBOX';
1535                 sort($mailboxes);
1536
1537                 $GLOBALS['log']->info("INBOUNDEMAIL: checking account [ {$this->name} ]");
1538
1539                 $mailboxes_meta = array();
1540                 foreach($mailboxes as $mailbox) {
1541                         $mailboxes_meta[$mailbox] = $this->getMailboxProcessCount($mailbox);
1542                 }
1543
1544                 $ret = array();
1545                 $ret['mailboxes'] = $mailboxes_meta;
1546
1547                 foreach($mailboxes_meta as $count) {
1548                         $ret['processCount'] += $count;
1549                 }
1550                 return $ret;
1551         }
1552
1553         function getMailboxProcessCount($mailbox) {
1554                 global $sugar_config;
1555
1556                 $GLOBALS['log']->info("INBOUNDEMAIL: checking mailbox [ {$mailbox} ]");
1557                 $this->mailbox = $mailbox;
1558                 $this->connectMailserver();
1559
1560                 $timestamp = $this->getCacheTimestamp($mailbox);
1561
1562                 $checkTime = '';
1563                 if($timestamp > 0) {
1564                         $checkTime = date('r', $timestamp);
1565                 }
1566
1567                 /* first time through, process ALL emails */
1568                 if(empty($checkTime)) {
1569                         $criteria = "ALL UNDELETED";
1570                         $prefetch = false; // do NOT prefetch emails on a brand new account - timeouts happen.
1571                         $GLOBALS['log']->info("INBOUNDEMAIL: new account detected - not prefetching email bodies.");
1572                 } else {
1573                         $criteria = "SINCE \"{$checkTime}\" UNDELETED"; // not using UNSEEN
1574                 }
1575
1576                 $GLOBALS['log']->info("INBOUNDEMAIL: using [ {$criteria} ]");
1577                 $searchResults = imap_search($this->conn, $criteria, SE_UID);
1578
1579                 if(!empty($searchResults)) {
1580                         $concatResults = implode(",", $searchResults);
1581                 } else {
1582                         $GLOBALS['log']->info("INBOUNDEMAIL: no results for mailbox [ {$mailbox} ]");
1583                 }
1584
1585                 if(empty($searchResults)) {
1586                         return 0;
1587                 }
1588
1589                 return count($searchResults);
1590         }
1591
1592         /**
1593          * update INBOX
1594          */
1595         function checkEmail($prefetch=true, $synch = false) {
1596                 global $sugar_config;
1597
1598                 if($this->protocol == 'pop3') {
1599                         $this->pop3_checkEmail();
1600                 } else {
1601                         $this->connectMailserver();
1602                         $mailboxes = $this->getMailboxes(true);
1603                         $mailboxes[] = 'INBOX';
1604                         sort($mailboxes);
1605
1606                         $GLOBALS['log']->info("INBOUNDEMAIL: checking account [ {$this->name} ]");
1607
1608                         foreach($mailboxes as $mailbox) {
1609                                 $this->checkEmailOneMailbox($mailbox, $prefetch, $synch);
1610                         }
1611                 }
1612         }
1613
1614         /**
1615          * full synchronization
1616          */
1617         function syncEmail() {
1618                 global $sugar_config;
1619                 global $current_user;
1620
1621                 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
1622
1623                 if(empty($showFolders)) {
1624                         $showFolders = array();
1625                 }
1626
1627                 $email = new Email();
1628                 $email->email2init();
1629
1630                 // personal accounts
1631                 if($current_user->hasPersonalEmail()) {
1632                         $personals = $this->retrieveByGroupId($current_user->id);
1633
1634                         foreach($personals as $personalAccount) {
1635                                 if(in_array($personalAccount->id, $showFolders)) {
1636                                         $personalAccount->email = $email;
1637                                         if ($personalAccount->isPop3Protocol()) {
1638                                                 $personalAccount->deletePop3Cache();
1639                                                 continue;
1640                                         }
1641                                         $personalAccount->cleanOutCache();
1642                                         $personalAccount->connectMailserver();
1643                                         $mailboxes = $personalAccount->getMailboxes(true);
1644                                         $mailboxes[] = 'INBOX';
1645                                         sort($mailboxes);
1646
1647                                         $GLOBALS['log']->info("[EMAIL] Start checking account [{$personalAccount->name}] for user [{$current_user->user_name}]");
1648
1649                                         foreach($mailboxes as $mailbox) {
1650                                                 $GLOBALS['log']->info("[EMAIL] Start checking mailbox [{$mailbox}] of account [{$personalAccount->name}] for user [{$current_user->user_name}]");
1651                                                 $personalAccount->checkEmailOneMailbox($mailbox, false, true);
1652                                                 $GLOBALS['log']->info("[EMAIL] Done checking mailbox [{$mailbox}] of account [{$personalAccount->name}] for user [{$current_user->user_name}]");
1653                                         }
1654                                         $GLOBALS['log']->info("[EMAIL] Done checking account [{$personalAccount->name}] for user [{$current_user->user_name}]");
1655                                 }
1656                         }
1657                 }
1658
1659                 // group accounts
1660                 $beans = $this->retrieveAllByGroupId($current_user->id, false);
1661                 foreach($beans as $k => $groupAccount) {
1662                         if(in_array($groupAccount->id, $showFolders)) {
1663                                 $groupAccount->email = $email;
1664                                 $groupAccount->cleanOutCache();
1665                                 $groupAccount->connectMailserver();
1666                                 $mailboxes = $groupAccount->getMailboxes(true);
1667                                 $mailboxes[] = 'INBOX';
1668                                 sort($mailboxes);
1669
1670                                 $GLOBALS['log']->info("INBOUNDEMAIL: checking account [ {$groupAccount->name} ]");
1671
1672                                 foreach($mailboxes as $mailbox) {
1673                                         $groupAccount->checkEmailOneMailbox($mailbox, false, true);
1674                                 }
1675                         }
1676                 }
1677         }
1678
1679
1680         /**
1681          * Deletes cached messages when moving from folder to folder
1682          * @param string $uids
1683          * @param string $fromFolder
1684          * @param string $toFolder
1685          */
1686         function deleteCachedMessages($uids, $fromFolder) {
1687                 global $sugar_config;
1688
1689                 if(!isset($this->email) && !isset($this->email->et)) {
1690                         if(!class_exists('Email')) {
1691
1692                         }
1693                         $this->email = new Email();
1694                         $this->email->email2init();
1695                 }
1696
1697                 $uids = $this->email->et->_cleanUIDList($uids);
1698
1699                 foreach($uids as $uid) {
1700                         $file = "{$sugar_config['cache_dir']}modules/Emails/{$this->id}/messages/{$fromFolder}{$uid}.php";
1701
1702                         if(file_exists($file)) {
1703                                 if(!unlink($file)) {
1704                                         $GLOBALS['log']->debug("INBOUNDEMAIL: Could not delete [ {$file} ] to [ {$newFile} ]");
1705                                 }
1706                         }
1707                 }
1708         }
1709
1710         /**
1711          * similar to imap_fetch_overview, but it gets overviews from a local cache
1712          * file.
1713          * @param string $uids UIDs in comma-delimited format
1714          * @param string $mailbox The mailbox in focus, will default to $this->mailbox
1715          * @param bool $remove Default false
1716          * @return array
1717          */
1718         function getOverviewsFromCacheFile($uids, $mailbox='', $remove=false) {
1719                 global $app_strings;
1720                 if(!isset($this->email) && !isset($this->email->et)) {
1721                         if(!class_exists('Email')) {
1722
1723                         }
1724                         $this->email = new Email();
1725                         $this->email->email2init();
1726                 }
1727
1728                 $uids = $this->email->et->_cleanUIDList($uids, true);
1729
1730                 // load current cache file
1731                 $mailbox = empty($mailbox) ? $this->mailbox : $mailbox;
1732                 $cacheValue = $this->getCacheValue($mailbox);
1733                 $ret = array();
1734
1735                 // prep UID array
1736                 $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
1737                 foreach($exUids as $k => $uid) {
1738                         $exUids[$k] = trim($uid);
1739                 }
1740
1741                 // fill $ret will requested $uids
1742                 foreach($cacheValue['retArr'] as $k => $overview) {
1743                         if(in_array($overview->imap_uid, $exUids)) {
1744                                 $ret[] = $overview;
1745                         }
1746                 }
1747
1748                 // remove requested $uids from current cache file (move_mail() type action)
1749                 if($remove) {
1750                         $this->setCacheValue($mailbox, array(), array(), $ret);
1751                 }
1752                 return $ret;
1753         }
1754
1755         /**
1756          * merges new info with the saved cached file
1757          * @param array $array Array of email Overviews
1758          * @param string $type 'append' or 'remove'
1759          * @param string $mailbox Target mailbox if not current assigned
1760          */
1761         function updateOverviewCacheFile($array, $type='append', $mailbox='') {
1762                 $mailbox = empty($mailbox) ? $this->mailbox : $mailbox;
1763
1764                 $cacheValue = $this->getCacheValue($mailbox);
1765                 $uids = $cacheValue['uids'];
1766
1767                 $updateRows = array();
1768                 $insertRows = array();
1769                 $removeRows = array();
1770
1771                 // update values
1772                 if($type == 'append') { // append
1773                         /* we are adding overviews to the cache file */
1774                         foreach($array as $overview) {
1775                                 if(isset($overview->uid)) {
1776                                         $overview->imap_uid = $overview->uid; // coming from imap_fetch_overview() call
1777                                 }
1778
1779                                 if(!in_array($overview->imap_uid, $uids)) {
1780                                         $insertRows[] = $overview;
1781                                 }
1782                         }
1783                 } else {
1784                         $updatedCacheOverviews = array();
1785                         // compare against generated list
1786                         /* we are removing overviews from the cache file */
1787                         foreach($cacheValue['retArr'] as $cacheOverview) {
1788                                 if(!in_array($cacheOverview->imap_uid, $uids)) {
1789                                         $insertRows[] = $cacheOverview;
1790                                 } else {
1791                                         $removeRows[] = $cacheOverview;
1792                                 }
1793                         }
1794
1795                         $cacheValue['retArr'] = $updatedCacheOverviews;
1796                 }
1797
1798                 $this->setCacheValue($mailbox, $insertRows, $updateRows, $removeRows);
1799         }
1800
1801         /**
1802          * Check email prefetches email bodies for quicker display
1803          * @param array array of fetched overviews
1804          */
1805         function fetchCheckedEmails($fetchedOverviews) {
1806                 global $sugar_config;
1807
1808                 if(is_array($fetchedOverviews) && !empty($fetchedOverviews)) {
1809                         foreach($fetchedOverviews as $overview) {
1810                                 if($overview->size < 10000) {
1811
1812                                         $uid = $overview->imap_uid;
1813
1814                                         if(!empty($uid)) {
1815                                                 $file = "{$this->mailbox}{$uid}.php";
1816                                                 $cacheFile = clean_path("{$sugar_config['cache_dir']}/modules/Emails/{$this->id}/messages/{$file}");
1817
1818                                                 if(!file_exists($cacheFile)) {
1819                                                         $GLOBALS['log']->info("INBOUNDEMAIL: Prefetching email [ {$file} ]");
1820                                                         $this->setEmailForDisplay($uid);
1821                                                         $out = $this->displayOneEmail($uid, $this->mailbox);
1822                                                         $this->email->et->writeCacheFile('out', $out, $this->id, 'messages', "{$this->mailbox}{$uid}.php");
1823                                                 } else {
1824                                                         $GLOBALS['log']->debug("INBOUNDEMAIL: Trying to prefetch an email we already fetched! [ {$cacheFile} ]");
1825                                                 }
1826                                         } else {
1827                                                 $GLOBALS['log']->debug("*** INBOUNDEMAIL: prefetch has a message with no UID");
1828                                         }
1829                                 } else {
1830                                         $GLOBALS['log']->debug("INBOUNDEMAIL: skipping email prefetch - size too large [ {$overview->size} ]");
1831                                 }
1832                         }
1833                 }
1834         }
1835
1836         /**
1837          * Sets flags on emails.  Assumes that connection is live, correct folder is
1838          * set.
1839          * @param string $uids Sequence of UIDs, comma separated
1840          * @param string $type Flag to mark
1841          */
1842         function markEmails($uids, $type) {
1843                 switch($type) {
1844                         case 'unread':
1845                                 $result = imap_clearflag_full($this->conn, $uids, '\\SEEN', ST_UID);
1846                         break;
1847                         case 'read':
1848                                 $result = imap_setflag_full($this->conn, $uids, '\\SEEN', ST_UID);
1849                         break;
1850                         case 'flagged':
1851                                 $result = imap_setflag_full($this->conn, $uids, '\\FLAGGED', ST_UID);
1852                         break;
1853                         case 'unflagged':
1854                                 $result = imap_clearflag_full($this->conn, $uids, '\\FLAGGED', ST_UID);
1855                         break;
1856                         case 'answered':
1857                                 $result = imap_setflag_full($this->conn, $uids, '\\Answered', ST_UID);
1858                         break;
1859                 }
1860         }
1861         ////    END EMAIL 2.0 SPECIFIC
1862         ///////////////////////////////////////////////////////////////////////////
1863
1864
1865
1866         ///////////////////////////////////////////////////////////////////////////
1867         ////    SERVER MANIPULATION METHODS
1868         /**
1869          * Deletes the specified folder
1870          * @param string $mbox "::" delimited IMAP mailbox path, ie, INBOX.saved.stuff
1871          * @return bool
1872          */
1873         function deleteFolder($mbox) {
1874                 $returnArray = array();
1875                 if ($this->getCacheCount($mbox) > 0) {
1876                         $returnArray['status'] = false;
1877                         $returnArray['errorMessage'] = "Can not delete {$mbox} as it has emails.";
1878                         return $returnArray;
1879                 }
1880                 $connectString = $this->getConnectString('', $mbox);
1881                 //Remove Folder cache
1882                 global $sugar_config;
1883                 unlink("{$sugar_config['cache_dir']}modules/Emails/{$this->id}/folders/folders.php");
1884
1885                 if(imap_unsubscribe($this->conn, imap_utf7_encode($connectString))) {
1886                         if(imap_deletemailbox($this->conn, $connectString)) {
1887                         $this->mailbox = str_replace(("," . $mbox), "", $this->mailbox);
1888                         $this->save();
1889                         $sessionFoldersString  = $this->getSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol);
1890                         $sessionFoldersString = str_replace(("," . $mbox), "", $sessionFoldersString);
1891                                 $this->setSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol, $sessionFoldersString);
1892                                 $returnArray['status'] = true;
1893                                 return $returnArray;
1894                         } else {
1895                                 $GLOBALS['log']->error("*** ERROR: EMAIL2.0 - could not delete IMAP mailbox with path: [ {$connectString} ]");
1896                                 $returnArray['status'] = false;
1897                                 $returnArray['errorMessage'] = "NOOP: could not delete folder: {$connectString}";
1898                                 return $returnArray;
1899                                 return false;
1900                         }
1901                 } else {
1902                         $GLOBALS['log']->error("*** ERROR: EMAIL2.0 - could not unsubscribe from folder, {$connectString} before deletion.");
1903                         $returnArray['status'] = false;
1904                         $returnArray['errorMessage'] = "NOOP: could not unsubscribe from folder, {$connectString} before deletion.";
1905                         return $returnArray;
1906                 }
1907         }
1908
1909         /**
1910          * Saves new folders
1911          * @param string $name Name of new IMAP mailbox
1912          * @param string $mbox "::" delimited IMAP mailbox path, ie, INBOX.saved.stuff
1913          * @return bool True on success
1914          */
1915         function saveNewFolder($name, $mbox) {
1916                 global $sugar_config;
1917         //Remove Folder cache
1918         global $sugar_config;
1919         //unlink("{$sugar_config['cache_dir']}modules/Emails/{$this->id}/folders/folders.php");
1920
1921         //$mboxImap = $this->getImapMboxFromSugarProprietary($mbox);
1922         $delimiter = $this->get_stored_options('folderDelimiter');
1923         if (!$delimiter) {
1924                 $delimiter = '.';
1925         }
1926
1927         $newFolder = $mbox . $delimiter . $name;
1928         $mbox .= $delimiter.str_replace($delimiter, "_", $name);
1929         $connectString = $this->getConnectString('', $mbox);
1930
1931                 if(imap_createmailbox($this->conn, imap_utf7_encode($connectString))) {
1932                         imap_subscribe($this->conn, imap_utf7_encode($connectString));
1933                         $status = imap_status($this->conn, str_replace("{$delimiter}{$name}","",$connectString));
1934                 $this->mailbox = $this->mailbox . "," . $newFolder;
1935                 $this->save();
1936                 $sessionFoldersString  = $this->getSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol);
1937                 $sessionFoldersString = $sessionFoldersString . "," . $newFolder;
1938                         $this->setSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol, $sessionFoldersString);
1939
1940                         echo $status;
1941                         return true;
1942                 } else {
1943                         echo "NOOP: could not create folder";
1944                         $GLOBALS['log']->error("*** ERROR: EMAIL2.0 - could not create IMAP mailbox with path: [ {$connectString} ]");
1945                         return false;
1946                 }
1947
1948         }
1949
1950         /**
1951          * Constructs an IMAP c-client compatible folder path from Sugar proprietary
1952          * @param string $mbox "::" delimited IMAP mailbox path, ie, INBOX.saved.stuff
1953          * @return string
1954          */
1955         function getImapMboxFromSugarProprietary($mbox) {
1956                 $exMbox = explode("::", $mbox);
1957
1958                 $mboxImap = '';
1959
1960                 for($i=2; $i<count($exMbox); $i++) {
1961                         if(!empty($mboxImap)) {
1962                                 $mboxImap .= ".";
1963                         }
1964                         $mboxImap .= $exMbox[$i];
1965                 }
1966
1967                 return $mboxImap;
1968         }
1969
1970         /**
1971          * Searches IMAP (and POP3?) accounts/folders for emails with qualifying criteria
1972          */
1973         function search($ieId, $subject='', $from='', $to='', $body='', $dateFrom='', $dateTo='') {
1974                 global $current_user;
1975                 global $app_strings;
1976                 global $timedate;
1977
1978                 $dateFrom = $timedate->to_db_date($dateFrom, false);
1979                 $dateTo = $timedate->to_db_date($dateTo, false);
1980                 $beans = array();
1981                 $bean = new InboundEmail();
1982                 $bean->retrieve($ieId);
1983                 $beans[] = $bean;
1984                 //$beans = $this->retrieveAllByGroupId($current_user->id, true);
1985
1986                 $subject = urldecode($subject);
1987
1988                 $criteria  = "";
1989                 $criteria .= (!empty($subject)) ? 'SUBJECT '.from_html($subject).'' : "";
1990                 //$criteria .= (!empty($subject)) ? 'SUBJECT "'.$GLOBALS['db']->helper->escape_quote($subject).'"' : "";
1991                 $criteria .= (!empty($from)) ? ' FROM "'.$from.'"' : "";
1992                 $criteria .= (!empty($to)) ? ' FROM "'.$to.'"' : "";
1993                 $criteria .= (!empty($body)) ? ' TEXT "'.$body.'"' : "";
1994                 $criteria .= (!empty($dateFrom)) ? ' SINCE "'.date('d-M-Y', strtotime($dateFrom)).'"' : "";
1995                 $criteria .= (!empty($dateTo)) ? ' BEFORE "'.date('d-M-Y', strtotime($dateTo)).'"' : "";
1996                 //$criteria .= (!empty($from)) ? ' FROM "'.$from.'"' : "";
1997
1998                 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
1999
2000                 $out = array();
2001
2002                 foreach($beans as $bean) {
2003                         if(!in_array($bean->id, $showFolders)) {
2004                                 continue;
2005                         }
2006
2007                         $GLOBALS['log']->info("*** INBOUNDEMAIL: searching [ {$bean->name} ] for [ {$subject}{$from}{$to}{$body}{$dateFrom}{$dateTo} ]");
2008                         $group = (!$bean->is_personal) ? 'group.' : '';
2009                         $bean->connectMailServer();
2010                         $mailboxes = $bean->getMailboxes(true);
2011                         if (!in_array('INBOX', $mailboxes)) {
2012                                 $mailboxes[] = 'INBOX';
2013                         }
2014                         $totalHits = 0;
2015
2016                         foreach($mailboxes as $mbox) {
2017                                 $bean->mailbox = $mbox;
2018                                 $searchOverviews = array();
2019                                 if ($bean->protocol == 'pop3') {
2020                                         $pop3Criteria = "SELECT * FROM email_cache WHERE ie_id = '{$bean->id}' AND mbox = '{$mbox}'";
2021                                         $pop3Criteria .= (!empty($subject)) ? ' AND subject like "%'.$bean->db->helper->escape_quote($subject).'%"' : "";
2022                                         $pop3Criteria .= (!empty($from)) ? ' AND fromaddr like "%'.$from.'%"' : "";
2023                                         $pop3Criteria .= (!empty($to)) ? ' AND toaddr like "%'.$to.'%"' : "";
2024                                         $pop3Criteria .= (!empty($dateFrom)) ? ' AND senddate > "'.$dateFrom.'"' : "";
2025                                         $pop3Criteria .= (!empty($dateTo)) ? ' AND senddate < "'.$dateTo.'"' : "";
2026                                         $GLOBALS['log']->info("*** INBOUNDEMAIL: searching [ {$mbox} ] using criteria [ {$pop3Criteria} ]");
2027
2028                                         $r = $bean->db->query($pop3Criteria);
2029                                         while($a = $bean->db->fetchByAssoc($r)) {
2030                                                 $overview = new Overview();
2031
2032                                                 foreach($a as $k => $v) {
2033                                                         $k=strtolower($k);
2034                                                         switch($k) {
2035                                                                 case "imap_uid":
2036                                                                         $overview->imap_uid = $v;
2037                                                                         $overview->uid = $a['message_id'];
2038                                                                 break;
2039                                                                 case "toaddr":
2040                                                                         $overview->to = from_html($v);
2041                                                                 break;
2042
2043                                                                 case "fromaddr":
2044                                                                         $overview->from = from_html($v);
2045                                                                 break;
2046
2047                                                                 case "mailsize":
2048                                                                         $overview->size = $v;
2049                                                                 break;
2050
2051                                                                 case "senddate":
2052                                                                         $overview->date = date('r', strtotime($v));
2053                                                                 break;
2054
2055                                                                 default:
2056                                                                         $overview->$k = from_html($v);
2057                                                                 break;
2058                                                         } // sqitch
2059                                                 } // foreach
2060                                                 $searchOverviews[] = $overview;
2061                                         } // while
2062                                 } else {
2063                                         $bean->connectMailServer();
2064                                         $searchResult = imap_search($bean->conn, $criteria, SE_UID);
2065                                         if (!empty($searchResult)) {
2066                                                 $searchOverviews = imap_fetch_overview($bean->conn, implode(',', $searchResult), FT_UID);
2067                                         } // if
2068                                 } // else
2069                                 $numHits = count($searchOverviews);
2070
2071                                 if($numHits > 0) {
2072                                         $totalHits = $totalHits + $numHits;
2073                                         $ret = $bean->sortFetchedOverview($searchOverviews, 'date', 'desc', true);
2074                                         $mbox = "{$bean->id}.SEARCH";
2075                                         $out = array_merge($out, $bean->displayFetchedSortedListXML($ret, $mbox, false));
2076                                 }
2077                         }
2078                 }
2079
2080                 $metadata = array();
2081                 $metadata['mbox'] = $app_strings['LBL_EMAIL_SEARCH_RESULTS_TITLE'];
2082                 $metadata['ieId'] = $this->id;
2083                 $metadata['name'] = $this->name;
2084                 $metadata['unreadChecked'] = ($current_user->getPreference('showUnreadOnly', 'Emails') == 1) ? 'CHECKED' : '';
2085                 $metadata['out'] = $out;
2086
2087                 return $metadata;
2088         }
2089
2090         /**
2091          * repairs the encrypted password for a given I-E account
2092          * @return bool True on success
2093          */
2094         function repairAccount() {
2095
2096                 for($i=0; $i<3; $i++) {
2097                         if($i != 0) { // decode is performed on retrieve already
2098                                 $this->email_password = blowfishDecode(blowfishGetKey('InboundEmail'), $this->email_password);
2099                         }
2100
2101                         if($this->connectMailserver() == 'true') {
2102                                 $this->save(); // save decoded password (is encoded on save())
2103                                 return true;
2104                         }
2105                 }
2106
2107                 return false;
2108         }
2109
2110         /**
2111          * soft deletes a User's personal inbox
2112          * @param string id I-E id
2113          * @param string user_name User name of User in focus, NOT current_user
2114          * @return bool True on success
2115          */
2116         function deletePersonalEmailAccount($id, $user_name) {
2117                 $q = "SELECT ie.id FROM inbound_email ie LEFT JOIN users u ON ie.group_id = u.id WHERE u.user_name = '{$user_name}'";
2118                 $r = $this->db->query($q, true);
2119
2120                 while($a = $this->db->fetchByAssoc($r)) {
2121                         if(!empty($a) && $a['id'] == $id) {
2122                                 $this->retrieve($id);
2123                                 $this->deleted = 1;
2124                                 $this->save();
2125                                 return true;
2126                         }
2127                 }
2128                 return false;
2129         }
2130
2131         function getTeamSetIdForTeams($teamIds) {
2132                 if(!is_array($teamIds)){
2133                    $teamIds = array($teamIds);
2134                 } // if
2135                 $teamSet = new TeamSet();
2136                 $team_set_id = $teamSet->addTeams($teamIds);
2137                 return $team_set_id;
2138         } // fn
2139
2140         /**
2141          * Saves Personal Inbox settings for Users
2142          * @param string userId ID of user to assign all emails for this account
2143          * @param strings userName Name of account, for Sugar purposes
2144          * @param bool forceSave Default true.  Flag to save errored settings.
2145          * @return boolean true on success, false on fail
2146          */
2147         function savePersonalEmailAccount($userId = '', $userName = '', $forceSave=true) {
2148                 $groupId = $userId;
2149                 $accountExists = false;
2150                 if(isset($_REQUEST['ie_id']) && !empty($_REQUEST['ie_id'])) {
2151                         $this->retrieve($_REQUEST['ie_id']);
2152                         $accountExists = true;
2153                 }
2154                 $ie_name = $_REQUEST['ie_name'];
2155
2156                 $this->is_personal = 1;
2157                 $this->name = $ie_name;
2158                 $this->group_id = $groupId;
2159                 $this->status = $_REQUEST['ie_status'];
2160                 $this->server_url = trim($_REQUEST['server_url']);
2161                 $this->email_user = trim($_REQUEST['email_user']);
2162                 $this->email_password = $_REQUEST['email_password'];
2163                 $this->port = trim($_REQUEST['port']);
2164                 $this->protocol = $_REQUEST['protocol'];
2165                 if ($this->protocol == "pop3") {
2166                         $_REQUEST['mailbox'] = "INBOX";
2167                 }
2168                 $this->mailbox = $_REQUEST['mailbox'];
2169                 $this->mailbox_type = 'pick'; // forcing this
2170
2171
2172                 if(isset($_REQUEST['ssl']) && $_REQUEST['ssl'] == 1) { $useSsl = true; }
2173                 else $useSsl = false;
2174                 $this->service = '::::::::::';
2175
2176                 if($forceSave) {
2177                         $id = $this->save(); // saving here to prevent user from having to re-enter all the info in case of error
2178                         $this->retrieve($id);
2179                 }
2180
2181                 $this->protocol = $_REQUEST['protocol']; // need to set this again since we safe the "service" string to empty explode values
2182                 $opts = $this->getSessionConnectionString($this->server_url, $this->email_user, $this->port, $this->protocol);
2183                 $detectedOpts = $this->findOptimumSettings($useSsl);
2184
2185                 //If $detectedOpts is empty, there was an error connecting, so clear $opts. If $opts was empty, use $detectedOpts
2186                 if (empty($opts) || empty($detectedOpts) || (empty($detectedOpts['good']) && empty($detectedOpts['serial'])))
2187                 {
2188                   $opts = $detectedOpts;
2189                 }
2190                 $delimiter = $this->getSessionInboundDelimiterString($this->server_url, $this->email_user, $this->port, $this->protocol);
2191
2192                 if(isset($opts['serial']) && !empty($opts['serial'])) {
2193                         $this->service = $opts['serial'];
2194                         if(isset($_REQUEST['mark_read']) && $_REQUEST['mark_read'] == 1) {
2195                                 $this->delete_seen = 0;
2196                         } else {
2197                                 $this->delete_seen = 1;
2198                         }
2199
2200                         // handle stored_options serialization
2201                         if(isset($_REQUEST['only_since']) && $_REQUEST['only_since'] == 1) {
2202                                 $onlySince = true;
2203                         } else {
2204                                 $onlySince = false;
2205                         }
2206
2207                         $focusUser = new User();
2208                         $focusUser->retrieve($groupId);
2209                         $mailerId = (isset($_REQUEST['outbound_email'])) ? $_REQUEST['outbound_email'] : "";
2210
2211                         $oe = new OutboundEmail();
2212                         $oe->getSystemMailerSettings($focusUser, $mailerId);
2213
2214                         $stored_options = array();
2215                         $stored_options['from_name'] = trim($_REQUEST['from_name']);
2216                         $stored_options['from_addr'] = trim($_REQUEST['from_addr']);
2217                         $stored_options['reply_to_addr'] = trim($_REQUEST['reply_to_addr']);
2218
2219                         if (!$this->isPop3Protocol()) {
2220                                 $stored_options['trashFolder'] = (isset($_REQUEST['trashFolder']) ? trim($_REQUEST['trashFolder']) : "");
2221                                 $stored_options['sentFolder'] = (isset($_REQUEST['sentFolder']) ? trim($_REQUEST['sentFolder']) : "");
2222                         } // if
2223                         $stored_options['only_since'] = $onlySince;
2224                         $stored_options['filter_domain'] = '';
2225                         $storedOptions['folderDelimiter'] = $delimiter;
2226                         $stored_options['outbound_email'] = (isset($_REQUEST['outbound_email'])) ? $_REQUEST['outbound_email'] : $oe->id;
2227                         $this->stored_options = base64_encode(serialize($stored_options));
2228
2229                         $ieId = $this->save();
2230
2231                         //If this is the first personal account the user has setup mark it as default for them.
2232                         $currentIECount = $this->getUserPersonalAccountCount($focusUser);
2233                         if($currentIECount == 1)
2234                             $this->setUsersDefaultOutboundServerId($focusUser, $ieId);
2235
2236                         return true;
2237                 } else {
2238                         // could not find opts, no save
2239                         $GLOBALS['log']->debug('-----> InboundEmail could not find optimums for User: '.$ie_name);
2240                         return false;
2241                 }
2242         }
2243         /**
2244          * Determines if this instance of I-E is for a Group Inbox or Personal Inbox
2245          */
2246         function handleIsPersonal() {
2247                 $qp = 'SELECT users.id, users.user_name FROM users WHERE users.is_group = 0 AND users.deleted = 0 AND users.status = \'active\' AND users.id = \''.$this->group_id.'\'';
2248                 $rp = $this->db->query($qp, true);
2249                 $personalBox = array();
2250                 while($ap = $this->db->fetchByAssoc($rp)) {
2251                         $personalBox[] = array($ap['id'], $ap['user_name']);
2252                 }
2253                 if(count($personalBox) > 0) {
2254                         return true;
2255                 } else {
2256                         return false;
2257                 }
2258         }
2259
2260         function getUserNameFromGroupId() {
2261                 $r = $this->db->query('SELECT users.user_name FROM users WHERE deleted=0 AND id=\''.$this->group_id.'\'', true);
2262                 while($a = $this->db->fetchByAssoc($r)) {
2263                         return $a['user_name'];
2264                 }
2265                 return '';
2266         }
2267
2268         function getFoldersListForMailBox() {
2269                 $return = array();
2270                 $foldersList = $this->getSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol);
2271                 if (empty($foldersList)) {
2272                         global $mod_strings;
2273                         $msg = $this->connectMailserver(true);
2274                         if (strpos($msg, "successfully")) {
2275                                 $foldersList = $this->getSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol);
2276                                 $return['status'] = true;
2277                                 $return['foldersList'] = $foldersList;
2278                                 $return['statusMessage'] = "";
2279                         } else {
2280                                 $return['status'] = false;
2281                                 $return['statusMessage'] = $msg;
2282                         } // else
2283                 } else {
2284                         $return['status'] = true;
2285                         $return['foldersList'] = $foldersList;
2286                         $return['statusMessage'] = "";
2287                 }
2288                 return $return;
2289         } // fn
2290         /**
2291          * Programatically determines best-case settings for imap_open()
2292          */
2293         function findOptimumSettings($useSsl=false, $user='', $pass='', $server='', $port='', $prot='', $mailbox='') {
2294                 global $mod_strings;
2295                 $serviceArr = array();
2296                 $returnService = array();
2297                 $badService = array();
2298                 $goodService = array();
2299                 $errorArr = array();
2300                 $raw = array();
2301                 $retArray = array(      'good' => $goodService,
2302                                                         'bad' => $badService,
2303                                                         'err' => $errorArr);
2304
2305                 if(!function_exists('imap_open')) {
2306                         $retArray['err'][0] = $mod_strings['ERR_NO_IMAP'];
2307                         return $retArray;
2308                 }
2309
2310                 imap_errors(); // clearing error stack
2311                 error_reporting(0); // turn off notices from IMAP
2312
2313                 if(isset($_REQUEST['ssl']) && $_REQUEST['ssl'] == 1) {
2314                         $useSsl = true;
2315                 }
2316
2317                 $exServ = explode('::', $this->service);
2318                 $service = '/'.$exServ[1];
2319
2320                 $nonSsl = array('both-secure'                   => '/notls/novalidate-cert/secure',
2321                                                 'both'                                  => '/notls/novalidate-cert',
2322                                                 'nocert-secure'                 => '/novalidate-cert/secure',
2323                                                 'nocert'                                => '/novalidate-cert',
2324                                                 'notls-secure'                  => '/notls/secure',
2325                                                 'secure'                                => '/secure', // for POP3 servers that force CRAM-MD5
2326                                                 'notls'                                 => '/notls',
2327                                                 'none'                                  => '', // try default nothing
2328                                         );
2329                 $ssl = array(
2330                                                 'ssl-both-on-secure'    => '/ssl/tls/validate-cert/secure',
2331                                                 'ssl-both-on'                   => '/ssl/tls/validate-cert',
2332                                                 'ssl-cert-secure'               => '/ssl/validate-cert/secure',
2333                                                 'ssl-cert'                              => '/ssl/validate-cert',
2334                                                 'ssl-tls-secure'                => '/ssl/tls/secure',
2335                                                 'ssl-tls'                               => '/ssl/tls',
2336                                                 'ssl-both-off-secure'   => '/ssl/notls/novalidate-cert/secure',
2337                                                 'ssl-both-off'                  => '/ssl/notls/novalidate-cert',
2338                                                 'ssl-nocert-secure'             => '/ssl/novalidate-cert/secure',
2339                                                 'ssl-nocert'                    => '/ssl/novalidate-cert',
2340                                                 'ssl-notls-secure'              => '/ssl/notls/secure',
2341                                                 'ssl-notls'                             => '/ssl/notls',
2342                                                 'ssl-secure'                    => '/ssl/secure',
2343                                                 'ssl-none'                              => '/ssl',
2344                                         );
2345
2346                 if(isset($user) && !empty($user) && isset($pass) && !empty($pass)) {
2347                         $this->email_password = $pass;
2348                         $this->email_user = $user;
2349                         $this->server_url = $server;
2350                         $this->port = $port;
2351                         $this->protocol = $prot;
2352                         $this->mailbox = $mailbox;
2353                 }
2354
2355                 // in case we flip from IMAP to POP3
2356                 if($this->protocol == 'pop3')
2357                   $this->mailbox = 'INBOX';
2358
2359                 //If user has selected multiple mailboxes, we only need to test the first mailbox for the connection string.
2360                 $a_mailbox = explode(",", $this->mailbox);
2361                 $tmpMailbox = isset($a_mailbox[0]) ? $a_mailbox[0] : "";
2362
2363                 if($useSsl == true)
2364                 {
2365                         foreach($ssl as $k => $service)
2366                         {
2367                                 $returnService[$k] = 'foo'.$service;
2368                                 $serviceArr[$k] = '{'.$this->server_url.':'.$this->port.'/service='.$this->protocol.$service.'}'.$tmpMailbox;
2369                         }
2370                 }
2371                 else
2372                 {
2373                         foreach($nonSsl as $k => $service)
2374                         {
2375                                 $returnService[$k] = 'foo'.$service;
2376                                 $serviceArr[$k] = '{'.$this->server_url.':'.$this->port.'/service='.$this->protocol.$service.'}'.$tmpMailbox;
2377                         }
2378                 }
2379
2380                 $GLOBALS['log']->debug('---------------STARTING FINDOPTIMUMS LOOP----------------');
2381                 $l = 1;
2382
2383                 //php imap library will capture c-client library warnings as errors causing good connections to be ignored.
2384                 //Check against known warnings to ensure good connections are used.
2385                 $acceptableWarnings = array("SECURITY PROBLEM: insecure server advertised AUTH=PLAIN", //c-client auth_pla.c
2386                                                 "Mailbox is empty");
2387                 $login = $this->email_user;
2388                 $passw = $this->email_password;
2389                 $foundGoodConnection = false;
2390                 foreach($serviceArr as $k => $serviceTest) {
2391                         $errors = '';
2392                         $alerts = '';
2393                         $GLOBALS['log']->debug($l.': I-E testing string: '.$serviceTest);
2394
2395                         // open the connection and try the test string
2396                         $this->conn = imap_open($serviceTest, $login, $passw);
2397
2398                         if(($errors = imap_last_error()) || ($alerts = imap_alerts())) {
2399                                 if($errors == 'Too many login failures' || $errors == '[CLOSED] IMAP connection broken (server response)') { // login failure means don't bother trying the rest
2400                                         $GLOBALS['log']->debug($l.': I-E failed using ['.$serviceTest.']');
2401                                         $retArray['err'][$k] = $mod_strings['ERR_BAD_LOGIN_PASSWORD'];
2402                                         $retArray['bad'][$k] = $serviceTest;
2403                                         $GLOBALS['log']->debug($l.': I-E ERROR: $ie->findOptimums() failed due to bad user credentials for user login: '.$this->email_user);
2404                                         return $retArray;
2405                                 } elseif( in_array($errors, $acceptableWarnings, TRUE)) { // false positive
2406                                         $GLOBALS['log']->debug($l.': I-E found good connection but with warnings ['.$serviceTest.'] Errors:' . $errors);
2407                                         $retArray['good'][$k] = $returnService[$k];
2408                                         $foundGoodConnection = true;
2409                                 }
2410                                 else {
2411                                         $GLOBALS['log']->debug($l.': I-E failed using ['.$serviceTest.'] - error: '.$errors);
2412                                         $retArray['err'][$k] = $errors;
2413                                         $retArray['bad'][$k] = $serviceTest;
2414                                 }
2415                         } else {
2416                                 $GLOBALS['log']->debug($l.': I-E found good connect using ['.$serviceTest.']');
2417                                 $retArray['good'][$k] = $returnService[$k];
2418                                 $foundGoodConnection = true;
2419                         }
2420
2421                         if(is_resource($this->conn)) {
2422                                 if (!$this->isPop3Protocol()) {
2423                                         $serviceTest = str_replace("INBOX", "", $serviceTest);
2424                                         $boxes = imap_getmailboxes($this->conn, $serviceTest, "*");
2425                                         $delimiter = '.';
2426                                         // clean MBOX path names
2427                                         foreach($boxes as $k => $mbox) {
2428                                                 $raw[] = $mbox->name;
2429                                                 if ($mbox->delimiter) {
2430                                                         $delimiter = $mbox->delimiter;
2431                                                 } // if
2432                                         } // foreach
2433                                         $this->setSessionInboundDelimiterString($this->server_url, $this->email_user, $this->port, $this->protocol, $delimiter);
2434                                 } // if
2435
2436                                 if(!imap_close($this->conn)) $GLOBALS['log']->debug('imap_close() failed!');
2437                         }
2438
2439                         $GLOBALS['log']->debug($l.': I-E clearing error and alert stacks.');
2440                         imap_errors(); // clear stacks
2441                         imap_alerts();
2442                         // If you find a good connection, then don't do any further testing to find URL
2443                         if ($foundGoodConnection) {
2444                                 break;
2445                         } // if
2446                         $l++;
2447                 }
2448                 $GLOBALS['log']->debug('---------------end FINDOPTIMUMS LOOP----------------');
2449
2450                 if(!empty($retArray['good'])) {
2451                         $newTls                         = '';
2452                         $newCert                        = '';
2453                         $newSsl                         = '';
2454                         $newNotls                       = '';
2455                         $newNovalidate_cert     = '';
2456                         $good = array_pop($retArray['good']); // get most complete string
2457                         $exGood = explode('/', $good);
2458                         foreach($exGood as $v) {
2459                                 switch($v) {
2460                                         case 'ssl':
2461                                                 $newSsl = 'ssl';
2462                                         break;
2463                                         case 'tls':
2464                                                 $newTls = 'tls';
2465                                         break;
2466                                         case 'notls':
2467                                                 $newNotls = 'notls';
2468                                         break;
2469                                         case 'cert':
2470                                                 $newCert = 'validate-cert';
2471                                         break;
2472                                         case 'novalidate-cert':
2473                                                 $newNovalidate_cert = 'novalidate-cert';
2474                                         break;
2475                                         case 'secure':
2476                                                 $secure = 'secure';
2477                                         break;
2478                                 }
2479                         }
2480
2481                         $goodStr['serial'] = $newTls.'::'.$newCert.'::'.$newSsl.'::'.$this->protocol.'::'.$newNovalidate_cert.'::'.$newNotls.'::'.$secure;
2482                         $goodStr['service'] = $good;
2483                         $testConnectString = str_replace('foo','', $good);
2484                         $testConnectString = '{'.$this->server_url.':'.$this->port.'/service='.$this->protocol.$testConnectString.'}';
2485                         $this->setSessionConnectionString($this->server_url, $this->email_user, $this->port, $this->protocol, $goodStr);
2486                         $i = 0;
2487                         foreach($raw as $mbox)
2488                         {
2489                                 $raw[$i] = str_replace($testConnectString, "", mb_convert_encoding($mbox, "UTF8", "UTF7-IMAP" ));
2490                                 $i++;
2491                         } // foreach
2492                         sort($raw);
2493                         $this->setSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol, implode(",", $raw));
2494                         return $goodStr;
2495                 } else {
2496                         return false;
2497                 }
2498         }
2499
2500         function getSessionConnectionString($server_url, $email_user, $port, $protocol) {
2501                 $sessionConnectionString = $server_url . $email_user . $port . $protocol;
2502                 return (isset($_SESSION[$sessionConnectionString]) ? $_SESSION[$sessionConnectionString] : "");
2503         }
2504
2505         function setSessionConnectionString($server_url, $email_user, $port, $protocol, $goodStr) {
2506                 $sessionConnectionString = $server_url . $email_user . $port . $protocol;
2507                 $_SESSION[$sessionConnectionString] = $goodStr;
2508         }
2509
2510         function getSessionInboundDelimiterString($server_url, $email_user, $port, $protocol) {
2511                 $sessionInboundDelimiterString = $server_url . $email_user . $port . $protocol . "delimiter";
2512                 return (isset($_SESSION[$sessionInboundDelimiterString]) ? $_SESSION[$sessionInboundDelimiterString] : "");
2513         }
2514
2515         function setSessionInboundDelimiterString($server_url, $email_user, $port, $protocol, $delimiter) {
2516                 $sessionInboundDelimiterString = $server_url . $email_user . $port . $protocol . "delimiter";
2517                 $_SESSION[$sessionInboundDelimiterString] = $delimiter;
2518         }
2519
2520         function getSessionInboundFoldersString($server_url, $email_user, $port, $protocol) {
2521                 $sessionInboundFoldersListString = $server_url . $email_user . $port . $protocol . "foldersList";
2522                 return (isset($_SESSION[$sessionInboundFoldersListString]) ? $_SESSION[$sessionInboundFoldersListString] : "");
2523         }
2524
2525         function setSessionInboundFoldersString($server_url, $email_user, $port, $protocol, $foldersList) {
2526                 $sessionInboundFoldersListString = $server_url . $email_user . $port . $protocol . "foldersList";
2527                 $_SESSION[$sessionInboundFoldersListString] = $foldersList;
2528         }
2529
2530         /**
2531          * Checks for duplicate Group User names when creating a new one at save()
2532          * @return      GUID            returns GUID of Group User if user_name match is
2533          * found
2534          * @return      boolean         false if NO DUPE IS FOUND
2535          */
2536         function groupUserDupeCheck() {
2537                 $q = "SELECT u.id FROM users u WHERE u.deleted=0 AND u.is_group=1 AND u.user_name = '".$this->name."'";
2538                 $r = $this->db->query($q, true);
2539                 $uid = '';
2540                 while($a = $this->db->fetchByAssoc($r)) {
2541                         $uid = $a['id'];
2542                 }
2543
2544                 if(strlen($uid) > 0) {
2545                         return $uid;
2546                 } else {
2547                         return false;
2548                 }
2549         }
2550
2551         /**
2552          * Returns <option> markup with the contents of Group users
2553          * @param array $groups default empty array
2554          * @return string HTML options
2555          */
2556         function getGroupsWithSelectOptions($groups = array()) {
2557                 $r = $this->db->query('SELECT id, user_name FROM users WHERE users.is_group = 1 AND deleted = 0', true);
2558                 if(is_resource($r)) {
2559                         while($a = $this->db->fetchByAssoc($r)) {
2560                                 $groups[$a['id']] = $a['user_name'];
2561                         }
2562                 }
2563
2564                 $selectOptions = get_select_options_with_id_separate_key($groups, $groups, $this->group_id);
2565                 return $selectOptions;
2566         }
2567
2568         /**
2569          * handles auto-responses to inbound emails
2570          *
2571          * @param object email Email passed as reference
2572          */
2573         function handleAutoresponse(&$email, &$contactAddr) {
2574                 if($this->template_id) {
2575                         $GLOBALS['log']->debug('found auto-reply template id - prefilling and mailing response');
2576
2577                         if($this->getAutoreplyStatus($contactAddr)
2578                         && $this->checkOutOfOffice($email->name)
2579                         && $this->checkFilterDomain($email)) { // if we haven't sent this guy 10 replies in 24hours
2580
2581                                 if(!empty($this->stored_options)) {
2582                                         $storedOptions = unserialize(base64_decode($this->stored_options));
2583                                 }
2584                                 // get FROM NAME
2585                                 if(!empty($storedOptions['from_name'])) {
2586                                         $from_name = $storedOptions['from_name'];
2587                                         $GLOBALS['log']->debug('got from_name from storedOptions: '.$from_name);
2588                                 } else { // use system default
2589                                         $rName = $this->db->query('SELECT value FROM config WHERE name = \'fromname\'', true);
2590                                         if(is_resource($rName)) {
2591                                                 $aName = $this->db->fetchByAssoc($rName);
2592                                         }
2593                                         if(!empty($aName['value'])) {
2594                                                 $from_name = $aName['value'];
2595                                         } else {
2596                                                 $from_name = '';
2597                                         }
2598                                 }
2599                                 // get FROM ADDRESS
2600                                 if(!empty($storedOptions['from_addr'])) {
2601                                         $from_addr = $storedOptions['from_addr'];
2602                                 } else {
2603                                         $rAddr = $this->db->query('SELECT value FROM config WHERE name = \'fromaddress\'', true);
2604                                         if(is_resource($rAddr)) {
2605                                                 $aAddr = $this->db->fetchByAssoc($rAddr);
2606                                         }
2607                                         if(!empty($aAddr['value'])) {
2608                                                 $from_addr = $aAddr['value'];
2609                                         } else {
2610                                                 $from_addr = '';
2611                                         }
2612                                 }
2613
2614                                 $replyToName = (!empty($storedOptions['reply_to_name']))? from_html($storedOptions['reply_to_name']) :$fromName ;
2615                                 $replyToAddr = (!empty($storedOptions['reply_to_addr'])) ? $storedOptions['reply_to_addr'] : $fromAddress;
2616
2617                                 if(!empty($email->reply_to_email)) {
2618                                         $to[0]['email'] = $email->reply_to_email;
2619                                 } else {
2620                                         $to[0]['email'] = $email->from_addr;
2621                                 }
2622                                 // handle to name: address, prefer reply-to
2623                                 if(!empty($email->reply_to_name)) {
2624                                         $to[0]['display'] = $email->reply_to_name;
2625                                 } elseif(!empty($email->from_name)) {
2626                                         $to[0]['display'] = $email->from_name;
2627                                 }
2628
2629                                 if(!class_exists('EmailTemplate')) {
2630
2631                                 }
2632                                 $et = new EmailTemplate();
2633                                 $et->retrieve($this->template_id);
2634                                 if(empty($et->subject))         { $et->subject = ''; }
2635                                 if(empty($et->body))            { $et->body = ''; }
2636                                 if(empty($et->body_html))       { $et->body_html = ''; }
2637
2638                                 $reply = new Email();
2639                                 $reply->type                            = 'out';
2640                                 $reply->to_addrs                        = $to[0]['email'];
2641                                 $reply->to_addrs_arr            = $to;
2642                                 $reply->cc_addrs_arr            = array();
2643                                 $reply->bcc_addrs_arr           = array();
2644                                 $reply->from_name                       = $from_name;
2645                                 $reply->from_addr                       = $from_addr;
2646                                 $reply->name                            = $et->subject;
2647                                 $reply->description                     = $et->body;
2648                                 $reply->description_html        = $et->body_html;
2649                                 $reply->reply_to_name           = $replyToName;
2650                                 $reply->reply_to_addr           = $replyToAddr;
2651
2652                                 $GLOBALS['log']->debug('saving and sending auto-reply email');
2653                                 //$reply->save(); // don't save the actual email.
2654                                 $reply->send();
2655                                 $this->setAutoreplyStatus($contactAddr);
2656                         } else {
2657                                 $GLOBALS['log']->debug('InboundEmail: auto-reply threshold reached for email ('.$contactAddr.') - not sending auto-reply');
2658                         }
2659                 }
2660         }
2661
2662         function handleCaseAssignment($email) {
2663                 if(!class_exists('aCase')) {
2664
2665                 }
2666                 $c = new aCase();
2667                 if($caseId = $this->getCaseIdFromCaseNumber($email->name, $c)) {
2668                         $c->retrieve($caseId);
2669                         $c->load_relationship('emails');
2670                         $c->emails->add($email->id);
2671
2672                         $email->retrieve($email->id);
2673                         $email->parent_type = "Cases";
2674                         $email->parent_id = $caseId;
2675                         // assign the email to the case owner
2676                         $email->assigned_user_id = $c->assigned_user_id;
2677                         $email->save();
2678                         $GLOBALS['log']->debug('InboundEmail found exactly 1 match for a case: '.$c->name);
2679                         return true;
2680                 } // if
2681                 return false;
2682         } // fn
2683
2684         /**
2685          * handles functionality specific to the Mailbox type (Cases, bounced
2686          * campaigns, etc.)
2687          *
2688          * @param object email Email object passed as a reference
2689          * @param object header Header object generated by imap_headerinfo();
2690          */
2691         function handleMailboxType(&$email, &$header) {
2692                 switch($this->mailbox_type) {
2693                         case 'support':
2694                                 $this->handleCaseAssignment($email);
2695                                 break;
2696                         case 'bug':
2697
2698                                 break;
2699
2700                         case 'info':
2701                                 // do something with this?
2702                                 break;
2703                         case 'sales':
2704                                 // do something with leads? we don't have an email_leads table
2705                                 break;
2706                         case 'task':
2707                                 // do something?
2708                                 break;
2709                         case 'bounce':
2710                                 require_once('modules/Campaigns/ProcessBouncedEmails.php');
2711                                 campaign_process_bounced_emails($email, $header);
2712                                 break;
2713                         case 'pick': // do all except bounce handling
2714                                 $GLOBALS['log']->debug('looking for a case for '.$email->name);
2715                                 $this->handleCaseAssignment($email);
2716                                 break;
2717                 }
2718         }
2719
2720         function isMailBoxTypeCreateCase() {
2721                 return ($this->mailbox_type == 'createcase' && !empty($this->groupfolder_id));
2722         } // fn
2723
2724         function handleCreateCase($email, $userId) {
2725                 global $current_user, $mod_strings, $current_language;
2726                 $mod_strings = return_module_language($current_language, "Emails");
2727                 $GLOBALS['log']->debug('In handleCreateCase');
2728                 if(!class_exists('aCase')) {
2729
2730                 }
2731                 $c = new aCase();
2732                 $this->getCaseIdFromCaseNumber($email->name, $c);
2733
2734                 if (!$this->handleCaseAssignment($email) && $this->isMailBoxTypeCreateCase()) {
2735                         // create a case
2736                         $GLOBALS['log']->debug('retrieveing email');
2737                         $email->retrieve($email->id);
2738                         $c = new aCase();
2739                         $c->description = $email->description;
2740                         $c->assigned_user_id = $userId;
2741                         $c->name = $email->name;
2742                         $c->status = 'New';
2743                         $c->priority = 'P1';
2744
2745                         if(!empty($email->reply_to_email)) {
2746                                 $contactAddr = $email->reply_to_email;
2747                         } else {
2748                                 $contactAddr = $email->from_addr;
2749                         }
2750
2751                         $GLOBALS['log']->debug('finding related accounts with address ' . $contactAddr);
2752                         if($accountIds = $this->getRelatedId($contactAddr, 'accounts')) {
2753                                 if (sizeof($accountIds) == 1) {
2754                                         $c->account_id = $accountIds[0];
2755
2756                                         $acct = new Account();
2757                                         $acct->retrieve($c->account_id);
2758                                         $c->account_name = $acct->name;
2759                                 } // if
2760                         } // if
2761                         $c->save(true);
2762                         $caseId = $c->id;
2763                         $c = new aCase();
2764                         $c->retrieve($caseId);
2765                         if($c->load_relationship('emails')) {
2766                                 $c->emails->add($email->id);
2767                         } // if
2768                         if($contactIds = $this->getRelatedId($contactAddr, 'contacts')) {
2769                                 if(!empty($contactIds) && $c->load_relationship('contacts')) {
2770                                         $c->contacts->add($contactIds);
2771                                 } // if
2772                         } // if
2773                         $c->email_id = $email->id;
2774                         $email->parent_type = "Cases";
2775                         $email->parent_id = $caseId;
2776                         // assign the email to the case owner
2777                         $email->assigned_user_id = $c->assigned_user_id;
2778                         $email->name = str_replace('%1', $c->case_number, $c->getEmailSubjectMacro()) . " ". $email->name;
2779                         $email->save();
2780                         $GLOBALS['log']->debug('InboundEmail created one case with number: '.$c->case_number);
2781                         $createCaseTemplateId = $this->get_stored_options('create_case_email_template', "");
2782                         if(!empty($this->stored_options)) {
2783                                 $storedOptions = unserialize(base64_decode($this->stored_options));
2784                         }
2785                         if(!empty($createCaseTemplateId)) {
2786                                 $fromName = "";
2787                                 $fromAddress = "";
2788                                 if (!empty($this->stored_options)) {
2789                                         $fromAddress = $storedOptions['from_addr'];
2790                                         $fromName = from_html($storedOptions['from_name']);
2791                                         $replyToName = (!empty($storedOptions['reply_to_name']))? from_html($storedOptions['reply_to_name']) :$fromName ;
2792                                         $replyToAddr = (!empty($storedOptions['reply_to_addr'])) ? $storedOptions['reply_to_addr'] : $fromAddress;
2793                                 } // if
2794                                 $defaults = $current_user->getPreferredEmail();
2795                                 $fromAddress = (!empty($fromAddress)) ? $fromAddress : $defaults['email'];
2796                                 $fromName = (!empty($fromName)) ? $fromName : $defaults['name'];
2797                                 $to[0]['email'] = $contactAddr;
2798
2799                                 // handle to name: address, prefer reply-to
2800                                 if(!empty($email->reply_to_name)) {
2801                                         $to[0]['display'] = $email->reply_to_name;
2802                                 } elseif(!empty($email->from_name)) {
2803                                         $to[0]['display'] = $email->from_name;
2804                                 }
2805
2806                                 if(!class_exists('EmailTemplate')) {
2807
2808                                 }
2809                                 $et = new EmailTemplate();
2810                                 $et->retrieve($createCaseTemplateId);
2811                                 if(empty($et->subject))         { $et->subject = ''; }
2812                                 if(empty($et->body))            { $et->body = ''; }
2813                                 if(empty($et->body_html))       { $et->body_html = ''; }
2814
2815                                 $et->subject = "Re:" . " " . str_replace('%1', $c->case_number, $c->getEmailSubjectMacro() . " ". $c->name);
2816
2817                                 $html = trim($email->description_html);
2818                                 $plain = trim($email->description);
2819
2820                                 $email->email2init();
2821                     $email->from_addr = $email->from_addr_name;
2822                     $email->to_addrs = $email->to_addrs_names;
2823                     $email->cc_addrs = $email->cc_addrs_names;
2824                     $email->bcc_addrs = $email->bcc_addrs_names;
2825                     $email->from_name = $email->from_addr;
2826
2827                 $email = $email->et->handleReplyType($email, "reply");
2828                 $ret = $email->et->displayComposeEmail($email);
2829                 $ret['description'] = empty($email->description_html) ?  str_replace("\n", "\n<BR/>", $email->description) : $email->description_html;
2830
2831                                 $reply = new Email();
2832                                 $reply->type                            = 'out';
2833                                 $reply->to_addrs                        = $to[0]['email'];
2834                                 $reply->to_addrs_arr            = $to;
2835                                 $reply->cc_addrs_arr            = array();
2836                                 $reply->bcc_addrs_arr           = array();
2837                                 $reply->from_name                       = $fromName;
2838                                 $reply->from_addr                       = $fromAddress;
2839                                 $reply->reply_to_name           = $replyToName;
2840                                 $reply->reply_to_addr           = $replyToAddr;
2841                                 $reply->name                            = $et->subject;
2842                                 $reply->description                     = $et->body . "<div><hr /></div>" .  $email->description;
2843                                 if (!$et->text_only) {
2844                                         $reply->description_html        = $et->body_html .  "<div><hr /></div>" . $email->description;
2845                                 }
2846                                 $GLOBALS['log']->debug('saving and sending auto-reply email');
2847                                 //$reply->save(); // don't save the actual email.
2848                                 $reply->send();
2849                         } // if
2850
2851                 } else {
2852                         if(!empty($email->reply_to_email)) {
2853                                 $contactAddr = $email->reply_to_email;
2854                         } else {
2855                                 $contactAddr = $email->from_addr;
2856                         }
2857                         $this->handleAutoresponse($email, $contactAddr);
2858                 }
2859
2860         } // fn
2861
2862         /**
2863          * handles linking contacts, accounts, etc. to an email
2864          *
2865          * @param object Email bean to be linked against
2866          * @return string contactAddr is the email address of the sender
2867          */
2868         function handleLinking(&$email) {
2869                 // link email to an User if emails match TO addr
2870                 if($userIds = $this->getRelatedId($email->to_addrs, 'users')) {
2871                         $GLOBALS['log']->debug('I-E linking email to User');
2872                         // link the user to the email
2873                         $email->load_relationship('users');
2874                         $email->users->add($userIds);
2875                 }
2876
2877                 // link email to a Contact, Lead, or Account if the emails match
2878                 // give precedence to REPLY-TO above FROM
2879                 if(!empty($email->reply_to_email)) {
2880                         $contactAddr = $email->reply_to_email;
2881                 } else {
2882                         $contactAddr = $email->from_addr;
2883                 }
2884
2885                 // Samir Gandhi : 12/06/07
2886                 // This changes has been done because the linking was done only with the from address and
2887                 // not with to address
2888                 $relationShipAddress = $contactAddr;
2889                 if (empty($relationShipAddress)) {
2890                         $relationShipAddress .= $email->to_addrs;
2891                 } else {
2892                         $relationShipAddress = $relationShipAddress . "," . $email->to_addrs;
2893                 }
2894                 if($leadIds = $this->getRelatedId($relationShipAddress, 'leads')) {
2895                         $GLOBALS['log']->debug('I-E linking email to Lead');
2896                         $email->load_relationship('leads');
2897                         $email->leads->add($leadIds);
2898
2899                         if(!class_exists('Lead')) {
2900
2901                         }
2902                         foreach($leadIds as $leadId) {
2903                                 $lead = new Lead();
2904                                 $lead->retrieve($leadId);
2905                                 $lead->load_relationship('emails');
2906                                 $lead->emails->add($email->id);
2907                         }
2908                 }
2909
2910                 if($contactIds = $this->getRelatedId($relationShipAddress, 'contacts')) {
2911                         $GLOBALS['log']->debug('I-E linking email to Contact');
2912                         // link the contact to the email
2913                         $email->load_relationship('contacts');
2914                         $email->contacts->add($contactIds);
2915                 }
2916
2917                 if($accountIds = $this->getRelatedId($relationShipAddress, 'accounts')) {
2918                         $GLOBALS['log']->debug('I-E linking email to Account');
2919                         // link the account to the email
2920                         $email->load_relationship('accounts');
2921                         $email->accounts->add($accountIds);
2922
2923                         if(!class_exists('Account')) {
2924
2925                         }
2926
2927                         /* cn: bug 9171 another cause of dying I-E - bad linking
2928                         foreach($accountIds as $accountId) {
2929                                 $GLOBALS['log']->debug('I-E reverse-linking Accounts to Emails');
2930                                 $acct = new Account();
2931                                 $acct->retrieve($accountId);
2932                                 $acct->load_relationship('emails');
2933                                 $acct->account_emails->add($email->id);
2934                         }
2935                         */
2936                 }
2937                 return $contactAddr;
2938         }
2939         /**
2940          * takes a breadcrumb and returns the encoding at that level
2941          * @param       string bc the breadcrumb string in format (1.1.1)
2942          * @param       array parts the root level parts array
2943          * @return      int retInt Int key to transfer encoding (see handleTranserEncoding())
2944          */
2945         function getEncodingFromBreadCrumb($bc, $parts) {
2946                 if(strstr($bc,'.')) {
2947                         $exBc = explode('.', $bc);
2948                 } else {
2949                         $exBc[0] = $bc;
2950                 }
2951
2952                 $depth = count($exBc);
2953
2954                 for($i=0; $i<$depth; $i++) {
2955                         $tempObj[$i] = $parts[($exBc[$i]-1)];
2956                         $retInt = imap_utf8($tempObj[$i]->encoding);
2957                         if(!empty($tempObj[$i]->parts)) {
2958                                 $parts = $tempObj[$i]->parts;
2959                         }
2960                 }
2961                 return $retInt;
2962         }
2963
2964         /**
2965          * retrieves the charset for a given part of an email body
2966          *
2967          * @param string bc target part of the message in format (1.1.1)
2968          * @param array parts 1 level above ROOT array of Objects representing a multipart body
2969          * @return string charset name
2970          */
2971         function getCharsetFromBreadCrumb($bc, $parts) {
2972                 if(strstr($bc,'.')) {
2973                         $exBc = explode('.', $bc);
2974                 } else {
2975                         $exBc[0] = $bc;
2976                 }
2977
2978                 foreach($exBc as $crumb) {
2979                         $tempObj = $parts[$crumb-1];
2980                         if(is_array($tempObj->parts)) {
2981                                 $parts = $tempObj->parts;
2982                         }
2983                 }
2984
2985                 // now we have the tempObj at the end of the breadCrumb trail
2986                 //$GLOBALS['log']->fatal(print_r(debug_backtrace(), true));
2987
2988                 if($tempObj->ifparameters) {
2989                         foreach($tempObj->parameters as $param) {
2990                                 if(strtolower($param->attribute) == 'charset') {
2991                                         return $param->value;
2992                                 }
2993                         }
2994                 }
2995
2996                 return 'default';
2997         }
2998
2999         /**
3000          * Get the message text from a single mime section, html or plain.
3001          *
3002          * @param string $msgNo
3003          * @param string $section
3004          * @param stdObject $structure
3005          * @return string
3006          */
3007         function getMessageTextFromSingleMimePart($msgNo,$section,$structure)
3008         {
3009             $msgPartTmp = imap_fetchbody($this->conn, $msgNo, $section);
3010             $enc = $this->getEncodingFromBreadCrumb($section, $structure->parts);
3011             $charset = $this->getCharsetFromBreadCrumb($section, $structure->parts);
3012             $msgPartTmp = $this->handleTranserEncoding($msgPartTmp, $enc);
3013             return $this->handleCharsetTranslation($msgPartTmp, $charset);
3014         }
3015
3016         /**
3017          * Givin an existing breadcrumb add a cooresponding offset
3018          *
3019          * @param string $bc
3020          * @param string $offset
3021          * @return string
3022          */
3023         function addBreadCrumbOffset($bc, $offset)
3024         {
3025             if( (empty($bc) || is_null($bc)) && !empty($offset) )
3026                return $offset;
3027
3028             $a_bc = explode(".", $bc);
3029             $a_offset = explode(".",$offset);
3030             if(count($a_bc) < count($a_offset))
3031                $a_bc = array_merge($a_bc,array_fill( count($a_bc), count($a_offset) - count($a_bc), 0));
3032
3033             $results = array();
3034             for($i=0;$i < count($a_bc); $i++)
3035             {
3036                 if(isset($a_offset[$i]))
3037                    $results[] = $a_bc[$i] + $a_offset[$i];
3038                 else
3039                    $results[] = $a_bc[$i];
3040             }
3041             return implode(".", $results);
3042         }
3043
3044         /**
3045          * returns the HTML text part of a multi-part message
3046          *
3047          * @param int msgNo the relative message number for the monitored mailbox
3048          * @param string $type the type of text processed, either 'PLAIN' or 'HTML'
3049          * @return string UTF-8 encoded version of the requested message text
3050          */
3051         function getMessageText($msgNo, $type, $structure, $fullHeader,$clean_email=true, $bcOffset = "") {
3052                 global $sugar_config;
3053
3054                 $msgPart = '';
3055                 $bc = $this->buildBreadCrumbs($structure->parts, $type);
3056                 //Add an offset if specified
3057                 if(!empty($bcOffset))
3058             $bc = $this->addBreadCrumbOffset($bc, $bcOffset);
3059
3060                 if(!empty($bc)) { // multi-part
3061                         // HUGE difference between PLAIN and HTML
3062                         if($type == 'PLAIN') {
3063                                 $msgPart = $this->getMessageTextFromSingleMimePart($msgNo,$bc,$structure);
3064                         } else {
3065                                 // get part of structure that will
3066                                 $msgPartRaw = '';
3067                                 $bcArray = $this->buildBreadCrumbsHTML($structure->parts,$bcOffset);
3068                                 // construct inline HTML/Rich msg
3069                                 foreach($bcArray as $bcArryKey => $bcArr) {
3070                                         foreach($bcArr as $type => $bcTrail) {
3071                                                 if($type == 'html')
3072                                                     $msgPartRaw .= $this->getMessageTextFromSingleMimePart($msgNo,$bcTrail,$structure);
3073                                                  else {
3074                                                         // deal with inline image
3075                                                         if(count($this->inlineImages > 0)) {
3076                                                                 $imageName = array_shift($this->inlineImages);
3077                                                                 $newImagePath = "class='image' src='{$sugar_config['site_url']}/{$sugar_config['cache_dir']}/images/{$imageName}'";
3078                                                                 $preImagePath = 'src="cid:'.substr($structure->parts[$bcArryKey]->id, 1, -1).'"';
3079                                                                 $msgPartRaw = str_replace($preImagePath, $newImagePath, $msgPartRaw);
3080                                                         }
3081                                                 }
3082                                         }
3083                                 }
3084                                 $msgPart = $msgPartRaw;
3085                         }
3086                 } else { // either PLAIN message type (flowed) or b0rk3d RFC
3087                         // make sure we're working on valid data here.
3088                         if($structure->subtype != $type) {
3089                                 return '';
3090                         }
3091
3092                         $decodedHeader = $this->decodeHeader($fullHeader);
3093
3094                         // now get actual body contents
3095                         $text = imap_body($this->conn, $msgNo);
3096
3097                         $upperCaseKeyDecodeHeader = array();
3098                         if (is_array($decodedHeader)) {
3099                                 $upperCaseKeyDecodeHeader = array_change_key_case($decodedHeader, CASE_UPPER);
3100                         } // if
3101                         if(isset($upperCaseKeyDecodeHeader[strtoupper('Content-Transfer-Encoding')])) {
3102                                 $flip = array_flip($this->transferEncoding);
3103                                 $text = $this->handleTranserEncoding($text, $flip[strtoupper($upperCaseKeyDecodeHeader[strtoupper('Content-Transfer-Encoding')])]);
3104                         }
3105
3106                         $msgPart = $text;
3107                         if(isset($upperCaseKeyDecodeHeader[strtoupper('Content-Type')]['charset']) && !empty($upperCaseKeyDecodeHeader[strtoupper('Content-Type')]['charset'])) {
3108                                 $msgPart = $this->handleCharsetTranslation($text, $upperCaseKeyDecodeHeader[strtoupper('Content-Type')]['charset']);
3109                         }
3110                 } // end else clause
3111
3112                 $msgPart = $this->customGetMessageText($msgPart);
3113                 /* cn: bug 9176 - htmlEntitites hide XSS attacks.
3114                  * decode to pass refreshed HTML to HTML_Safe */
3115                 if ($type == 'PLAIN')
3116                     return $this->cleanXssContent(to_html($msgPart));
3117                 else
3118                 {
3119             $safedMsgPart = $this->cleanContent($msgPart);
3120                     return str_replace("<img />", '', $safedMsgPart);
3121                 }
3122         }
3123
3124         /**
3125          * decodes raw header information and passes back an associative array with
3126          * the important elements key'd by name
3127          * @param header string the raw header
3128          * @return decodedHeader array the associative array
3129          */
3130         function decodeHeader($fullHeader) {
3131                 $decodedHeader = array();
3132                 $exHeaders = explode("\r", $fullHeader);
3133                 if (!is_array($exHeaders)) {
3134                         $exHeaders = explode("\r\n", $fullHeader);
3135                 }
3136                 $quotes = array('"', "'");
3137
3138                 foreach($exHeaders as $lineNum => $head) {
3139                         $key    = '';
3140                         $key    = trim(substr($head, 0, strpos($head, ':')));
3141                         $value  = '';
3142                         $value  = trim(substr($head, (strpos($head, ':') + 1), strlen($head)));
3143
3144                         // handle content-type section in headers
3145                         if(strtolower($key) == 'content-type' && strpos($value, ';')) { // ";" means something follows related to (such as Charset)
3146                                 $semiColPos = mb_strpos($value, ';');
3147                                 $strLenVal = mb_strlen($value);
3148                                 if(($semiColPos + 4) >= $strLenVal) {
3149                                         // the charset="[something]" is on the next line
3150                                         $value .= str_replace($quotes, "", trim($exHeaders[$lineNum+1]));
3151                                 }
3152
3153                                 $newValue = array();
3154                                 $exValue = explode(';', $value);
3155                                 $newValue['type'] = $exValue[0];
3156
3157                                 for($i=1; $i<count($exValue); $i++) {
3158                                         $exContent = explode('=', $exValue[$i]);
3159                                         $newValue[trim($exContent[0])] = trim($exContent[1]);
3160                                 }
3161                                 $value = $newValue;
3162                         }
3163
3164                         if(!empty($key) && !empty($value)) {
3165                                 $decodedHeader[$key] = $value;
3166                         }
3167                 }
3168
3169                 return $decodedHeader;
3170         }
3171
3172         /**
3173          * handles translating message text from orignal encoding into UTF-8
3174          *
3175          * @param string text test to be re-encoded
3176          * @param string charset original character set
3177          * @return string utf8 re-encoded text
3178          */
3179         function handleCharsetTranslation($text, $charset) {
3180                 global $locale;
3181
3182                 if(empty($charset)) {
3183                         $GLOBALS['log']->debug("***ERROR: InboundEmail::handleCharsetTranslation() called without a \$charset!");
3184                         $GLOBALS['log']->debug("***STACKTRACE: ".print_r(debug_backtrace(), true));
3185                         return $text;
3186                 }
3187
3188                 // typical headers have no charset - let destination pick (since it's all ASCII anyways)
3189                 if(strtolower($charset) == 'default' || strtolower($charset) == 'utf-8') {
3190                         return $text;
3191                 }
3192
3193                 return $locale->translateCharset($text, $charset);
3194         }
3195
3196
3197
3198         /**
3199          * Builds up the "breadcrumb" trail that imap_fetchbody() uses to return
3200          * parts of an email message, including attachments and inline images
3201          * @param       $parts  array of objects
3202          * @param       $subtype        what type of trail to return? HTML? Plain? binaries?
3203          * @param       $breadcrumb     text trail to build up
3204          */
3205         function buildBreadCrumbs($parts, $subtype, $breadcrumb = '0') {
3206                 //_pp('buildBreadCrumbs building for '.$subtype.' with BC at '.$breadcrumb);
3207                 // loop through available parts in the array
3208                 foreach($parts as $k => $part) {
3209                         // mark passage through level
3210                         $thisBc = ($k+1);
3211                         // if this is not the first time through, start building the map
3212                         if($breadcrumb != 0) {
3213                                 $thisBc = $breadcrumb.'.'.$thisBc;
3214                         }
3215
3216                         // found a multi-part/mixed 'part' - keep digging
3217                         if($part->type == 1 && (strtoupper($part->subtype) == 'RELATED' || strtoupper($part->subtype) == 'ALTERNATIVE' || strtoupper($part->subtype) == 'MIXED')) {
3218                                 //_pp('in loop: going deeper with subtype: '.$part->subtype.' $k is: '.$k);
3219                                 $thisBc = $this->buildBreadCrumbs($part->parts, $subtype, $thisBc);
3220                                 return $thisBc;
3221
3222                         } elseif(strtolower($part->subtype) == strtolower($subtype)) { // found the subtype we want, return the breadcrumb value
3223                                 //_pp('found '.$subtype.' bc! returning: '.$thisBc);
3224                                 return $thisBc;
3225                         } else {
3226                                 //_pp('found '.$part->subtype.' instead');
3227                         }
3228                 }
3229         }
3230
3231         /**
3232          * Similar to buildBreadCrumbs() but returns an ordered array containing all parts of the message that would be
3233          * considered "HTML" or Richtext (embedded images, formatting, etc.).
3234          * @param array parts Array of parts of a message
3235          * @param int breadcrumb Passed integer value to start breadcrumb trail
3236          * @param array stackedBreadcrumbs Persistent trail of breadcrumbs
3237          * @return array Ordered array of parts to retrieve via imap_fetchbody()
3238          */
3239         function buildBreadCrumbsHTML($parts, $breadcrumb = '0', $stackedBreadcrumbs = array()) {
3240                 $subtype = 'HTML';
3241                 $disposition = 'inline';
3242
3243                 foreach($parts as $k => $part) {
3244                         // mark passage through level
3245                         $thisBc = ($k+1);
3246
3247                         if($breadcrumb != 0) {
3248                                 $thisBc = $breadcrumb.'.'.$thisBc;
3249                         }
3250                         // found a multi-part/mixed 'part' - keep digging
3251                         if($part->type == 1 && (strtoupper($part->subtype) == 'RELATED' || strtoupper($part->subtype) == 'ALTERNATIVE' || strtoupper($part->subtype) == 'MIXED')) {
3252                                 $stackedBreadcrumbs = $this->buildBreadCrumbsHTML($part->parts, $thisBc, $stackedBreadcrumbs);
3253                         } elseif(
3254                                 (strtolower($part->subtype) == strtolower($subtype)) ||
3255                                         (
3256                                                 isset($part->disposition) && strtolower($part->disposition) == 'inline' &&
3257                                                 in_array(strtoupper($part->subtype), $this->imageTypes)
3258                                         )
3259                         ) {
3260                                 // found the subtype we want, return the breadcrumb value
3261                                 $stackedBreadcrumbs[] = array(strtolower($part->subtype) => $thisBc);
3262                         } elseif($part->type == 5) {
3263                                 $stackedBreadcrumbs[] = array(strtolower($part->subtype) => $thisBc);
3264                         }
3265                 }
3266
3267                 return $stackedBreadcrumbs;
3268         }
3269
3270         /**
3271          * Takes a PHP imap_* object's to/from/cc/bcc address field and converts it
3272          * to a standard string that SugarCRM expects
3273          * @param       $arr    an array of email address objects
3274          */
3275         function convertImapToSugarEmailAddress($arr) {
3276                 if(is_array($arr)) {
3277                         $addr = '';
3278                         foreach($arr as $key => $obj) {
3279                                 $addr .= $obj->mailbox.'@'.$obj->host.', ';
3280                         }
3281                         // strip last comma
3282                         $ret = substr_replace($addr,'',-2,-1);
3283                         return trim($ret);
3284                 }
3285         }
3286
3287         /**
3288          * tries to figure out what character set a given filename is using and
3289          * decode based on that
3290          *
3291          * @param string name Name of attachment
3292          * @return string decoded name
3293          */
3294         function handleEncodedFilename($name) {
3295                 $imapDecode = imap_mime_header_decode($name);
3296                 /******************************
3297                 $imapDecode => stdClass Object
3298                         (
3299                                 [charset] => utf-8
3300                                 [text] => w�hlen.php
3301                         )
3302
3303                                         OR
3304
3305                 $imapDecode => stdClass Object
3306                         (
3307                                 [charset] => default
3308                                 [text] => UTF-8''%E3%83%8F%E3%82%99%E3%82%A4%E3%82%AA%E3%82%AF%E3%82%99%E3%83%A9%E3%83%95%E3%82%A3%E3%83%BC.txt
3309                         )
3310                 *******************************/
3311                 if($imapDecode[0]->charset != 'default') { // mime-header encoded charset
3312                         $encoding = $imapDecode[0]->charset;
3313                         $name = $imapDecode[0]->text; // encoded in that charset
3314                 } else {
3315                         /* encoded filenames are formatted as [encoding]''[filename] */
3316                         if(strpos($name, "''") !== false) {
3317
3318                                 $encoding = substr($name, 0, strpos($name, "'"));
3319
3320                                 while(strpos($name, "'") !== false) {
3321                                         $name = trim(substr($name, (strpos($name, "'")+1), strlen($name)));
3322                                 }
3323                         }
3324                         $name = urldecode($name);
3325                 }
3326                 return (strtolower($encoding) == 'utf-8') ? $name : mb_convert_encoding($name, 'UTF-8', $encoding);
3327         }
3328
3329         /*
3330                 Primary body types for a part of a mail structure (imap_fetchstructure returned object)
3331                 0 => text
3332                 1 => multipart
3333                 2 => message
3334                 3 => application
3335                 4 => audio
3336                 5 => image
3337                 6 => video
3338                 7 => other
3339         */
3340         public $imap_types = array(
3341                 0 => 'text',
3342                 1 => 'multipart',
3343                 2 => 'message',
3344                 3 => 'application',
3345                 4 => 'audio',
3346                 5 => 'image',
3347                 6 => 'video',
3348         );
3349
3350         public function getMimeType($type, $subtype)
3351         {
3352                 if(isset($this->imap_types[$type])) {
3353                         return $this->imap_types[$type]."/$subtype";
3354                 } else {
3355                         return "other/$subtype";
3356                 }
3357                 
3358         }
3359
3360         /**
3361          * Takes the "parts" attribute of the object that imap_fetchbody() method
3362          * returns, and recursively goes through looking for objects that have a
3363          * disposition of "attachement" or "inline"
3364          * @param int $msgNo The relative message number for the monitored mailbox
3365          * @param object $parts Array of objects to examine
3366          * @param string $emailId The GUID of the email saved prior to calling this method
3367          * @param array $breadcrumb Default 0, build up of the parts mapping
3368          * @param bool $forDisplay Default false
3369          */
3370         function saveAttachments($msgNo, $parts, $emailId, $breadcrumb='0', $forDisplay) {
3371                 global $sugar_config;
3372
3373                 foreach($parts as $k => $part) {
3374                         $thisBc = $k+1;
3375                         if($breadcrumb != '0') {
3376                                 $thisBc = $breadcrumb.'.'.$thisBc;
3377                         }
3378                         // check if we need to recurse into the object
3379                         //if($part->type == 1 && !empty($part->parts)) {
3380                         if(isset($part->parts) && !empty($part->parts) && !( isset($part->subtype) && strtolower($part->subtype) == 'rfc822')  ) {
3381                                 $this->saveAttachments($msgNo, $part->parts, $emailId, $thisBc, $forDisplay);
3382                         } elseif($part->ifdisposition) {
3383                                 // we will take either 'attachments' or 'inline'
3384                                 if(strtolower($part->disposition) == 'attachment' || ((strtolower($part->disposition) == 'inline') && $part->type != 0)) {
3385                                         $attach = $this->getNoteBeanForAttachment($emailId);
3386                                         $fname = $this->handleEncodedFilename($this->retrieveAttachmentNameFromStructure($part->dparameters));
3387
3388                                         if(!empty($fname)) {//assign name to attachment
3389                                                 $attach->name = $fname;
3390                                         } else {//if name is empty, default to filename
3391                                                 $attach->name = urlencode($this->retrieveAttachmentNameFromStructure($part->dparameters));
3392                                         }
3393                                         $attach->filename = $attach->name;
3394                                         if (empty($attach->filename)) {
3395                                                 continue;
3396                                         }
3397
3398                                         // deal with the MIME types email has
3399                                         $attach->file_mime_type = $this->getMimeType($part->type, $part->subtype);
3400                                         $attach->safeAttachmentName();
3401                                         if($forDisplay) {
3402                                                 $attach->id = $this->getTempFilename();
3403                                         } else {
3404                                                 // only save if doing a full import, else we want only the binaries
3405                                                 $attach->save();
3406                                         }
3407                                         $this->saveAttachmentBinaries($attach, $msgNo, $thisBc, $part, $forDisplay);
3408                                 } // end if disposition type 'attachment'
3409                         }// end ifdisposition
3410                         //Retrieve contents of subtype rfc8822
3411                         elseif ($part->type == 2 && isset($part->subtype) && strtolower($part->subtype) == 'rfc822' )
3412                         {
3413                             $tmp_eml =  imap_fetchbody($this->conn, $msgNo, $thisBc);
3414                             $attach = $this->getNoteBeanForAttachment($emailId);
3415                             $attach->file_mime_type = 'messsage/rfc822';
3416                             $attach->description = $tmp_eml;
3417                             $attach->filename = 'bounce.eml';
3418                             $attach->safeAttachmentName();
3419                             if($forDisplay) {
3420                                 $attach->id = $this->getTempFilename();
3421                             } else {
3422                                 // only save if doing a full import, else we want only the binaries
3423                                 $attach->save();
3424                             }
3425                             $this->saveAttachmentBinaries($attach, $msgNo, $thisBc, $part, $forDisplay);
3426                         } elseif(!$part->ifdisposition && $part->type != 1 && $part->type != 2 && $thisBc != '1') {
3427                         // No disposition here, but some IMAP servers lie about disposition headers, try to find the truth
3428                                 // Also Outlook puts inline attachments as type 5 (image) without a disposition
3429                                 if($part->ifparameters) {
3430                     foreach($part->parameters as $param) {
3431                         if(strtolower($param->attribute) == "name") {
3432                             $fname = $this->handleEncodedFilename($param->value);
3433                         }
3434                     }
3435                     if(!isset($fname)) continue;
3436                                         // we assume that named parts are attachments too
3437                     $attach = $this->getNoteBeanForAttachment($emailId);
3438
3439                                         $attach->filename = $attach->name = $fname;
3440                                         $attach->file_mime_type = $this->getMimeType($part->type, $part->subtype);
3441
3442                                         $attach->safeAttachmentName();
3443                                         if($forDisplay) {
3444                                                 $attach->id = $this->getTempFilename();
3445                                         } else {
3446                                                 // only save if doing a full import, else we want only the binaries
3447                                                 $attach->save();
3448                                         }
3449                                         $this->saveAttachmentBinaries($attach, $msgNo, $thisBc, $part, $forDisplay);
3450                                 }
3451                         }
3452                 } // end foreach
3453         }
3454
3455         /**
3456          * Return a new note object for attachments.
3457          *
3458          * @param string $emailId
3459          * @return Note
3460          */
3461         function getNoteBeanForAttachment($emailId)
3462         {
3463             $attach = new Note();
3464             $attach->parent_id = $emailId;
3465             $attach->parent_type = 'Emails';
3466
3467             return $attach;
3468         }
3469
3470         /**
3471          * Return the filename of the attachment by examining the dparameters returned from imap_fetch_structure which
3472          * represet the content-disposition of the MIME header.
3473          *
3474          * @param array $dparamaters
3475          * @return string
3476          */
3477         function retrieveAttachmentNameFromStructure($dparamaters)
3478         {
3479            $result = "";
3480
3481            foreach ($dparamaters as $k => $v)
3482            {
3483                if( strtolower($v->attribute) == 'filename')
3484                {
3485                    $result = $v->value;
3486                    break;
3487                }
3488            }
3489
3490            return $result;
3491
3492     }
3493         /**
3494          * saves the actual binary file of a given attachment
3495          * @param object attach Note object that is attached to the binary file
3496          * @param string msgNo Message Number on IMAP/POP3 server
3497          * @param string thisBc Breadcrumb to navigate email structure to find the content
3498          * @param object part IMAP standard object that contains the "parts" of this section of email
3499          * @param bool $forDisplay
3500          */
3501         function saveAttachmentBinaries($attach, $msgNo, $thisBc, $part, $forDisplay) {
3502                 global $sugar_config;
3503
3504                 // decide where to place the file temporarily
3505                 $uploadDir = $sugar_config['upload_dir']; // typically "cache/uploads/"
3506                 $uploadDir = ($forDisplay) ? "{$sugar_config['cache_dir']}modules/Emails/{$this->id}/attachments/" : $uploadDir;
3507
3508                 // decide what name to save file as
3509                 $fileName = $attach->id;
3510
3511                 // deal with attachment encoding and decode the text string
3512                 if(!file_exists($uploadDir.$fileName)) {
3513                         $msgPartRaw = imap_fetchbody($this->conn, $msgNo, $thisBc);
3514                         $msgPart = $this->handleTranserEncoding($msgPartRaw, $part->encoding);
3515
3516                         if($fp = fopen($uploadDir.$fileName, 'wb')) {
3517                                 if(fwrite($fp, $msgPart)) {
3518                                         $this->tempAttachment[$fileName] = urldecode($attach->filename);
3519                                         $GLOBALS['log']->debug('InboundEmail saved attachment file: '.$attach->filename);
3520                                 } else {
3521                                         $GLOBALS['log']->debug('InboundEmail could not create attachment file: '.$attach->filename ." - temp file target: [ {$uploadDir}{$fileName} ]");
3522                                 }
3523                                 fclose($fp);
3524
3525                                 // if all was successful, feel for inline and cache Note ID for display:
3526                                 if((strtolower($part->disposition) == 'inline' && in_array($part->subtype, $this->imageTypes))
3527                                         || ($part->type == 5)) {
3528                                         if(copy($uploadDir.$fileName,
3529                                                 "{$sugar_config['cache_dir']}/images/{$fileName}.".strtolower($part->subtype))) {
3530                                                 $this->inlineImages[] = $attach->id.".".strtolower($part->subtype);
3531                                         }
3532                                 }
3533                         } else {
3534                                 $GLOBALS['log']->debug('InboundEmail could not open a filepointer to: '.$uploadDir.$fileName);
3535                         }
3536                 } else {
3537                         // binary is in cache already, just prep necessary metadata
3538                         $this->tempAttachment[$fileName] = urldecode($attach->filename);
3539                 }
3540         }
3541
3542         /**
3543          * decodes a string based on its associated encoding
3544          * if nothing is passed, we default to no-encoding type
3545          * @param       $str    encoded string
3546          * @param       $enc    detected encoding
3547          */
3548         function handleTranserEncoding($str, $enc=0) {
3549                 switch($enc) {
3550                         case 2:// BINARY
3551                                 $ret = $str;
3552                                 break;
3553                         case 3:// BASE64
3554                                 $ret = base64_decode($str);
3555                                 break;
3556                         case 4:// QUOTED-PRINTABLE
3557                                 $ret = quoted_printable_decode($str);
3558                                 break;
3559                         case 0:// 7BIT or 8BIT
3560                         case 1:// already in a string-useable format - do nothing
3561                         case 5:// OTHER
3562                         default:// catch all
3563                                 $ret = $str;
3564                                 break;
3565                 }
3566
3567                 return $ret;
3568         }
3569
3570
3571         /**
3572          * Some emails do not get assigned a message_id, specifically from
3573          * Outlook/Exchange.
3574          *
3575          * We need to derive a reliable one for duplicate import checking.
3576          */
3577         function getMessageId($header) {
3578                 $message_id = md5(print_r($header, true));
3579                 return $message_id;
3580         }
3581
3582         /**
3583          * checks for duplicate emails on polling.  The uniqueness of a given email message is determined by a concatenation
3584          * of 2 values, the messageID and the delivered-to field.  This allows multiple To: and B/CC: destination addresses
3585          * to be imported by Sugar without violating the true duplicate-email issues.
3586          *
3587          * @param string message_id message ID generated by sending server
3588          * @param int message number (mailserver's key) of email
3589          * @param object header object generated by imap_headerinfo()
3590          * @param string textHeader Headers in normal text format
3591          * @return bool
3592          */
3593         function importDupeCheck($message_id, $header, $textHeader) {
3594                 $GLOBALS['log']->debug('*********** InboundEmail doing dupe check.');
3595
3596                 // generate "delivered-to" seed for email duplicate check
3597                 $deliveredTo = $this->id; // cn: bug 12236 - cc's failing dupe check
3598                 $exHeader = explode("\n", $textHeader);
3599
3600                 foreach($exHeader as $headerLine) {
3601                         if(strpos(strtolower($headerLine), 'delivered-to:') !== false) {
3602                                 $deliveredTo = substr($headerLine, strpos($headerLine, " "), strlen($headerLine));
3603                                 $GLOBALS['log']->debug('********* InboundEmail found [ '.$deliveredTo.' ] as the destination address for email [ '.$message_id.' ]');
3604                         } elseif(strpos(strtolower($headerLine), 'x-real-to:') !== false) {
3605                                 $deliveredTo = substr($headerLine, strpos($headerLine, " "), strlen($headerLine));
3606                                 $GLOBALS['log']->debug('********* InboundEmail found [ '.$deliveredTo.' ] for non-standards compliant email x-header [ '.$message_id.' ]');
3607                         }
3608                 }
3609
3610                 //if(empty($message_id) && !isset($message_id)) {
3611                 if(empty($message_id) || !isset($message_id)) {
3612                         $GLOBALS['log']->debug('*********** NO MESSAGE_ID.');
3613                         $message_id = $this->getMessageId($header);
3614                 }
3615
3616                 // generate compound messageId
3617                 $this->compoundMessageId = trim($message_id).trim($deliveredTo);
3618                 // if the length > 255 then md5 it so that the data will be of smaller length
3619                 if (strlen($this->compoundMessageId) > 255) {
3620                         $this->compoundMessageId = md5($this->compoundMessageId);
3621                 } // if
3622
3623                 if (empty($this->compoundMessageId)) {
3624                         $GLOBALS['log']->error('Inbound Email found a message without a header and message_id');
3625                         return false;
3626                 } // if
3627
3628                 $potentials = clean_xss($this->compoundMessageId, false);
3629
3630                 if(is_array($potentials) && !empty($potentials)) {
3631                         foreach($potentials as $bad) {
3632                                 $this->compoundMessageId = str_replace($bad, "", $this->compoundMessageId);
3633                         }
3634                 }
3635
3636                 $query = 'SELECT count(emails.id) AS c FROM emails WHERE emails.message_id = \''.$this->compoundMessageId.'\' and emails.deleted = 0';
3637                 $r = $this->db->query($query, true);
3638                 $a = $this->db->fetchByAssoc($r);
3639
3640                 if($a['c'] > 0) {
3641                         $GLOBALS['log']->debug('InboundEmail found a duplicate email with ID ('.$this->compoundMessageId.')');
3642                         return false; // we have a dupe and don't want to import the email'
3643                 } else {
3644                         return true;
3645                 }
3646         }
3647
3648         /**
3649          * takes the output from imap_mime_hader_decode() and handles multiple types of encoding
3650          * @param string subject Raw subject string from email
3651          * @return string ret properly formatted UTF-8 string
3652          */
3653         function handleMimeHeaderDecode($subject) {
3654                 $subjectDecoded = imap_mime_header_decode($subject);
3655
3656                 $ret = '';
3657                 foreach($subjectDecoded as $object) {
3658                         if($object->charset != 'default') {
3659                                 $ret .= $this->handleCharsetTranslation($object->text, $object->charset);
3660                         } else {
3661                                 $ret .= $object->text;
3662                         }
3663                 }
3664                 return $ret;
3665         }
3666
3667         /**
3668          * Cleans content for XSS and other types of attack vectors
3669          * @param string str String to clean
3670          * @return string
3671          */
3672         function cleanContent($str) {
3673                 // Safe_HTML
3674                 $this->safe->clear();
3675                 $str = $this->safe->parse($str);
3676                 return $this->cleanXssContent($str);
3677         }
3678
3679         /**
3680          * Cleans content for XSS
3681          * @param string str String to clean
3682          * @return string
3683          */
3684         function cleanXssContent($str) {
3685
3686                 $potentials = clean_xss($str, false);
3687                 if(is_array($potentials) && !empty($potentials)) {
3688                         foreach($potentials as $bad) {
3689                                 $str = str_replace($bad, "", $str);
3690                         }
3691                 }
3692                 return $str;
3693         }
3694         /**
3695          * Calculates the appropriate display date/time sent for an email.
3696          * @param string headerDate The date sent of email in MIME header format
3697          * @return string GMT-0 Unix timestamp
3698          */
3699         function getUnixHeaderDate($headerDate) {
3700                 global $timedate;
3701
3702                 if (empty($headerDate)) {
3703                         return "";
3704                 }
3705                 ///////////////////////////////////////////////////////////////////
3706                 ////    CALCULATE CORRECT SENT DATE/TIME FOR EMAIL
3707                 if(!empty($headerDate)) {
3708                         // need to hack PHP/windows' bad handling of strings when using POP3
3709                         if(strstr($headerDate,'+0000 GMT')) {
3710                                 $headerDate = str_replace('GMT','', $headerDate);
3711                         } elseif(!strtotime($headerDate)) {
3712                                 $headerDate = 'now'; // catch non-standard format times.
3713                         } else {
3714                                 // cn: bug 9196 parse the GMT offset
3715                                 if(strpos($headerDate, '-') || strpos($headerDate, '+')) {
3716                                         // cn: bug make sure last 5 chars are [+|-]nnnn
3717                                         if(strpos($headerDate, "(")) {
3718                                                 $headerDate = preg_replace("/\([\w]+\)/i", "", $headerDate);
3719                                                 $headerDate = trim($headerDate);
3720                                         }
3721
3722                                         // parse mailserver time
3723                                         $gmtEmail = trim(substr($headerDate, -5, 5));
3724                                         $posNeg = substr($gmtEmail, 0, 1);
3725                                         $gmtHours = substr($gmtEmail, 1, 2);
3726                                         $gmtMins = substr($gmtEmail, -2, 2);
3727
3728                                         // get seconds
3729                                         $secsHours = $gmtHours * 60 * 60;
3730                                         $secsTotal = $secsHours + ($gmtMins * 60);
3731                                         $secsTotal = ($posNeg == '-') ? $secsTotal : -1 * $secsTotal;
3732
3733                                         $headerDate = trim(substr_replace($headerDate, '', -5)); // mfh: bug 10961/12855 - date time values with GMT offsets not properly formatted
3734                                 }
3735                         }
3736                 } else {
3737                         $headerDate = 'now';
3738                 }
3739
3740                 $unixHeaderDate = strtotime($headerDate);
3741
3742                 if(isset($secsTotal)) {
3743                         // this gets the timestamp to true GMT-0
3744                         $unixHeaderDate += $secsTotal;
3745                 }
3746
3747                 if(strtotime('Jan 1, 2001') > $unixHeaderDate) {
3748                         $unixHeaderDate = strtotime('now');
3749                 }
3750
3751                 // now get it to user's datetime format for save
3752 //              $gmt0dateTime = $timedate->to_display_date_time(date('Y-m-d H:i:s', $unixHeaderDate));
3753 //              $gmt0dateTime = $timedate->swap_formats($gmt0dateTime, $timedate->get_date_time_format(), $timedate->get_db_date_time_format());
3754 //              $unixHeaderDate = strtotime($gmt0dateTime);
3755 //
3756                 return $unixHeaderDate;
3757                 ////    END CALCULATE CORRECT SENT DATE/TIME FOR EMAIL
3758                 ///////////////////////////////////////////////////////////////////
3759         }
3760
3761         /**
3762          * This method returns the correct messageno for the pop3 protocol
3763          * @param String UIDL
3764          * @return returnMsgNo
3765          */
3766         function getCorrectMessageNoForPop3($messageId) {
3767                 $returnMsgNo = -1;
3768                 if ($this->protocol == 'pop3') {
3769                         if($this->pop3_open()) {
3770                                 // get the UIDL from database;
3771                                 $query = "SELECT msgno FROM email_cache WHERE ie_id = '{$this->id}' AND message_id = '{$messageId}'";
3772                                 $r = $this->db->query($query);
3773                                 $a = $this->db->fetchByAssoc($r);
3774                                 $msgNo = $a['msgno'];
3775                                 $returnMsgNo = $msgNo;
3776
3777                                 // authenticate
3778                                 $this->pop3_sendCommand("USER", $this->email_user);
3779                                 $this->pop3_sendCommand("PASS", $this->email_password);
3780
3781                                 // get UIDL for this msgNo
3782                                 $this->pop3_sendCommand("UIDL {$msgNo}", '', false); // leave socket buffer alone until the while()
3783                                 $buf = fgets($this->pop3socket, 1024); // handle "OK+ msgNo UIDL(UIDL for this messageno)";
3784
3785                                 // if it returns OK then we have found the message else get all the UIDL
3786                                 // and search for the correct msgNo;
3787                                 $foundMessageNo = false;
3788                                 if (preg_match("/OK/", $buf) > 0) {
3789                                         $mailserverResponse = explode(" ", $buf);
3790                                         // if the cachedUIDL and the UIDL from mail server matches then its the correct messageno
3791                                         if (trim($mailserverResponse[sizeof($mailserverResponse) - 1]) == $messageId) {
3792                                                 $foundMessageNo = true;
3793                                         }
3794                                 } //if
3795
3796                                 //get all the UIDL and then find the correct messageno
3797                                 if (!$foundMessageNo) {
3798                                         // get UIDLs
3799                                         $this->pop3_sendCommand("UIDL", '', false); // leave socket buffer alone until the while()
3800                                         fgets($this->pop3socket, 1024); // handle "OK+";
3801                                         $UIDLs = array();
3802                                         $buf = '!';
3803                                         if(is_resource($this->pop3socket)) {
3804                                                 while(!feof($this->pop3socket)) {
3805                                                         $buf = fgets($this->pop3socket, 1024); // 8kb max buffer - shouldn't be more than 80 chars via pop3...
3806                                                         if(trim($buf) == '.') {
3807                                                                 $GLOBALS['log']->debug("*** GOT '.'");
3808                                                                 break;
3809                                                         } // if
3810                                                         // format is [msgNo] [UIDL]
3811                                                         $exUidl = explode(" ", $buf);
3812                                                         $UIDLs[trim($exUidl[1])] = trim($exUidl[0]);
3813                                                 } // while
3814                                                 if (array_key_exists($messageId, $UIDLs)) {
3815                                                         $returnMsgNo = $UIDLs[$messageId];
3816                                                 } else {
3817                                                         // message could not be found on server
3818                                                         $returnMsgNo = -1;
3819                                                 } // else
3820                                         } // if
3821
3822                                 } // if
3823                                 $this->pop3_cleanUp();
3824                         } //if
3825                 } //if
3826                 return $returnMsgNo;
3827         }
3828
3829         /**
3830          * If the importOneEmail returns false, then findout if the duplicate email
3831          */
3832         function getDuplicateEmailId($msgNo, $uid) {
3833                 if(!class_exists('Email')) {
3834
3835                 }
3836                 global $timedate;
3837                 global $app_strings;
3838                 global $app_list_strings;
3839                 global $sugar_config;
3840                 global $current_user;
3841
3842                 $header = imap_headerinfo($this->conn, $msgNo);
3843                 $fullHeader = imap_fetchheader($this->conn, $msgNo); // raw headers
3844
3845                 // reset inline images cache
3846                 $this->inlineImages = array();
3847
3848                 // handle messages deleted on server
3849                 if(empty($header)) {
3850                         if(!isset($this->email) || empty($this->email)) {
3851                                 $this->email = new Email();
3852                         } // if
3853                         return "";
3854                 } else {
3855                         $dupeCheckResult = $this->importDupeCheck($header->message_id, $header, $fullHeader);
3856                         if (!$dupeCheckResult && !empty($this->compoundMessageId)) {
3857                                 // we have a duplicate email
3858                                 $query = 'SELECT id FROM emails WHERE emails.message_id = \''.$this->compoundMessageId.'\' and emails.deleted = 0';
3859                                 $r = $this->db->query($query, true);
3860                                 $a = $this->db->fetchByAssoc($r);
3861
3862                                 $this->email = new Email();
3863                                 $this->email->id = $a['id'];
3864                                 return $a['id'];
3865                         } // if
3866                         return "";
3867                 } // else
3868         } // fn
3869
3870
3871         /**
3872          * shiny new importOneEmail() method
3873          * @param int msgNo
3874          * @param bool forDisplay
3875          * @param clean_email boolean, default true,
3876          */
3877         function importOneEmail($msgNo, $uid, $forDisplay=false, $clean_email=true) {
3878                 if(!class_exists('Email')) {
3879
3880                 }
3881
3882                 $GLOBALS['log']->debug("InboundEmail processing 1 email {$msgNo}-----------------------------------------------------------------------------------------");
3883                 global $timedate;
3884                 global $app_strings;
3885                 global $app_list_strings;
3886                 global $sugar_config;
3887                 global $current_user;
3888
3889                 $header = imap_headerinfo($this->conn, $msgNo);
3890                 $fullHeader = imap_fetchheader($this->conn, $msgNo); // raw headers
3891
3892                 // reset inline images cache
3893                 $this->inlineImages = array();
3894
3895                 // handle messages deleted on server
3896                 if(empty($header)) {
3897                         if(!isset($this->email) || empty($this->email)) {
3898                                 $this->email = new Email();
3899                         }
3900
3901                         $q = "";
3902                         if ($this->isPop3Protocol()) {
3903                                 $this->email->name = $app_strings['LBL_EMAIL_ERROR_MESSAGE_DELETED'];
3904                                 $q = "DELETE FROM email_cache WHERE message_id = '{$uid}' AND ie_id = '{$this->id}' AND mbox = '{$this->mailbox}'";
3905                         } else {
3906                                 $this->email->name = $app_strings['LBL_EMAIL_ERROR_IMAP_MESSAGE_DELETED'];
3907                                 $q = "DELETE FROM email_cache WHERE imap_uid = {$uid} AND ie_id = '{$this->id}' AND mbox = '{$this->mailbox}'";
3908                         } // else
3909                         // delete local cache
3910                         $r = $this->db->query($q);
3911
3912                         $this->email->date_sent = date('Y-m-d H:i:s');
3913                         return false;
3914                         //return "Message deleted from server.";
3915                 }
3916
3917                 ///////////////////////////////////////////////////////////////////////
3918                 ////    DUPLICATE CHECK
3919                 $dupeCheckResult = $this->importDupeCheck($header->message_id, $header, $fullHeader);
3920                 if($forDisplay || $dupeCheckResult) {
3921                         $GLOBALS['log']->debug('*********** NO duplicate found, continuing with processing.');
3922
3923                         $structure = imap_fetchstructure($this->conn, $msgNo); // map of email
3924
3925                         ///////////////////////////////////////////////////////////////////
3926                         ////    CREATE SEED EMAIL OBJECT
3927                         $email = new Email();
3928                         $email->isDuplicate = ($dupeCheckResult) ? false : true;
3929                         $email->mailbox_id = $this->id;
3930                         $message = array();
3931                         $email->id = create_guid();
3932                         $email->new_with_id = true; //forcing a GUID here to prevent double saves.
3933                         ////    END CREATE SEED EMAIL
3934                         ///////////////////////////////////////////////////////////////////
3935
3936                         ///////////////////////////////////////////////////////////////////
3937                         ////    PREP SYSTEM USER
3938                         if(empty($current_user)) {
3939                                 // I-E runs as admin, get admin prefs
3940
3941                                 $current_user = new User();
3942                                 $current_user->getSystemUser();
3943                         }
3944                         $tPref = $current_user->getUserDateTimePreferences();
3945                         ////    END USER PREP
3946                         ///////////////////////////////////////////////////////////////////
3947
3948                         $unixHeaderDate = $this->getUnixHeaderDate($header->date);
3949
3950                         ///////////////////////////////////////////////////////////////////
3951                         ////    HANDLE EMAIL ATTACHEMENTS OR HTML TEXT
3952                         ////    Inline images require that I-E handle attachments before body text
3953                         // parts defines attachments - be mindful of .html being interpreted as an attachment
3954                         if($structure->type == 1 && !empty($structure->parts)) {
3955                                 $GLOBALS['log']->debug('InboundEmail found multipart email - saving attachments if found.');
3956                                 $this->saveAttachments($msgNo, $structure->parts, $email->id, 0, $forDisplay);
3957                         } elseif($structure->type == 0) {
3958                                 $uuemail = ($this->isUuencode($email->description)) ? true : false;
3959                                 /*
3960                                  * UUEncoded attachments - legacy, but still have to deal with it
3961                                  * format:
3962                                  * begin 777 filename.txt
3963                                  * UUENCODE
3964                                  *
3965                                  * end
3966                                  */
3967                                 // set body to the filtered one
3968                                 if($uuemail) {
3969                                         $email->description = $this->handleUUEncodedEmailBody($email->description, $email->id);
3970                                         $email->retrieve($email->id);
3971                                         $email->save();
3972                                 }
3973                         } else {
3974                                 if($this->port != 110) {
3975                                         $GLOBALS['log']->debug('InboundEmail found a multi-part email (id:'.$msgNo.') with no child parts to parse.');
3976                                 }
3977                         }
3978                         ////    END HANDLE EMAIL ATTACHEMENTS OR HTML TEXT
3979                         ///////////////////////////////////////////////////////////////////
3980
3981                         ///////////////////////////////////////////////////////////////////
3982                         ////    ASSIGN APPROPRIATE ATTRIBUTES TO NEW EMAIL OBJECT
3983                         // handle UTF-8/charset encoding in the ***headers***
3984                         global $db;
3985                         //bug #33929 added quoteForEmail() to replace single quote
3986                         $email->name                    = $this->handleMimeHeaderDecode($header->subject);
3987                         $unixHeaderDate = (!empty($unixHeaderDate)) ? date($timedate->get_db_date_time_format(), $unixHeaderDate) : "";
3988                         $email->date_start = (!empty($unixHeaderDate)) ? $timedate->to_display_date($unixHeaderDate) : "";
3989                         $email->time_start = (!empty($unixHeaderDate)) ? $timedate->to_display_time($unixHeaderDate) : "";
3990                         $email->type = 'inbound';
3991                         $email->date_created = (!empty($unixHeaderDate)) ? $timedate->to_display_date_time($unixHeaderDate) : "";
3992                         $email->status = 'unread'; // this is used in Contacts' Emails SubPanel
3993                         if(!empty($header->toaddress)) {
3994                                 $email->to_name  = $this->handleMimeHeaderDecode($header->toaddress);
3995                                 $email->to_addrs_names = $email->to_name;
3996                         }
3997                         if(!empty($header->to)) {
3998                                 $email->to_addrs        = $this->convertImapToSugarEmailAddress($header->to);
3999                         }
4000                         $email->from_name               = $this->handleMimeHeaderDecode($header->fromaddress);
4001                         $email->from_addr_name = $email->from_name;
4002                         $email->from_addr               = $this->convertImapToSugarEmailAddress($header->from);
4003                         if(!empty($header->cc)) {
4004                                 $email->cc_addrs        = $this->convertImapToSugarEmailAddress($header->cc);
4005                         }
4006                         if(!empty($header->ccaddress)) {
4007                                 $email->cc_addrs_names   = $this->handleMimeHeaderDecode($header->ccaddress);
4008                         } // if
4009                         $email->reply_to_name   = $this->handleMimeHeaderDecode($header->reply_toaddress);
4010                         $email->reply_to_email  = $this->convertImapToSugarEmailAddress($header->reply_to);
4011                         if (!empty($email->reply_to_email)) {
4012                                 $email->reply_to_addr   = $email->reply_to_name;
4013                         }
4014                         $email->intent                  = $this->mailbox_type;
4015
4016                         $email->message_id              = $this->compoundMessageId; // filled by importDupeCheck();
4017
4018                         // handle multi-part email bodies
4019                         $email->description_html= $this->getMessageText($msgNo, 'HTML', $structure, $fullHeader,$clean_email); // runs through handleTranserEncoding() already
4020                         $email->description     = $this->getMessageText($msgNo, 'PLAIN', $structure, $fullHeader,$clean_email); // runs through handleTranserEncoding() already
4021
4022                         // empty() check for body content
4023                         if(empty($email->description)) {
4024                                 $GLOBALS['log']->debug('InboundEmail Message (id:'.$email->message_id.') has no body');
4025                         }
4026
4027                         // assign_to group
4028                         if (!empty($_REQUEST['user_id'])) {
4029                                 $email->assigned_user_id = $_REQUEST['user_id'];
4030                         } else {
4031                                 // Samir Gandhi : Commented out this code as its not needed
4032                                 //$email->assigned_user_id = $this->group_id;
4033                         }
4034
4035                 //Assign Parent Values if set
4036                 if (!empty($_REQUEST['parent_id']) && !empty($_REQUEST['parent_type'])) {
4037                 $email->parent_id = $_REQUEST['parent_id'];
4038                 $email->parent_type = $_REQUEST['parent_type'];
4039                 $mod = strtolower($email->parent_type);
4040                 $rel = array_key_exists($mod, $email->field_defs) ? $mod : $mod . "_activities_emails"; //Custom modules rel name
4041
4042                 if(! $email->load_relationship($rel) )
4043                     return FALSE;
4044                 $email->$rel->add($email->parent_id);
4045                 }
4046
4047                         // override $forDisplay w/user pref
4048                         if($forDisplay) {
4049                                 if($this->isAutoImport()) {
4050                                         $forDisplay = false; // triggers save of imported email
4051                                 }
4052                         }
4053
4054                         if(!$forDisplay) {
4055                                 $email->save();
4056
4057                                 $email->new_with_id = false; // to allow future saves by UPDATE, instead of INSERT
4058                                 ////    ASSIGN APPROPRIATE ATTRIBUTES TO NEW EMAIL OBJECT
4059                                 ///////////////////////////////////////////////////////////////////
4060
4061                                 ///////////////////////////////////////////////////////////////////
4062                                 ////    LINK APPROPRIATE BEANS TO NEWLY SAVED EMAIL
4063                                 //$contactAddr = $this->handleLinking($email);
4064                                 ////    END LINK APPROPRIATE BEANS TO NEWLY SAVED EMAIL
4065                                 ///////////////////////////////////////////////////////////////////
4066
4067                                 ///////////////////////////////////////////////////////////////////
4068                                 ////    MAILBOX TYPE HANDLING
4069                                 $this->handleMailboxType($email, $header);
4070                                 ////    END MAILBOX TYPE HANDLING
4071                                 ///////////////////////////////////////////////////////////////////
4072
4073                                 ///////////////////////////////////////////////////////////////////
4074                                 ////    SEND AUTORESPONSE
4075                                 if(!empty($email->reply_to_email)) {
4076                                         $contactAddr = $email->reply_to_email;
4077                                 } else {
4078                                         $contactAddr = $email->from_addr;
4079                                 }
4080                                 if (!$this->isMailBoxTypeCreateCase()) {
4081                                         $this->handleAutoresponse($email, $contactAddr);
4082                                 }
4083                                 ////    END SEND AUTORESPONSE
4084                                 ///////////////////////////////////////////////////////////////////
4085                                 ////    END IMPORT ONE EMAIL
4086                                 ///////////////////////////////////////////////////////////////////
4087                         }
4088                 } else {
4089                         // only log if not POP3; pop3 iterates through ALL mail
4090                         if($this->protocol != 'pop3') {
4091                                 $GLOBALS['log']->info("InboundEmail found a duplicate email: ".$header->message_id);
4092                                 //echo "This email has already been imported";
4093                         }
4094                         return false;
4095                 }
4096                 ////    END DUPLICATE CHECK
4097                 ///////////////////////////////////////////////////////////////////////
4098
4099                 ///////////////////////////////////////////////////////////////////////
4100                 ////    DEAL WITH THE MAILBOX
4101                 if(!$forDisplay) {
4102                         imap_setflag_full($this->conn, $msgNo, '\\SEEN');
4103
4104                         // if delete_seen, mark msg as deleted
4105                         if($this->delete_seen == 1  && !$forDisplay) {
4106                                 $GLOBALS['log']->info("INBOUNDEMAIL: delete_seen == 1 - deleting email");
4107                                 imap_setflag_full($this->conn, $msgNo, '\\DELETED');
4108                         }
4109                 } else {
4110                         // for display - don't touch server files?
4111                         //imap_setflag_full($this->conn, $msgNo, '\\UNSEEN');
4112                 }
4113
4114                 $GLOBALS['log']->debug('********************************* InboundEmail finished import of 1 email: '.$email->name);
4115                 ////    END DEAL WITH THE MAILBOX
4116                 ///////////////////////////////////////////////////////////////////////
4117
4118                 ///////////////////////////////////////////////////////////////////////
4119                 ////    TO SUPPORT EMAIL 2.0
4120                 $this->email = $email;
4121
4122                 if(empty($this->email->et)) {
4123                         $this->email->email2init();
4124                 }
4125
4126                 return true;
4127         }
4128
4129         /**
4130          * figures out if a plain text email body has UUEncoded attachments
4131          * @param string string The email body
4132          * @return bool True if UUEncode is detected.
4133          */
4134         function isUuencode($string) {
4135                 $rx = "begin [0-9]{3} .*";
4136
4137                 $exBody = explode("\r", $string);
4138                 foreach($exBody as $line) {
4139                         if(preg_match("/begin [0-9]{3} .*/i", $line)) {
4140                                 return true;
4141                         }
4142                 }
4143
4144                 return false;
4145         }
4146
4147         /**
4148          * handles UU Encoded emails - a legacy from pre-RFC 822 which must still be supported (?)
4149          * @param string raw The raw email body
4150          * @param string id Parent email ID
4151          * @return string The filtered email body, stripped of attachments
4152          */
4153         function handleUUEncodedEmailBody($raw, $id) {
4154                 global $locale;
4155
4156                 $emailBody = '';
4157                 $attachmentBody = '';
4158                 $inAttachment = false;
4159
4160                 $exRaw = explode("\n", $raw);
4161
4162                 foreach($exRaw as $k => $line) {
4163                         $line = trim($line);
4164
4165                         if(preg_match("/begin [0-9]{3} .*/i", $line, $m)) {
4166                                 $inAttachment = true;
4167                                 $fileName = $this->handleEncodedFilename(substr($m[0], 10, strlen($m[0])));
4168
4169                                 $attachmentBody = ''; // reset for next part of loop;
4170                                 continue;
4171                         }
4172
4173                         // handle "end"
4174                         if(strpos($line, "end") === 0) {
4175                                 if(!empty($fileName) && !empty($attachmentBody)) {
4176                                         $this->handleUUDecode($id, $fileName, trim($attachmentBody));
4177                                         $attachmentBody = ''; // reset for next part of loop;
4178                                 }
4179                         }
4180
4181                         if($inAttachment === false) {
4182                                 $emailBody .= "\n".$line;
4183                         } else {
4184                                 $attachmentBody .= "\n".$line;
4185                         }
4186                 }
4187
4188                 /* since UUEncode was developed before MIME, we have NO idea what character set encoding was used.  we will assume the user's locale character set */
4189                 $emailBody = $locale->translateCharset($emailBody, $locale->getExportCharset(), 'UTF-8');
4190                 return $emailBody;
4191         }
4192
4193         /**
4194          * wrapper for UUDecode
4195          * @param string id Id of the email
4196          * @param string UUEncode Encode US-ASCII
4197          */
4198         function handleUUDecode($id, $fileName, $UUEncode) {
4199                 global $sugar_config;
4200                 /* include PHP_Compat library; it auto-feels for PHP5's compiled convert_uuencode() function */
4201                 require_once('include/PHP_Compat/convert_uudecode.php');
4202
4203
4204                 $attach = new Note();
4205                 $attach->parent_id = $id;
4206                 $attach->parent_type = 'Emails';
4207
4208                 $fname = $this->handleEncodedFilename($fileName);
4209
4210                 if(!empty($fname)) {//assign name to attachment
4211                         $attach->name = $fname;
4212                 } else {//if name is empty, default to filename
4213                         $attach->name = urlencode($fileName);
4214                 }
4215
4216                 $attach->filename = urlencode($attach->name);
4217
4218                 //get position of last "." in file name
4219                 $file_ext_beg = strrpos($attach->filename,".");
4220                 $file_ext = "";
4221                 //get file extension
4222                 if($file_ext_beg >0) {
4223                         $file_ext = substr($attach->filename, $file_ext_beg+1);
4224                 }
4225                 //check to see if this is a file with extension located in "badext"
4226                 foreach($sugar_config['upload_badext'] as $badExt) {
4227                         if(strtolower($file_ext) == strtolower($badExt)) {
4228                                 //if found, then append with .txt and break out of lookup
4229                                 $attach->name = $attach->name . ".txt";
4230                                 $attach->file_mime_type = 'text/';
4231                                 $attach->filename = $attach->filename . ".txt";
4232                                 break; // no need to look for more
4233                         }
4234                 }
4235                 $attach->save();
4236
4237                 $bin = convert_uudecode($UUEncode);
4238                 if($fp = fopen($sugar_config['upload_dir'].$attach->id, 'wb')) {
4239                         if(fwrite($fp, $bin)) {
4240                                 $GLOBALS['log']->debug('InboundEmail saved attachment file: '.$attach->filename);
4241                         } else {
4242                                 $GLOBALS['log']->debug('InboundEmail could not create attachment file: '.$attach->filename);
4243                         }
4244                         fclose($fp);
4245                 } else {
4246                         //kbrill Bug#17125
4247                         $GLOBALS['log']->debug('InboundEmail could not open a filepointer to: '.$sugar_config['upload_dir'].$attach->id);
4248                 }
4249         }
4250
4251         /**
4252          * returns true if the email's domain is NOT in the filter domain string
4253          *
4254          * @param object email Email object in question
4255          * @return bool true if not filtered, false if filtered
4256          */
4257         function checkFilterDomain($email) {
4258                 $filterDomain = $this->get_stored_options('filter_domain');
4259                 if(!isset($filterDomain) || empty($filterDomain)) {
4260                         return true; // nothing set for this
4261                 } else {
4262                         $replyTo = strtolower($email->reply_to_email);
4263                         $from = strtolower($email->from_addr);
4264                         $filterDomain = '@'.strtolower($filterDomain);
4265                         if(strpos($replyTo, $filterDomain) !== false) {
4266                                 $GLOBALS['log']->debug('Autoreply cancelled - [reply to] address domain matches filter domain.');
4267                                 return false;
4268                         } elseif(strpos($from, $filterDomain) !== false) {
4269                                 $GLOBALS['log']->debug('Autoreply cancelled - [from] address domain matches filter domain.');
4270                                 return false;
4271                         } else {
4272                                 return true; // no match
4273                         }
4274                 }
4275         }
4276
4277         /**
4278          * returns true if subject is NOT "out of the office" type
4279          *
4280          * @param string subject Subject line of email in question
4281          * @return bool returns false if OOTO found
4282          */
4283         function checkOutOfOffice($subject) {
4284                 $ooto = array("Out of the Office", "Out of Office");
4285
4286                 foreach($ooto as $str) {
4287                         if(preg_replace('/'.$str.'/i', $subject)) {
4288                                 $GLOBALS['log']->debug('Autoreply cancelled - found "Out of Office" type of subject.');
4289                                 return false;
4290                         }
4291                 }
4292                 return true; // no matches to ooto strings
4293         }
4294
4295
4296         /**
4297          * sets a timestamp for an autoreply to a single email addy
4298          *
4299          * @param string addr Address of auto-replied target
4300          */
4301         function setAutoreplyStatus($addr) {
4302                 $this->db->query(       'INSERT INTO inbound_email_autoreply (id, deleted, date_entered, date_modified, autoreplied_to, ie_id) VALUES (
4303                                                         \''.create_guid().'\',
4304                                                         0,
4305                                                         \''.gmdate('Y-m-d H:i:s', strtotime('now')).'\',
4306                                                         \''.gmdate('Y-m-d H:i:s', strtotime('now')).'\',
4307                                                         \''.$addr.'\',
4308                                     \''.$this->id.'\') ', true);
4309         }
4310
4311
4312         /**
4313          * returns true if recipient has NOT received 10 auto-replies in 24 hours
4314          *
4315          * @param string from target address for auto-reply
4316          * @return bool true if target is valid/under limit
4317          */
4318         function getAutoreplyStatus($from) {
4319                 global $sugar_config;
4320
4321                 $q_clean = 'UPDATE inbound_email_autoreply SET deleted = 1 WHERE date_entered < \''.gmdate($GLOBALS['timedate']->get_db_date_time_format(), strtotime('now -24 hours')).'\'';
4322                 $r_clean = $this->db->query($q_clean, true);
4323
4324                 $q = 'SELECT count(*) AS c FROM inbound_email_autoreply WHERE deleted = 0 AND autoreplied_to = \''.$from.'\' AND ie_id = \''.$this->id.'\'';
4325                 $r = $this->db->query($q, true);
4326                 $a = $this->db->fetchByAssoc($r);
4327
4328                 $email_num_autoreplies_24_hours = $this->get_stored_options('email_num_autoreplies_24_hours');
4329                 $maxReplies = (isset($email_num_autoreplies_24_hours)) ? $email_num_autoreplies_24_hours : $this->maxEmailNumAutoreplies24Hours;
4330
4331                 if($a['c'] >= $maxReplies) {
4332                         $GLOBALS['log']->debug('Autoreply cancelled - more than ' . $maxReplies . ' replies sent in 24 hours.');
4333                         return false;
4334                 } else {
4335                         return true;
4336                 }
4337         }
4338
4339         /**
4340          * returns exactly 1 id match. if more than one, than returns false
4341          * @param       $emailName              the subject of the email to match
4342          * @param       $tableName              the table of the matching bean type
4343          */
4344         function getSingularRelatedId($emailName, $tableName) {
4345                 $repStrings = array('RE:','Re:','re:');
4346                 $preppedName = str_replace($repStrings,'',trim($emailName));
4347
4348                 //TODO add team security to this query
4349                 $q = 'SELECT count(id) AS c FROM '.$tableName.' WHERE deleted = 0 AND name LIKE \'%'.$preppedName.'%\'';
4350                 $r = $this->db->query($q, true);
4351                 $a = $this->db->fetchByAssoc($r);
4352
4353                 if($a['c'] == 0) {
4354                         $q = 'SELECT id FROM '.$tableName.' WHERE deleted = 0 AND name LIKE \'%'.$preppedName.'%\'';
4355                         $r = $this->db->query($q, true);
4356                         $a = $this->db->fetchByAssoc($r);
4357                         return $a['id'];
4358                 } else {
4359                         return false;
4360                 }
4361         }
4362
4363         /**
4364          * saves InboundEmail parse macros to config.php
4365          * @param string type Bean to link
4366          * @param string macro The new macro
4367          */
4368         function saveInboundEmailSystemSettings($type, $macro) {
4369                 global $sugar_config;
4370
4371                 // inbound_email_case_subject_macro
4372                 $var = "inbound_email_".strtolower($type)."_subject_macro";
4373                 $sugar_config[$var] = $macro;
4374
4375                 ksort($sugar_config);
4376
4377                 $sugar_config_string = "<?php\n" .
4378                         '// created: ' . date('Y-m-d H:i:s') . "\n" .
4379                         '$sugar_config = ' .
4380                         var_export($sugar_config, true) .
4381                         ";\n?>\n";
4382
4383                 write_array_to_file("sugar_config", $sugar_config, "config.php");
4384         }
4385
4386         /**
4387          * returns the HTML for InboundEmail system settings
4388          * @return string HTML
4389          */
4390         function getSystemSettingsForm() {
4391                 global $sugar_config;
4392                 global $mod_strings;
4393                 global $app_strings;
4394                 global $app_list_strings;
4395
4396                 ////    Case Macro
4397                 if(!class_exists('aCase')) {
4398
4399                 }
4400                 $c = new aCase();
4401
4402                 $macro = $c->getEmailSubjectMacro();
4403
4404                 $ret =<<<eoq
4405                         <form action="index.php" method="post" name="Macro" id="form">
4406                                                 <input type="hidden" name="module" value="InboundEmail">
4407                                                 <input type="hidden" name="action" value="ListView">
4408                                                 <input type="hidden" name="save" value="true">
4409
4410                         <table width="100%" cellpadding="0" cellspacing="0" border="0">
4411                                 <tr>
4412                                         <td>
4413                                                 <input  title="{$app_strings['LBL_SAVE_BUTTON_TITLE']}"
4414                                                                 accessKey="{$app_strings['LBL_SAVE_BUTTON_KEY']}"
4415                                                                 class="button"
4416                                                                 onclick="this.form.return_module.value='InboundEmail'; this.form.return_action.value='ListView';"
4417                                                                 type="submit" name="Edit" value="  {$app_strings['LBL_SAVE_BUTTON_LABEL']}  ">
4418                                         </td>
4419                                 </tr>
4420                         </table>
4421
4422                         <table width="100%" border="0" cellspacing="0" cellpadding="0" class="detail view">
4423                                 <tr>
4424                                         <td valign="top" width='10%' NOWRAP scope="row">
4425                                                 <slot>
4426                                                         <b>{$mod_strings['LBL_CASE_MACRO']}:</b>
4427                                                 </slot>
4428                                         </td>
4429                                         <td valign="top" width='20%'>
4430                                                 <slot>
4431                                                         <input name="inbound_email_case_macro" type="text" value="{$macro}">
4432                                                 </slot>
4433                                         </td>
4434                                         <td valign="top" width='70%'>
4435                                                 <slot>
4436                                                         {$mod_strings['LBL_CASE_MACRO_DESC']}
4437                                                         <br />
4438                                                         <i>{$mod_strings['LBL_CASE_MACRO_DESC2']}</i>
4439                                                 </slot>
4440                                         </td>
4441                                 </tr>
4442                         </table>
4443                         </form>
4444 eoq;
4445                 return $ret;
4446         }
4447
4448         /**
4449          * for mailboxes of type "Support" parse for '[CASE:%1]'
4450          * @param       $emailName              the subject line of the email
4451          * @param       $aCase                  a Case object
4452          */
4453         function getCaseIdFromCaseNumber($emailName, $aCase) {
4454                 //$emailSubjectMacro
4455                 $exMacro = explode('%1', $aCase->getEmailSubjectMacro());
4456                 $open = $exMacro[0];
4457                 $close = $exMacro[1];
4458
4459                 if($sub = stristr($emailName, $open)) { // eliminate everything up to the beginning of the macro and return the rest
4460                         // $sub is [CASE:XX] xxxxxxxxxxxxxxxxxxxxxx
4461                         $sub2 = str_replace($open, '', $sub);
4462                         // $sub2 is XX] xxxxxxxxxxxxxx
4463                         $sub3 = substr($sub2, 0, strpos($sub2, $close));
4464
4465                         $r = $this->db->query("SELECT id FROM cases WHERE case_number = '{$sub3}'", true);
4466                         $a = $this->db->fetchByAssoc($r);
4467                         if(!empty($a['id'])) {
4468                                 return $a['id'];
4469                         } else {
4470                                 return false;
4471                         }
4472                 } else {
4473                         return false;
4474                 }
4475         }
4476
4477         function get_stored_options($option_name,$default_value=null,$stored_options=null) {
4478                 if (empty($stored_options)) {
4479                         $stored_options=$this->stored_options;
4480                 }
4481                 if(!empty($stored_options)) {
4482                         $storedOptions = unserialize(base64_decode($stored_options));
4483                         if (isset($storedOptions[$option_name])) {
4484                                 $default_value=$storedOptions[$option_name];
4485                         }
4486                 }
4487                 return $default_value;
4488         }
4489
4490
4491         /**
4492          * This function returns a contact or user ID if a matching email is found
4493          * @param       $email          the email address to match
4494          * @param       $table          which table to query
4495          */
4496         function getRelatedId($email, $module) {
4497                 $email = trim(strtoupper($email));
4498                 if(strpos($email, ',') !== false) {
4499                         $emailsArray = explode(',', $email);
4500                         $emailAddressString = "";
4501                         foreach($emailsArray as $emailAddress) {
4502                                 if (!empty($emailAddressString)) {
4503                                         $emailAddressString .= ",";
4504                                 }
4505                                 $emailAddressString .=  "'" . $emailAddress. "'";
4506                         } // foreach
4507                         $email = $emailAddressString;
4508                 } else {
4509                         $email = "'" . $email . "'";
4510                 } // else
4511                 $module = ucfirst($module);
4512
4513                 $q = "SELECT bean_id FROM email_addr_bean_rel eabr
4514                                 JOIN email_addresses ea ON (eabr.email_address_id = ea.id)
4515                                 WHERE bean_module = '{$module}' AND ea.email_address_caps in ( {$email} ) AND eabr.deleted=0";
4516
4517                 $r = $this->db->query($q, true);
4518
4519                 $retArr = array();
4520                 while($a = $this->db->fetchByAssoc($r)) {
4521                         $retArr[] = $a['bean_id'];
4522                 }
4523                 if(count($retArr) > 0) {
4524                         return $retArr;
4525                 } else {
4526                         return false;
4527                 }
4528         }
4529
4530         /**
4531          * finds emails tagged "//UNSEEN" on mailserver and "SINCE: [date]" if that
4532          * option is set
4533          *
4534          * @return array Array of messageNumbers (mail server's internal keys)
4535          */
4536         function getNewMessageIds() {
4537                 $storedOptions = unserialize(base64_decode($this->stored_options));
4538
4539                 //TODO figure out if the since date is UDT
4540                 if($storedOptions['only_since']) {// POP3 does not support Unseen flags
4541                         if(!isset($storedOptions['only_since_last']) && !empty($storedOptions['only_since_last'])) {
4542                                 $q = 'SELECT last_run FROM schedulers WHERE job = \'function::pollMonitoredInboxes\'';
4543                                 $r = $this->db->query($q, true);
4544                                 $a = $this->db->fetchByAssoc($r);
4545
4546                                 $date = date('r', strtotime($a['last_run']));
4547                         } else {
4548                                 $date = $storedOptions['only_since_last'];
4549                         }
4550                         $ret = imap_search($this->conn, 'SINCE "'.$date.'" UNDELETED UNSEEN');
4551                         $check = imap_check($this->conn);
4552                         $storedOptions['only_since_last'] = $check->Date;
4553                         $this->stored_options = base64_encode(serialize($storedOptions));
4554                         $this->save();
4555                 } else {
4556                         $ret = imap_search($this->conn, 'UNDELETED UNSEEN');
4557                 }
4558
4559                 $GLOBALS['log']->debug('-----> getNewMessageIds() got '.count($ret).' new Messages');
4560                 return $ret;
4561         }
4562
4563         /**
4564          * Constructs the resource connection string that IMAP needs
4565          * @param string $service Service string, will generate if not passed
4566          * @return string
4567          */
4568         function getConnectString($service='', $mbox='', $includeMbox=true) {
4569                 $service = empty($service) ? $this->getServiceString() : $service;
4570                 $mbox = empty($mbox) ? $this->mailbox : $mbox;
4571
4572                 $connectString = '{'.$this->server_url.':'.$this->port.'/service='.$this->protocol.$service.'}';
4573                 $connectString .= ($includeMbox) ? $mbox : "";
4574
4575                 return $connectString;
4576         }
4577
4578         function disconnectMailserver() {
4579                 if(is_resource($this->conn)) {
4580                         imap_close($this->conn);
4581                 }
4582         }
4583
4584         /**
4585          * Connects to mailserver.  If an existing IMAP resource is available, it
4586          * will attempt to reuse the connection, updating the mailbox path.
4587          *
4588          * @param bool test Flag to test connection
4589          * @param bool force Force reconnect
4590          * @return string "true" on success, "false" or $errorMessage on failure
4591          */
4592         function connectMailserver($test=false, $force=false) {
4593                 global $mod_strings;
4594                 if(!function_exists("imap_open")) {
4595                         $GLOBALS['log']->debug('------------------------- IMAP libraries NOT available!!!! die()ing thread.----');
4596                         return $mod_strings['LBL_WARN_NO_IMAP'];
4597                 }
4598
4599                 imap_errors(); // clearing error stack
4600                 error_reporting(0); // turn off notices from IMAP
4601
4602                 // tls::ca::ssl::protocol::novalidate-cert::notls
4603                 $useSsl = ($_REQUEST['ssl'] == 'true') ? true : false;
4604                 if($test) {
4605                         imap_timeout(1, 15); // 60 secs is the default
4606                         imap_timeout(2, 15);
4607                         imap_timeout(3, 15);
4608
4609                         $opts = $this->findOptimumSettings($useSsl);
4610                         if(isset($opts['good']) && empty($opts['good'])) {
4611                                 return array_pop($opts['err']);
4612                         } else {
4613                                 $service = $opts['service'];
4614                                 $service = str_replace('foo','', $service); // foo there to support no-item explodes
4615                         }
4616                 } else {
4617                         $service = $this->getServiceString();
4618                 }
4619
4620                 $connectString = $this->getConnectString($service, $this->mailbox);
4621
4622                 /*
4623                  * Try to recycle the current connection to reduce response times
4624                  */
4625                 if(is_resource($this->conn)) {
4626                         if($force) {
4627                                 // force disconnect
4628                                 imap_close($this->conn);
4629                         }
4630
4631                         if(imap_ping($this->conn)) {
4632                                 // we have a live connection
4633                                 imap_reopen($this->conn, $connectString, CL_EXPUNGE);
4634                         }
4635                 }
4636
4637                 // final test
4638                 if(!is_resource($this->conn) && !$test) {
4639                         $this->conn = imap_open($connectString, $this->email_user, $this->email_password, CL_EXPUNGE);
4640                 }
4641
4642                 if($test) {
4643                         if ($opts == false && !is_resource($this->conn)) {
4644                                 $this->conn = imap_open($connectString, $this->email_user, $this->email_password, CL_EXPUNGE);
4645                         }
4646                         $errors = '';
4647                         $alerts = '';
4648                         $successful = false;
4649                         if(($errors = imap_last_error()) || ($alerts = imap_alerts())) {
4650                                 if($errors == 'Mailbox is empty') { // false positive
4651                                         $successful = true;
4652                                 } else {
4653                                         $msg .= $errors;
4654                                         $msg .= '<p>'.$alerts.'<p>';
4655                                         $msg .= '<p>'.$mod_strings['ERR_TEST_MAILBOX'];
4656                                 }
4657                         } else {
4658                                 $successful = true;
4659                         }
4660
4661                         if($successful) {
4662                                 if($this->protocol == 'imap') {
4663                                         $msg .= $mod_strings['LBL_TEST_SUCCESSFUL'];
4664                                         /*
4665                                         $testConnectString = '{'.$this->server_url.':'.$this->port.'/service='.$this->protocol.$service.'}';
4666                                         if (!is_resource($this->conn)) {
4667                                                 $this->conn = imap_open($connectString, $this->email_user, $this->email_password, CL_EXPUNGE);
4668                                         }
4669                                         $list = imap_getmailboxes($this->conn, $testConnectString, "*");
4670                                         if(isset($_REQUEST['personal']) && $_REQUEST['personal'] == 'true') {
4671                                                 $msg .= $mod_strings['LBL_TEST_SUCCESSFUL'];
4672                                         } elseif (is_array($list)) {
4673                                                 sort($list);
4674                                                 _ppd($boxes);
4675
4676                                                 $msg .= '<b>'.$mod_strings['LBL_FOUND_MAILBOXES'].'</b><p>';
4677                                                 foreach ($list as $key => $val) {
4678                                                         $mb = imap_utf7_decode(str_replace($testConnectString,'',$val->name));
4679                                                         $msg .= '<a onClick=\'setMailbox(\"'.$mb.'\"); window.close();\'>';
4680                                                         $msg .= $mb;
4681                                                         $msg .= '</a><br>';
4682                                                 }
4683                                         } else {
4684                                                 $msg .= $errors;
4685                                                 $msg .= '<p>'.$mod_strings['ERR_MAILBOX_FAIL'].imap_last_error().'</p>';
4686                                                 $msg .= '<p>'.$mod_strings['ERR_TEST_MAILBOX'].'</p>';
4687                                         }
4688                                         */
4689                                 } else {
4690                                         $msg .= $mod_strings['LBL_POP3_SUCCESS'];
4691                                 }
4692                         }
4693
4694                         imap_errors(); // collapse error stack
4695                         imap_close($this->conn);
4696                         return $msg;
4697                 } elseif(!is_resource($this->conn)) {
4698                         return "false";
4699                 } else {
4700                         return "true";
4701                 }
4702         }
4703
4704
4705
4706         function checkImap() {
4707                 global $mod_strings;
4708
4709                 if(!function_exists('imap_open')) {
4710                         echo '
4711                         <table cellpadding="0" cellspacing="0" width="100%" border="0" class="list view">
4712                                 <tr height="20">
4713                                         <td scope="col" width="25%"  colspan="2"><slot>
4714                                                 '.$mod_strings['LBL_WARN_IMAP_TITLE'].'
4715                                         </slot></td>
4716                                 </tr>
4717                                 <tr>
4718                                         <td scope="row" valign=TOP bgcolor="#fdfdfd" width="20%"><slot>
4719                                                 '.$mod_strings['LBL_WARN_IMAP'].'
4720                                         <td scope="row" valign=TOP class="oddListRowS1" bgcolor="#fdfdfd" width="80%"><slot>
4721                                                 <span class=error>'.$mod_strings['LBL_WARN_NO_IMAP'].'</span>
4722                                         </slot></td>
4723                                 </tr>
4724                         </table>
4725                         <br>';
4726                 }
4727         }
4728
4729         /**
4730          * retrieves an array of I-E beans based on the group_id
4731          * @param       string  $groupId        GUID of the group user or Individual
4732          * @return      array   $beans          array of beans
4733          * @return      boolean false if none returned
4734          */
4735         function retrieveByGroupId($groupId) {
4736                 $q = 'SELECT id FROM inbound_email WHERE group_id = \''.$groupId.'\' AND deleted = 0 AND status = \'Active\'';
4737                 $r = $this->db->query($q, true);
4738
4739                 $beans = array();
4740                 while($a = $this->db->fetchByAssoc($r)) {
4741                         $ie = new InboundEmail();
4742                         $ie->retrieve($a['id']);
4743                         $beans[$a['id']] = $ie;
4744                 }
4745                 return $beans;
4746         }
4747
4748         /**
4749          * Retrieves the current count of personal accounts for the user specified.
4750          *
4751          * @param unknown_type $user
4752          */
4753         function getUserPersonalAccountCount($user = null)
4754         {
4755             if($user == null)
4756                $user = $GLOBALS['current_user'];
4757
4758             $query = "SELECT count(*) as c FROM inbound_email WHERE deleted=0 AND is_personal='1' AND group_id='{$user->id}' AND status='Active'";
4759
4760             $rs = $this->db->query($query);
4761                 $row = $this->db->fetchByAssoc($rs);
4762         return $row['c'];
4763         }
4764
4765         /**
4766          * retrieves an array of I-E beans based on the group folder id
4767          * @param       string  $groupFolderId  GUID of the group folder
4768          * @return      array   $beans          array of beans
4769          * @return      boolean false if none returned
4770          */
4771         function retrieveByGroupFolderId($groupFolderId) {
4772                 $q = 'SELECT id FROM inbound_email WHERE groupfolder_id = \''.$groupFolderId.'\' AND deleted = 0 ';
4773                 $r = $this->db->query($q, true);
4774
4775                 $beans = array();
4776                 while($a = $this->db->fetchByAssoc($r)) {
4777                         $ie = new InboundEmail();
4778                         $ie->retrieve($a['id']);
4779                         $beans[] = $ie;
4780                 }
4781                 return $beans;
4782         }
4783
4784         /**
4785          * Retrieves an array of I-E beans that the user has team access to
4786          */
4787         function retrieveAllByGroupId($id, $includePersonal=true) {
4788                 global $current_user;
4789
4790                 $beans = ($includePersonal) ? $this->retrieveByGroupId($id) : array();
4791
4792                 $teamJoin = '';
4793
4794
4795
4796                 $q = "SELECT inbound_email.id FROM inbound_email {$teamJoin} WHERE is_personal = 0 AND groupfolder_id is null AND mailbox_type not like 'bounce' AND inbound_email.deleted = 0 AND status = 'Active' ";
4797
4798
4799
4800                 $r = $this->db->query($q, true);
4801
4802                 while($a = $this->db->fetchByAssoc($r)) {
4803                         $found = false;
4804                         foreach($beans as $bean) {
4805                                 if($bean->id == $a['id']) {
4806                                         $found = true;
4807                                 }
4808                         }
4809
4810                         if(!$found) {
4811                                 $ie = new InboundEmail();
4812                                 $ie->retrieve($a['id']);
4813                                 $beans[$a['id']] = $ie;
4814                         }
4815                 }
4816
4817                 return $beans;
4818         }
4819
4820         /**
4821          * Retrieves an array of I-E beans that the user has team access to including group
4822          */
4823         function retrieveAllByGroupIdWithGroupAccounts($id, $includePersonal=true) {
4824                 global $current_user;
4825
4826                 $beans = ($includePersonal) ? $this->retrieveByGroupId($id) : array();
4827
4828                 $teamJoin = '';
4829
4830
4831
4832
4833
4834
4835                 $q = "SELECT DISTINCT inbound_email.id FROM inbound_email {$teamJoin} WHERE is_personal = 0 AND mailbox_type not like 'bounce' AND status = 'Active' AND inbound_email.deleted = 0 ";
4836
4837                 $r = $this->db->query($q, true);
4838
4839                 while($a = $this->db->fetchByAssoc($r)) {
4840                         $found = false;
4841                         foreach($beans as $bean) {
4842                                 if($bean->id == $a['id']) {
4843                                         $found = true;
4844                                 }
4845                         }
4846
4847                         if(!$found) {
4848                                 $ie = new InboundEmail();
4849                                 $ie->retrieve($a['id']);
4850                                 $beans[$a['id']] = $ie;
4851                         }
4852                 }
4853
4854                 return $beans;
4855         }
4856
4857
4858         /**
4859          * returns the bean name - overrides SugarBean's
4860          */
4861         function get_summary_text() {
4862                 return $this->name;
4863         }
4864
4865         /**
4866          * Override's SugarBean's
4867          */
4868         function create_export_query($order_by, $where, $show_deleted = 0) {
4869                 return $this->create_new_list_query($order_by, $where, $show_deleted = 0);
4870         }
4871
4872         /**
4873          * Override's SugarBean's
4874          */
4875
4876         /**
4877          * Override's SugarBean's
4878          */
4879         function get_list_view_data(){
4880                 global $mod_strings;
4881                 global $app_list_strings;
4882                 $temp_array = $this->get_list_view_array();
4883                 $temp_array['MAILBOX_TYPE_NAME']= $app_list_strings['dom_mailbox_type'][$this->mailbox_type];
4884                 //cma, fix bug 21670.
4885         $temp_array['GLOBAL_PERSONAL_STRING']= ($this->is_personal ? $mod_strings['LBL_IS_PERSONAL'] : $mod_strings['LBL_IS_GROUP']);
4886         $temp_array['STATUS'] = ($this->status == 'Active') ? $mod_strings['LBL_STATUS_ACTIVE'] : $mod_strings['LBL_STATUS_INACTIVE'];
4887                 return $temp_array;
4888         }
4889
4890         /**
4891          * Override's SugarBean's
4892          */
4893         function fill_in_additional_list_fields() {
4894                 $this->fill_in_additional_detail_fields();
4895         }
4896
4897         /**
4898          * Override's SugarBean's
4899          */
4900         function fill_in_additional_detail_fields() {
4901                 if(!empty($this->service)) {
4902                         $exServ = explode('::', $this->service);
4903                         $this->tls              = $exServ[0];
4904                         if ( isset($exServ[1]) )
4905                             $this->ca           = $exServ[1];
4906                         if ( isset($exServ[2]) )
4907                             $this->ssl          = $exServ[2];
4908                         if ( isset($exServ[3]) )
4909                             $this->protocol     = $exServ[3];
4910                 }
4911         }
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926         ///////////////////////////////////////////////////////////////////////////
4927         ////    IN SUPPORT OF EMAIL 2.0
4928         /**
4929          * Checks for $user's autoImport setting and returns the current value
4930          * @param object $user User in focus, defaults to $current_user
4931          * @return bool
4932          */
4933         function isAutoImport($user=null) {
4934                 if(!empty($this->autoImport)) {
4935                         return $this->autoImport;
4936                 }
4937
4938                 global $current_user;
4939                 if(empty($user)) $user = $current_user;
4940
4941                 $emailSettings = $current_user->getPreference('emailSettings', 'Emails');
4942                 $emailSettings = is_string($emailSettings) ? unserialize($emailSettings) : $emailSettings;
4943
4944                 $this->autoImport = (isset($emailSettings['autoImport']) && !empty($emailSettings['autoImport'])) ? true : false;
4945                 return $this->autoImport;
4946         }
4947
4948         /**
4949          * Clears out cache files for a user
4950          */
4951         function cleanOutCache() {
4952                 $GLOBALS['log']->debug("INBOUNDEMAIL: at cleanOutCache()");
4953                 //global $current_user;
4954                 //global $sugar_config;
4955
4956                 //$showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
4957                 //$personals = $this->retrieveAllByGroupId($current_user->id, true);
4958
4959                 //foreach($personals as $k => $personalAccount) {
4960                 //      if(in_array($personalAccount->id, $showFolders)) {
4961 //                              // check for cache value
4962 //                              $cacheRoot = getcwd()."/{$sugar_config['cache_dir']}modules/Emails/{$personalAccount->id}";
4963 //
4964 //                              // on new account creation, this is not created yet
4965 //                              if(!file_exists($cacheRoot)) {
4966 //                                      require_once("modules/Emails/EmailUI.php");
4967 //                                      $et = new EmailUI();
4968 //                                      $et->preflightEmailCache($cacheRoot);
4969 //                                      $et->preflightUserCache();
4970 //                                      continue; // no need to find files, there are none.
4971 //                              }
4972 //
4973 //                              // destroy overviews, keep messages
4974 //                              $cacheFiles = findAllFiles($cacheRoot."/folders/", array());
4975 //
4976 //                              foreach($cacheFiles as $cFile) {
4977 //                                      if(preg_match("/imapFetchOverview/", $cFile)) {
4978 //                                              _ppl("***InboundEmail deleting cache file [ {$cFile} ]");
4979 //                                              $GLOBALS['log']->debug("***InboundEmail deleting cache file [ {$cFile} ]");
4980 //                                              if(!unlink($cFile)) {
4981 //                                                      $GLOBALS['log']->error("*** ERROR: InboundEmail could not delete cache file [ {$cFile} ]");
4982 //                                              }
4983 //                                      }
4984 //                              }
4985
4986                                 // delete the tables
4987                                 $this->deleteCache();
4988                         //}
4989                 //}
4990         }
4991
4992         /**
4993          * moves emails from folder to folder
4994          * @param string $fromIe I-E id
4995          * @param string $fromFolder IMAP path to folder in which the email lives
4996          * @param string $toIe I-E id
4997          * @param string $toFolder
4998          * @param string $uids UIDs of emails to move, either Sugar GUIDS or IMAP
4999          * UIDs
5000          */
5001         function copyEmails($fromIe, $fromFolder, $toIe, $toFolder, $uids) {
5002                 $this->moveEmails($fromIe, $fromFolder, $toIe, $toFolder, $uids, true);
5003         }
5004
5005         /**
5006          * moves emails from folder to folder
5007          * @param string $fromIe I-E id
5008          * @param string $fromFolder IMAP path to folder in which the email lives
5009          * @param string $toIe I-E id
5010          * @param string $toFolder
5011          * @param string $uids UIDs of emails to move, either Sugar GUIDS or IMAP
5012          * UIDs
5013          * @param bool $copy Default false
5014          * @return bool True on successful execution
5015          */
5016         function moveEmails($fromIe, $fromFolder, $toIe, $toFolder, $uids, $copy=false) {
5017                 global $app_strings;
5018                 global $current_user;
5019
5020
5021                 // same I-E server
5022                 if($fromIe == $toIe) {
5023                         $GLOBALS['log']->debug("********* SUGARFOLDER - moveEmails() moving email from I-E to I-E");
5024                         //$exDestFolder = explode("::", $toFolder);
5025                         //preserve $this->mailbox
5026                 if (isset($this->mailbox)) {
5027                     $oldMailbox = $this->mailbox;
5028                 }
5029
5030
5031                         $this->retrieve($fromIe);
5032                     $this->mailbox = $fromFolder;
5033                         $this->connectMailserver();
5034                         $exUids = explode('::;::', $uids);
5035                         $uids = implode(",", $exUids);
5036                         // imap_mail_move accepts comma-delimited lists of UIDs
5037                         if($copy) {
5038                                 if(imap_mail_copy($this->conn, $uids, $toFolder, CP_UID)) {
5039                                         $this->mailbox = $toFolder;
5040                                         $this->connectMailserver();
5041                                         $newOverviews = imap_fetch_overview($this->conn, $uids, FT_UID);
5042                                         $this->updateOverviewCacheFile($newOverviews, 'append');
5043                                     if (isset($oldMailbox)) {
5044                         $this->mailbox = $oldMailbox;
5045                     }
5046                                         return true;
5047                                 } else {
5048                                         $GLOBALS['log']->debug("INBOUNDEMAIL: could not imap_mail_copy() [ {$uids} ] to folder [ {$toFolder} ] from folder [ {$fromFolder} ]");
5049                                 }
5050                         } else {
5051                                 if(imap_mail_move($this->conn, $uids, $toFolder, CP_UID)) {
5052                                         $GLOBALS['log']->info("INBOUNDEMAIL: imap_mail_move() [ {$uids} ] to folder [ {$toFolder} ] from folder [ {$fromFolder} ]");
5053                                         imap_expunge($this->conn); // hard deletes moved messages
5054
5055                                         // update cache on fromFolder
5056                                         $newOverviews = $this->getOverviewsFromCacheFile($uids, $fromFolder, true);
5057                                         $this->deleteCachedMessages($uids, $fromFolder);
5058
5059                                         // update cache on toFolder
5060                                         $this->checkEmailOneMailbox($toFolder, true, true);
5061                                     if (isset($oldMailbox)) {
5062                         $this->mailbox = $oldMailbox;
5063                     }
5064
5065                                         return true;
5066                                 } else {
5067                                         $GLOBALS['log']->debug("INBOUNDEMAIL: could not imap_mail_move() [ {$uids} ] to folder [ {$toFolder} ] from folder [ {$fromFolder} ]");
5068                                 }
5069                         }
5070                 } elseif($toIe == 'folder' && $fromFolder == 'sugar::Emails') {
5071                         $GLOBALS['log']->debug("********* SUGARFOLDER - moveEmails() moving email from SugarFolder to SugarFolder");
5072                         // move from sugar folder to sugar folder
5073                         require_once("include/SugarFolders/SugarFolders.php");
5074                         $sugarFolder = new SugarFolder();
5075                         $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
5076                         foreach($exUids as $id) {
5077                                 if($copy) {
5078                                         $sugarFolder->copyBean($fromIe, $toFolder, $id, "Emails");
5079                                 } else {
5080                                         $fromSugarFolder = new SugarFolder();
5081                                         $fromSugarFolder->retrieve($fromIe);
5082                                         $toSugarFolder = new SugarFolder();
5083                                         $toSugarFolder->retrieve($toFolder);
5084
5085                                         $email = new Email();
5086                                         $email->retrieve($id);
5087                                         $email->status = 'unread';
5088
5089                                         // when you move from My Emails to Group Folder, Assign To field for the Email should become null
5090                                         if ($fromSugarFolder->is_dynamic && $toSugarFolder->is_group) {
5091                                                 $email->assigned_user_id = "";
5092                                                 $email->save();
5093                                                 if (!$toSugarFolder->checkEmailExistForFolder($id)) {
5094                                                         $fromSugarFolder->deleteEmailFromAllFolder($id);
5095                                                         $toSugarFolder->addBean($email);
5096                                                 }
5097                                         } elseif ($fromSugarFolder->is_group && $toSugarFolder->is_dynamic) {
5098                                                 $fromSugarFolder->deleteEmailFromAllFolder($id);
5099                                                 $email->assigned_user_id = $current_user->id;
5100                                                 $email->save();
5101                                         } else {
5102                                                 // If you are moving something from personal folder then delete an entry from all folder
5103                                                 if (!$fromSugarFolder->is_dynamic && !$fromSugarFolder->is_group) {
5104                                                         $fromSugarFolder->deleteEmailFromAllFolder($id);
5105                                                 } // if
5106
5107                                                 if ($fromSugarFolder->is_dynamic && !$toSugarFolder->is_dynamic && !$toSugarFolder->is_group) {
5108                                                         $email->assigned_user_id = "";
5109                                                         $toSugarFolder->addBean($email);
5110                                                 } // if
5111                                                 if (!$toSugarFolder->checkEmailExistForFolder($id)) {
5112                                                         if (!$toSugarFolder->is_dynamic) {
5113                                                                 $fromSugarFolder->deleteEmailFromAllFolder($id);
5114                                                                 $toSugarFolder->addBean($email);
5115                                                         } else {
5116                                                                 $fromSugarFolder->deleteEmailFromAllFolder($id);
5117                                                                 $email->assigned_user_id = $current_user->id;
5118                                                         }
5119                                                 } else {
5120                                                         $sugarFolder->move($fromIe, $toFolder, $id);
5121                                                 } // else
5122                                                 $email->save();
5123                                         } // else
5124                                 }
5125                         }
5126
5127                         return true;
5128                 } elseif($toIe == 'folder') {
5129                         $GLOBALS['log']->debug("********* SUGARFOLDER - moveEmails() moving email from I-E to SugarFolder");
5130                         // move to Sugar folder
5131                         require_once("include/SugarFolders/SugarFolders.php");
5132                         $sugarFolder = new SugarFolder();
5133                         $sugarFolder->retrieve($toFolder);
5134                         //Show the import form if we don't have the required info
5135                         if (!isset($_REQUEST['delete'])) {
5136                                 $json = getJSONobj();
5137                                 if ($sugarFolder->is_group) {
5138                                         $_REQUEST['showTeam'] = false;
5139                                         $_REQUEST['showAssignTo'] = false;
5140                                 }
5141                     $ret = $this->email->et->getImportForm($_REQUEST, $this->email);
5142                     $ret['move'] = true;
5143                     $ret['srcFolder'] = $fromFolder;
5144                     $ret['srcIeId']   = $fromIe;
5145                     $ret['dstFolder'] = $toFolder;
5146                     $ret['dstIeId']   = $toIe;
5147                     $out = trim($json->encode($ret, false));
5148                     echo  $out;
5149                     return true;
5150                         }
5151
5152
5153                         // import to Sugar
5154                         $this->retrieve($fromIe);
5155                         $this->mailbox = $fromFolder;
5156                         $this->connectMailserver();
5157                         // If its a group folder the team should be of the folder team
5158                         if ($sugarFolder->is_group) {
5159                                 $_REQUEST['team_id'] = $sugarFolder->team_id;
5160                                 $_REQUEST['team_set_id'] = $sugarFolder->team_set_id;
5161                         } else {
5162                                 // TODO - set team_id, team_set for new UI
5163                         } // else
5164
5165                         $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
5166
5167                         if(!empty($sugarFolder->id)) {
5168                                 $count = 1;
5169                                 $return = array();
5170                                 $json = getJSONobj();
5171                                 foreach($exUids as $k => $uid) {
5172                                         $msgNo = $uid;
5173                                         if ($this->isPop3Protocol()) {
5174                                                 $msgNo = $this->getCorrectMessageNoForPop3($uid);
5175                                         } else {
5176                                                 $msgNo = imap_msgno($this->conn, $uid);
5177                                         }
5178
5179                                         if(!empty($msgNo)) {
5180                                                 $importStatus = $this->importOneEmail($msgNo, $uid);
5181                                                 // add to folder
5182                                                 if($importStatus) {
5183                                                         $sugarFolder->addBean($this->email);
5184                                                         if(!$copy && isset($_REQUEST['delete']) && ($_REQUEST['delete'] == "true") && $importStatus) {
5185                                                                 $GLOBALS['log']->error("********* delete from mailserver [ {explode(",", $uids)} ]");
5186                                                                 // delete from mailserver
5187                                                                 $this->deleteMessageOnMailServer($uid);
5188                                                                 $this->deleteMessageFromCache($uid);
5189                                                         } // if
5190                                                 }
5191                                                 $return[] = $app_strings['LBL_EMAIL_MESSAGE_NO'] . " " . $count . ", " . $app_strings['LBL_STATUS'] . " " . ($importStatus ? $app_strings['LBL_EMAIL_IMPORT_SUCCESS'] : $app_strings['LBL_EMAIL_IMPORT_FAIL']);
5192                                                 $count++;
5193                                         } // if
5194                                 } // foreach
5195                                 echo $json->encode($return);
5196                                 return true;
5197                         } else {
5198                                 $GLOBALS['log']->error("********* SUGARFOLDER - failed to retrieve folder ID [ {$toFolder} ]");
5199                         }
5200                 } else {
5201                         $GLOBALS['log']->debug("********* SUGARFOLDER - moveEmails() called with no passing criteria");
5202                 }
5203
5204                 return false;
5205         }
5206
5207
5208         /**
5209          * Hard deletes an I-E account
5210          * @param string id GUID
5211          */
5212         function hardDelete($id) {
5213                 $q = "DELETE FROM inbound_email WHERE id = '{$id}'";
5214                 $r = $this->db->query($q, true);
5215         }
5216
5217         /**
5218          * Generate a unique filename for attachments based on the message id.  There are no maximum
5219          * specifications for the length of the message id, the only requirement is that it be globally unique.
5220          *
5221          * @param bool $nameOnly Whether or not the attachment count should be appended to the filename.
5222          * @return string The temp file name
5223          */
5224         function getTempFilename($nameOnly=false) {
5225
5226         $str = md5($this->compoundMessageId);
5227
5228                 if(!$nameOnly) {
5229                         $str = $str.$this->attachmentCount;
5230                         $this->attachmentCount++;
5231                 }
5232
5233                 return $str;
5234         }
5235
5236         /**
5237          * deletes and expunges emails on server
5238          * @param string $uid UID(s), comma delimited, of email(s) on server
5239          * @return bool true on success
5240          */
5241         function deleteMessageOnMailServer($uid) {
5242                 global $app_strings;
5243                 $this->connectMailserver();
5244
5245                 if(strpos($uid, $app_strings['LBL_EMAIL_DELIMITER']) !== false) {
5246                         $uids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uid);
5247                 } else {
5248                         $uids[] = $uid;
5249                 }
5250
5251                 $return = true;
5252
5253                 if($this->protocol == 'imap') {
5254                         $trashFolder = $this->get_stored_options("trashFolder");
5255                         if (empty($trashFolder)) {
5256                                 $trashFolder = "INBOX.Trash";
5257                         }
5258                         foreach($uids as $uid) {
5259                         if($this->moveEmails($this->id, $this->mailbox, $this->id, $trashFolder, $uid))
5260                         $GLOBALS['log']->debug("INBOUNDEMAIL: MoveEmail to {$trashFolder} successful.");
5261                     else {
5262                         $GLOBALS['log']->debug("INBOUNDEMAIL: MoveEmail to {$trashFolder} FAILED - trying hard delete for message: $uid");
5263                         imap_delete($this->conn, $uid, FT_UID);
5264                                         $return = true;
5265                     }
5266                 }
5267                 }
5268         else {
5269             $msgnos = array();
5270                 foreach($uids as $uid) {
5271                 $msgnos[] = $this->getCorrectMessageNoForPop3($uid);
5272                         }
5273                         $msgnos = implode(',', $msgnos);
5274                         imap_delete($this->conn, $msgnos);
5275                         $return = true;
5276                 }
5277
5278                 if(!imap_expunge($this->conn)) {
5279             $GLOBALS['log']->debug("NOOP: could not expunge deleted email.");
5280             $return = false;
5281          }
5282          else
5283             $GLOBALS['log']->info("INBOUNDEMAIL: hard-deleted mail with MSgno's' [ {$msgnos} ]");
5284
5285                 return $return;
5286         }
5287
5288         /**
5289          * deletes and expunges emails on server
5290          * @param string $uid UID(s), comma delimited, of email(s) on server
5291          */
5292         function deleteMessageOnMailServerForPop3($uid) {
5293                 if(imap_delete($this->conn, $uid)) {
5294             if(!imap_expunge($this->conn)) {
5295                 $GLOBALS['log']->debug("NOOP: could not expunge deleted email.");
5296                 $return = false;
5297             } else {
5298                 $GLOBALS['log']->info("INBOUNDEMAIL: hard-deleted mail with MSgno's' [ {$uid} ]");
5299             }
5300                 }
5301         }
5302
5303         /**
5304          * Checks if this is a pop3 type of an account or not
5305          * @return boolean
5306          */
5307         function isPop3Protocol() {
5308                 return ($this->protocol == 'pop3');
5309         }
5310
5311         /**
5312          * Gets the UIDL from database for the corresponding msgno
5313          * @param int messageNo of a message
5314          * @return UIDL for the message
5315          */
5316         function getUIDLForMessage($msgNo) {
5317                 $query = "SELECT message_id FROM email_cache WHERE ie_id = '{$this->id}' AND msgno = '{$msgNo}'";
5318                 $r = $this->db->query($query);
5319                 $a = $this->db->fetchByAssoc($r);
5320                 return $a['message_id'];
5321         }
5322                 /**
5323          * Get the users default IE account id
5324          *
5325          * @param User $user
5326          * @return string
5327          */
5328         function getUsersDefaultOutboundServerId($user)
5329         {
5330                 $id =  $user->getPreference($this->keyForUsersDefaultIEAccount,'Emails',$user);
5331                 //If no preference has been set, grab the default system id.
5332                 if(empty($id))
5333                 {
5334                         $oe = new OutboundEmail();
5335                         $system = $oe->getSystemMailerSettings();
5336                         $id=empty($system->id) ? '' : $system->id;
5337                 }
5338
5339                 return $id;
5340         }
5341
5342         /**
5343          * Get the users default IE account id
5344          *
5345          * @param User $user
5346          */
5347         function setUsersDefaultOutboundServerId($user,$oe_id)
5348         {
5349                 $user->setPreference($this->keyForUsersDefaultIEAccount, $oe_id, '', 'Emails');
5350         }
5351         /**
5352          * Gets the UIDL from database for the corresponding msgno
5353          * @param int messageNo of a message
5354          * @return UIDL for the message
5355          */
5356         function getMsgnoForMessageID($messageid) {
5357                 $query = "SELECT msgno FROM email_cache WHERE ie_id = '{$this->id}' AND message_id = '{$messageid}'";
5358                 $r = $this->db->query($query);
5359                 $a = $this->db->fetchByAssoc($r);
5360                 return $a['message_id'];
5361         }
5362
5363         /**
5364          * fills InboundEmail->email with an email's details
5365          * @param int uid Unique ID of email
5366          * @param bool isMsgNo flag that passed ID is msgNo, default false
5367          * @param bool setRead Sets the 'seen' flag in cache
5368          * @param bool forceRefresh Skips cache file
5369          * @return string
5370          */
5371         function setEmailForDisplay($uid, $isMsgNo=false, $setRead=false, $forceRefresh=false) {
5372
5373                 if(empty($uid)) {
5374                         $GLOBALS['log']->debug("*** ERROR: INBOUNDEMAIL trying to setEmailForDisplay() with no UID");
5375                         return 'NOOP';
5376                 }
5377
5378                 global $sugar_config;
5379                 global $app_strings;
5380
5381                 // if its a pop3 then get the UIDL and see if this file name exist or not
5382                 if ($this->isPop3Protocol()) {
5383                         // get the UIDL from database;
5384                         $cachedUIDL = md5($uid);
5385                         $cache = "{$sugar_config['cache_dir']}modules/Emails/{$this->id}/messages/{$this->mailbox}{$cachedUIDL}.php";
5386                 } else {
5387                         $cache = "{$sugar_config['cache_dir']}modules/Emails/{$this->id}/messages/{$this->mailbox}{$uid}.php";
5388                 }
5389
5390                 if(file_exists($cache) && !$forceRefresh) {
5391                         $GLOBALS['log']->info("INBOUNDEMAIL: Using cache file for setEmailForDisplay()");
5392
5393                         include($cache); // profides $cacheFile
5394
5395
5396                         $metaOut = unserialize($cacheFile['out']);
5397                         $meta = $metaOut['meta']['email'];
5398                         $email = new Email();
5399
5400                         foreach($meta as $k => $v) {
5401                                 $email->$k = $v;
5402                         }
5403
5404                         $email->to_addrs = $meta['toaddrs'];
5405                         $email->date_sent = $meta['date_start'];
5406                         //_ppf($email,true);
5407
5408                         $this->email = $email;
5409                         $this->email->email2init();
5410                         $ret = 'cache';
5411                 } else {
5412                         $GLOBALS['log']->info("INBOUNDEMAIL: opening new connection for setEmailForDisplay()");
5413             if($this->isPop3Protocol()) {
5414                 $msgNo = $this->getCorrectMessageNoForPop3($uid);
5415             } else {
5416                                 if(empty($this->conn)) {
5417                                         $this->connectMailserver();
5418                                 }
5419                 $msgNo = ($isMsgNo) ? $uid : imap_msgno($this->conn, $uid);
5420             }
5421                         if(empty($this->conn)) {
5422                                 $status = $this->connectMailserver();
5423                                 if($status == "false") {
5424                                         $this->email = new Email();
5425                                         $this->email->name = $app_strings['LBL_EMAIL_ERROR_MAILSERVERCONNECTION'];
5426                                         $ret = 'error';
5427                                         return $ret;
5428                                 }
5429
5430                         }
5431
5432                         $this->importOneEmail($msgNo, $uid, true);
5433                         $this->email->id = '';
5434                         $this->email->new_with_id = false;
5435                         $ret = 'import';
5436                 }
5437
5438                 if($setRead) {
5439                         $this->setStatuses($uid, 'seen', 1);
5440                 }
5441
5442                 return $ret;
5443         }
5444
5445
5446         /**
5447          * Sets status for a particular attribute on the mailserver and the local cache file
5448          */
5449         function setStatuses($uid, $field, $value) {
5450                 global $sugar_config;
5451                 /** available status fields
5452                     [subject] => aaa
5453                     [from] => Some Name
5454                     [to] => Some Name
5455                     [date] => Mon, 22 Jan 2007 17:32:57 -0800
5456                     [message_id] =>
5457                     [size] => 718
5458                     [uid] => 191
5459                     [msgno] => 141
5460                     [recent] => 0
5461                     [flagged] => 0
5462                     [answered] => 0
5463                     [deleted] => 0
5464                     [seen] => 1
5465                     [draft] => 0
5466                 */
5467                 // local cache
5468                 $file = "{$this->mailbox}.imapFetchOverview.php";
5469                 $overviews = $this->getCacheValueForUIDs($this->mailbox, array($uid));
5470
5471                 if(!empty($overviews)) {
5472                         $updates = array();
5473
5474                         foreach($overviews['retArr'] as $k => $obj) {
5475                                 if($obj->imap_uid == $uid) {
5476                                         $obj->$field = $value;
5477                                         $updates[] = $obj;
5478                                 }
5479                         }
5480
5481                         if(!empty($updates)) {
5482                                 $this->setCacheValue($this->mailbox, array(), $updates);
5483                         }
5484                 }
5485         }
5486
5487         /**
5488          * Removes an email from the cache file, deletes the message from the cache too
5489          * @param string String of uids, comma delimited
5490          */
5491         function deleteMessageFromCache($uids) {
5492                 global $sugar_config;
5493                 global $app_strings;
5494
5495                 // delete message cache file and email_cache file
5496                 $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
5497
5498                 foreach($exUids as $uid) {
5499                         // local cache
5500                         if ($this->isPop3Protocol()) {
5501                                 $q = "DELETE FROM email_cache WHERE message_id = '{$uid}' AND ie_id = '{$this->id}'";
5502                         } else {
5503                                 $q = "DELETE FROM email_cache WHERE imap_uid = {$uid} AND ie_id = '{$this->id}'";
5504                         }
5505                         $r = $this->db->query($q);
5506                         if ($this->isPop3Protocol()) {
5507                                 $uid = md5($uid);
5508                         } // if
5509                         $msgCacheFile = "{$sugar_config['cache_dir']}modules/Emails/{$this->id}/messages/{$this->mailbox}{$uid}.php";
5510                         if(file_exists($msgCacheFile)) {
5511                                 if(!unlink($msgCacheFile)) {
5512                                         $GLOBALS['log']->error("***ERROR: InboundEmail could not delete the cache file [ {$msgCacheFile} ]");
5513                                 }
5514                         }
5515                 }
5516         }
5517
5518
5519         /**
5520          * Shows one email.
5521          * @param int uid UID of email to display
5522          * @param string mbox Mailbox to look in for the message
5523          * @param bool isMsgNo Flag to assume $uid is a MessageNo, not UniqueID, default false
5524          */
5525         function displayOneEmail($uid, $mbox, $isMsgNo=false) {
5526                 require_once("include/JSON.php");
5527
5528                 global $timedate;
5529                 global $app_strings;
5530                 global $app_list_strings;
5531                 global $sugar_smarty;
5532                 global $theme;
5533                 global $current_user;
5534
5535                 $fetchedAttributes = array(
5536                         'name',
5537                         'from_name',
5538                         'from_addr',
5539                         'date_start',
5540                         'time_start',
5541                         'message_id',
5542                 );
5543
5544                 $souEmail = array();
5545                 foreach($fetchedAttributes as $k) {
5546                         if ($k == 'date_start') {
5547                                 $this->email->$k . " " . $this->email->time_start;
5548                                 //$timedate->to_display_date_time($msg->date)
5549                                 //$souEmail[$k] = $timedate->to_display_date_time(date('r', strtotime($this->email->$k . " " . $this->email->time_start)));
5550                                 //$souEmail[$k] = $timedate->swap_formats($this->email->$k . " " . $this->email->time_start, $timedate->get_date_time_format(true,$current_user), $timedate->get_db_date_time_format());
5551                                 //$souEmail[$k] = $timedate->to_display_date_time($souEmail[$k]);
5552                                 $souEmail[$k] = $this->email->$k . " " . $this->email->time_start;
5553                         } elseif ($k == 'time_start') {
5554                                 $souEmail[$k] = "";
5555                         } else {
5556                                 $souEmail[$k] = trim($this->email->$k);
5557                         }
5558                 }
5559
5560                 // if a MsgNo is passed in, convert to UID
5561                 if($isMsgNo)
5562                         $uid = imap_uid($this->conn, $uid);
5563
5564                 // meta object to allow quick retrieval for replies
5565                 $meta = array();
5566                 $meta['type'] = $this->email->type;
5567                 $meta['uid'] = $uid;
5568                 $meta['ieId'] = $this->id;
5569                 $meta['email'] = $souEmail;
5570                 $meta['mbox'] = $this->mailbox;
5571                 $ccs = '';
5572                 // imap vs pop3
5573
5574                 // self mapping
5575                 $exMbox = explode("::", $mbox);
5576
5577                 // CC section
5578                 $cc = '';
5579                 if(!empty($this->email->cc_addrs)) {
5580                         //$ccs = $this->collapseLongMailingList($this->email->cc_addrs);
5581                         $ccs = to_html($this->email->cc_addrs_names);
5582                         $cc =<<<eoq
5583                                 <tr>
5584                                         <td NOWRAP valign="top" class="displayEmailLabel">
5585                                                 {$app_strings['LBL_EMAIL_CC']}:
5586                                         </td>
5587                                         <td class="displayEmailValue">
5588                                                 {$ccs}
5589                                         </td>
5590                                 </tr>
5591 eoq;
5592                 }
5593                 $meta['cc'] = $cc;
5594                 $meta['email']['cc_addrs'] = $ccs;
5595                 // attachments
5596                 $attachments = '';
5597                 if ($mbox == "sugar::Emails") {
5598
5599                         $q = "SELECT id, filename FROM notes WHERE parent_id = '{$uid}' AND deleted = 0";
5600                         $r = $this->db->query($q);
5601                         $i = 0;
5602                         while($a = $this->db->fetchByAssoc($r)) {
5603                                 $url = "index.php?entryPoint=download&id={$a['id']}&type=notes";
5604                                 $lbl = ($i == 0) ? $app_strings['LBL_EMAIL_ATTACHMENTS'].":" : '';
5605                                 $i++;
5606                                 $attachments .=<<<EOQ
5607                                 <tr>
5608                                                         <td NOWRAP valign="top" class="displayEmailLabel">
5609                                                                 {$lbl}
5610                                                         </td>
5611                                                         <td NOWRAP valign="top" colspan="2" class="displayEmailValue">
5612                                                                 <a href="{$url}">{$a['filename']}</a>
5613                                                         </td>
5614                                                 </tr>
5615 EOQ;
5616
5617                     } // while
5618
5619
5620                 } else {
5621
5622                         if($this->attachmentCount > 0) {
5623                                 $theCount = $this->attachmentCount;
5624
5625                                 for($i=0; $i<$theCount; $i++) {
5626                                         $lbl = ($i == 0) ? $app_strings['LBL_EMAIL_ATTACHMENTS'].":" : '';
5627                                         $name = $this->getTempFilename(true).$i;
5628                                         $tempName = urlencode($this->tempAttachment[$name]);
5629
5630                                         $url = "index.php?entryPoint=download&id={$name}&type=temp&isTempFile=true&ieId={$this->id}&tempName={$tempName}";
5631
5632                                         $attachments .=<<<eoq
5633                                                 <tr>
5634                                                         <td NOWRAP valign="top" class="displayEmailLabel">
5635                                                                 {$lbl}
5636                                                         </td>
5637                                                         <td NOWRAP valign="top" colspan="2" class="displayEmailValue">
5638                                                                 <a href="{$url}">{$this->tempAttachment[$name]}</a>
5639                                                         </td>
5640                                                 </tr>
5641 eoq;
5642                                 } // for
5643                         } // if
5644                 } // else
5645                 $meta['email']['attachments'] = $attachments;
5646
5647                 // toasddrs
5648                 $meta['email']['toaddrs'] = $this->collapseLongMailingList($this->email->to_addrs);
5649                 $meta['email']['cc_addrs'] = $ccs;
5650
5651                 // body
5652                 $description = (empty($this->email->description_html)) ? nl2br($this->email->description) : $this->email->description_html;
5653                 $meta['email']['description'] = $description;
5654
5655                 // meta-metadata
5656                 $meta['is_sugarEmail'] = ($exMbox[0] == 'sugar') ? true : false;
5657
5658                 if(!$meta['is_sugarEmail']) {
5659                         if($this->isAutoImport) {
5660                                 $meta['is_sugarEmail'] = true;
5661                         }
5662                 } else {
5663                         // mark SugarEmail read
5664                         $q = "UPDATE emails SET status = 'read' WHERE id = '{$uid}'";
5665                         $r = $this->db->query($q);
5666                 }
5667
5668                 $return = array();
5669         $meta['email']['name'] = to_html($this->email->name);
5670         $meta['email']['from_addr'] = ( !empty($this->email->from_addr_name) ) ? to_html($this->email->from_addr_name) : to_html($this->email->from_addr);
5671         $meta['email']['toaddrs'] = ( !empty($this->email->to_addrs_names) ) ? to_html($this->email->to_addrs_names) : to_html($this->email->to_addrs);
5672         $meta['email']['cc_addrs'] = to_html($this->email->cc_addrs_names);
5673         $meta['email']['reply_to_addr'] = to_html($this->email->reply_to_addr);
5674                 $return['meta'] = $meta;
5675
5676                 return $return;
5677         }
5678
5679         /**
5680          * Takes a long list of email addresses from a To or CC field and shows the first 3, the rest hidden
5681          * @param string emails
5682          * @return string
5683          */
5684         function collapseLongMailingList($emails) {
5685                 global $app_strings;
5686
5687                 $ex = explode(",", $emails);
5688                 $i = 0;
5689                 $j = 0;
5690
5691                 if(count($ex) > 3) {
5692                         $emails = "";
5693                         $emailsHidden = "";
5694
5695                         foreach($ex as $email) {
5696                                 if($i < 2) {
5697                                         if(!empty($emails)) {
5698                                                 $emails .= ", ";
5699                                         }
5700                                         $emails .= trim($email);
5701                                 } else {
5702                                         if(!empty($emailsHidden)) {
5703                                                 $emailsHidden .= ", ";
5704                                         }
5705                                         $emailsHidden .= trim($email);
5706                                         $j++;
5707                                 }
5708                                 $i++;
5709                         }
5710
5711                         if(!empty($emailsHidden)) {
5712                                 $email2 = $emails;
5713                                 $emails = "<span onclick='javascript:SUGAR.email2.detailView.showFullEmailList(this);' style='cursor:pointer;'>{$emails} [...{$j} {$app_strings['LBL_MORE']}]</span>";
5714                                 $emailsHidden = "<span onclick='javascript:SUGAR.email2.detailView.showCroppedEmailList(this)' style='cursor:pointer; display:none;'>{$email2}, {$emailsHidden} [ {$app_strings['LBL_LESS']} ]</span>";
5715                         }
5716
5717                         $emails .= $emailsHidden;
5718                 }
5719
5720                 return $emails;
5721         }
5722
5723
5724         /**
5725          * Sorts IMAP's imap_fetch_overview() results
5726          * @param array $arr Array of standard objects
5727          * @param string $sort Column to sort by
5728          * @param string direction Direction to sort by (asc/desc)
5729          * @return array Sorted array of obj.
5730          */
5731         function sortFetchedOverview($arr, $sort=4, $direction='DESC', $forceSeen=false) {
5732                 global $current_user;
5733
5734                 $sortPrefs = $current_user->getPreference('folderSortOrder', 'Emails');
5735                 if(!empty($sortPrefs))
5736                         $listPrefs = $sortPrefs;
5737                 else
5738                         $listPrefs = array();
5739
5740                 if(isset($listPrefs[$this->id][$this->mailbox])) {
5741                         $currentNode = $listPrefs[$this->id][$this->mailbox];
5742                 }
5743
5744                 if(isset($currentNode['current']) && !empty($currentNode['current'])) {
5745                         $sort = $currentNode['current']['sort'];
5746                         $direction = $currentNode['current']['direction'];
5747                 }
5748
5749                 // sort defaults
5750                 if(empty($sort)) {
5751                         $sort = $this->defaultSort;//4;
5752                         $direction = $this->defaultDirection; //'DESC';
5753                 } elseif(!is_numeric($sort)) {
5754                         // handle bad sort index
5755                         $sort = $this->defaultSort;
5756                 } else {
5757                         // translate numeric index to human readable
5758             $sort = $this->hrSort[$sort];
5759                 }
5760                 if(empty($direction)) {
5761                         $direction = 'DESC';
5762                 }
5763
5764
5765
5766                 $retArr = array();
5767                 $sorts = array();
5768
5769                 foreach($arr as $k => $overview) {
5770                         $sorts['flagged'][$k] = $overview->flagged;
5771                         $sorts['status'][$k] = $overview->answered;
5772                         $sorts['from'][$k] = str_replace('"', "", $this->handleMimeHeaderDecode($overview->from));
5773                         $sorts['subj'][$k] = $this->handleMimeHeaderDecode(quoted_printable_decode($overview->subject));
5774                         $sorts['date'][$k] = $overview->date;
5775                 }
5776
5777                 // sort by column
5778                 natcasesort($sorts[$sort]);
5779                 //_ppd($sorts[$sort]);
5780                 // direction
5781                 if(strtolower($direction) == 'desc') {
5782                         $revSorts = array();
5783                         $keys = array_reverse(array_keys($sorts[$sort]));
5784 //                      _pp("count keys in DESC: ".count($keys));
5785 //                      _pp("count elements in sort[sort]: ".count($sorts[$sort]));
5786
5787                         for($i=0; $i<count($keys); $i++) {
5788                                 $v = $keys[$i];
5789                                 $revSorts[$v] = $sorts[$sort][$v];
5790                         }
5791
5792                         //_pp("count post-sort: ".count($revSorts));
5793                         $sorts[$sort] = $revSorts;
5794                 }
5795
5796                 foreach($sorts[$sort] as $k2 => $overview2) {
5797                         $conv = $this->getUnixHeaderDate($arr[$k2]->date);
5798                         $arr[$k2]->date = date('Y-m-d H:i:s', $conv);
5799                         $arr[$k2]->date = $arr[$k2]->date;
5800                         $retArr[] = $arr[$k2];
5801                 }
5802                 //_pp("final count: ".count($retArr));
5803
5804                 $finalReturn = array();
5805                 $finalReturn['retArr'] = $retArr;
5806                 $finalReturn['sortBy'] = $sort;
5807                 $finalReturn['direction'] = $direction;
5808                 return $finalReturn;
5809         }
5810
5811
5812         function setReadFlagOnFolderCache($mbox, $uid) {
5813                 global $sugar_config;
5814
5815                 $this->mailbox = $mbox;
5816
5817                 // cache
5818                 if($this->validCacheExists($this->mailbox)) {
5819                         $ret = $eui->getCacheValue($this->mailbox);
5820
5821                         $updates = array();
5822
5823                         foreach($ret as $k => $v) {
5824                                 if($v->imap_uid == $uid) {
5825                                         $v->seen = 1;
5826                                         $updates[] = $v;
5827                                         break;
5828                                 }
5829                         }
5830
5831                         $this->setCacheValue($this->mailbox, array(), $updates);
5832                 }
5833         }
5834
5835         /**
5836          * Returns a list of emails in a mailbox.
5837          * @param string mbox Name of mailbox using dot notation paths to display
5838          * @param string $forceRefresh Flag to use cache or not
5839          */
5840         function displayFolderContents($mbox, $forceRefresh='false', $page) {
5841                 global $current_user;
5842
5843                 $delimiter = $this->get_stored_options('folderDelimiter');
5844                 if ($delimiter) {
5845                         $mbox = str_replace('.', $delimiter, $mbox);
5846                 }
5847
5848                 $this->mailbox = $mbox;
5849
5850                 // jchi #9424, get sort and direction from user preference
5851                 $sort = 'date';
5852                 $direction = 'desc';
5853                 $sortSerial = $current_user->getPreference('folderSortOrder', 'Emails');
5854                 if(!empty($sortSerial) && !empty($_REQUEST['ieId']) && !empty($_REQUEST['mbox'])) {
5855                         $sortArray = unserialize($sortSerial);
5856                         $sort = $sortArray[$_REQUEST['ieId']][$_REQUEST['mbox']]['current']['sort'];
5857                         $direction = $sortArray[$_REQUEST['ieId']][$_REQUEST['mbox']]['current']['direction'];
5858                 }
5859                 //end
5860
5861                 // save sort order
5862                 if(!empty($_REQUEST['sort']) && !empty($_REQUEST['dir'])) {
5863                         $this->email->et->saveListViewSortOrder($_REQUEST['ieId'], $_REQUEST['mbox'], $_REQUEST['sort'], $_REQUEST['dir']);
5864                         $sort = $_REQUEST['sort'];
5865                         $direction = $_REQUEST['dir'];
5866                 } else {
5867                         $_REQUEST['sort'] = '';
5868                         $_REQUEST['dir'] = '';
5869                 }
5870
5871                 // cache
5872                 $ret = array();
5873                 $cacheUsed = false;
5874                 if($forceRefresh == 'false' && $this->validCacheExists($this->mailbox)) {
5875                         $emailSettings = $current_user->getPreference('emailSettings', 'Emails');
5876
5877                         // cn: default to a low number until user specifies otherwise
5878                         if(empty($emailSettings['showNumInList'])) {
5879                                 $emailSettings['showNumInList'] = 20;
5880                         }
5881
5882                         $ret = $this->getCacheValue($this->mailbox, $emailSettings['showNumInList'], $page, $sort, $direction);
5883                         $cacheUsed = true;
5884                 }
5885
5886                 $out = $this->displayFetchedSortedListXML($ret, $mbox);
5887
5888                 $metadata = array();
5889                 $metadata['mbox'] = $mbox;
5890                 $metadata['ieId'] = $this->id;
5891                 $metadata['name'] = $this->name;
5892                 $metadata['fromCache'] = $cacheUsed ? 1 : 0;
5893                 $metadata['out'] = $out;
5894
5895                 return $metadata;
5896         }
5897
5898         /**
5899          * For a group email account, create subscriptions for all users associated with the
5900          * team assigned to the account.
5901          *
5902          */
5903         function createUserSubscriptionsForGroupAccount()
5904         {
5905             $team = new Team();
5906             $team->retrieve($this->team_id);
5907             $usersList = $team->get_team_members(true);
5908             foreach($usersList as $userObject)
5909             {
5910                 $previousSubscriptions = unserialize(base64_decode($userObject->getPreference('showFolders', 'Emails',$userObject)));
5911                 if($previousSubscriptions === FALSE)
5912                     $previousSubscriptions = array();
5913
5914                 $previousSubscriptions[] = $this->id;
5915
5916                 $encodedSubs = base64_encode(serialize($previousSubscriptions));
5917                 $userObject->setPreference('showFolders',$encodedSubs , '', 'Emails');
5918                 $userObject->savePreferencesToDB();
5919             }
5920     }
5921         /**
5922     * Create a sugar folder for this inbound email account
5923     * if the Enable Auto Import option is selected
5924     *
5925     * @return String Id of the sugar folder created.
5926     */
5927         function createAutoImportSugarFolder()
5928         {
5929             global $current_user;
5930             $guid = create_guid();
5931             $GLOBALS['log']->debug("Creating Sugar Folder for IE with id $guid");
5932             $folder = new SugarFolder();
5933             $folder->id = $guid;
5934             $folder->new_with_id = TRUE;
5935             $folder->name = $this->name;
5936             $folder->has_child = 0;
5937             $folder->is_group = 1;
5938             $folder->assign_to_id = $current_user->id;
5939             $folder->parent_folder = "";
5940
5941
5942             //If this inbound email is marked as inactive, don't add subscriptions.
5943             $addSubscriptions = ($this->status == 'Inactive' || $this->mailbox_type == 'bounce') ? FALSE : TRUE;
5944             $folder->save($addSubscriptions);
5945
5946             return $guid;
5947         }
5948
5949         function validCacheExists($mbox) {
5950                 $q = "SELECT count(*) c FROM email_cache WHERE ie_id = '{$this->id}'";
5951                 $r = $this->db->query($q);
5952                 $a = $this->db->fetchByAssoc($r);
5953                 $count = $a['c'];
5954
5955                 if($count > 0) {
5956                         return true;
5957                 }
5958
5959                 return false;
5960         }
5961
5962
5963
5964
5965         function displayFetchedSortedListXML($ret, $mbox) {
5966
5967                 global $timedate;
5968                 global $current_user;
5969                 global $sugar_config;
5970
5971                 if(empty($ret['retArr'])) {
5972                     return array();
5973                 }
5974
5975                 $tPref = $current_user->getUserDateTimePreferences();
5976
5977                 $return = array();
5978
5979                 foreach($ret['retArr'] as $msg) {
5980
5981                         $flagged        = ($msg->flagged == 0) ? "" : $this->iconFlagged;
5982                         $status         = ($msg->deleted) ? $this->iconDeleted : "";
5983                         $status         = ($msg->draft == 0) ? $status : $this->iconDraft;
5984                         $status         = ($msg->answered == 0) ? $status : $this->iconAnswered;
5985                         $from           = $this->handleMimeHeaderDecode($msg->from);
5986                         $subject        = $this->handleMimeHeaderDecode($msg->subject);
5987                         //$date         = date($tPref['date']." ".$tPref['time'], $msg->date);
5988                         $date           = $timedate->to_display_date_time($msg->date);
5989                         //$date         = date($tPref['date'], $this->getUnixHeaderDate($msg->date));
5990
5991                         $temp = array();
5992                         $temp['flagged'] = $flagged;
5993                         $temp['status'] = $status;
5994                         $temp['from']   = $from;
5995                         $temp['subject'] = $subject;
5996                         $temp['date']   = $date;
5997                         $temp['uid'] = $msg->uid; // either from an imap_search() or massaged cache value
5998                         $temp['mbox'] = $this->mailbox;
5999                         $temp['ieId'] = $this->id;
6000                         $temp['site_url'] = $sugar_config['site_url'];
6001                         $temp['seen'] = $msg->seen;
6002                         $temp['type'] = (isset($msg->type)) ? $msg->type: 'remote';
6003                         $temp['to_addrs'] = $msg->to;
6004                         $temp['hasAttach'] = '0';
6005
6006                         $return[] = $temp;
6007                 }
6008
6009                 return $return;
6010         }
6011
6012
6013
6014         /**
6015          * retrieves the mailboxes for a given account in the following format
6016          * Array(
6017             [INBOX] => Array
6018                 (
6019                     [Bugs] => Bugs
6020                     [Builder] => Builder
6021                     [DEBUG] => Array
6022                         (
6023                             [out] => out
6024                             [test] => test
6025                         )
6026                 )
6027          * @param bool $justRaw Default false
6028          * @return array
6029          */
6030         function getMailboxes($justRaw=false) {
6031                 if($justRaw == true) {
6032                         return $this->mailboxarray;
6033                 } // if
6034
6035                 return $this->generateMultiDimArrayFromFlatArray($this->mailboxarray, $this->retrieveDelimiter());
6036                 /*
6037                 $serviceString = $this->getConnectString('', '', false);
6038
6039                 if(strpos($serviceString, 'pop3')) {
6040                         $obj = new temp();
6041                         $obj->name = $serviceString."INBOX";
6042                         $boxes = array("INBOX" => $obj);
6043                 } else {
6044                         $boxes = imap_getmailboxes($this->conn, $serviceString, "*");
6045                 }
6046                 $raw = array();
6047                 //_ppd($boxes);
6048                 $delimiter = '.';
6049                 // clean MBOX path names
6050                 foreach($boxes as $k => $mbox) {
6051                         $raw[] = str_replace($serviceString, "", $mbox->name);
6052                         if ($mbox->delimiter) {
6053                                 $delimiter = $mbox->delimiter;
6054                         }
6055                 }
6056                 $storedOptions = unserialize(base64_decode($this->stored_options));
6057                 $storedOptions['folderDelimiter'] = $delimiter;
6058                 $this->stored_options = base64_encode(serialize($storedOptions));
6059         $this->save();
6060
6061                 sort($raw);
6062                 //_ppd($raw);
6063
6064                 // used by $this->search()
6065                 if($justRaw == true) {
6066                         return $raw;
6067                 }
6068
6069
6070                 // generate a multi-dimensional array to iterate through
6071                 $ret = array();
6072                 foreach($raw as $mbox) {
6073                         $ret = $this->sortMailboxes($mbox, $ret, $delimiter);
6074                 }
6075                 //_ppd($ret);
6076                 return $ret;
6077                 */
6078         }
6079
6080         function getMailBoxesForGroupAccount() {
6081                 $mailboxes = $this->generateMultiDimArrayFromFlatArray(explode(",", $this->mailbox), $this->retrieveDelimiter());
6082                 $mailboxesArray = $this->generateFlatArrayFromMultiDimArray($mailboxes, $this->retrieveDelimiter());
6083                 $mailboxesArray = $this->filterMailBoxFromRaw(explode(",", $this->mailbox), $mailboxesArray);
6084                 $this->saveMailBoxFolders($mailboxesArray);
6085                 /*
6086                 if ($this->mailbox != $this->$email_user) {
6087                         $mailboxes = $this->sortMailboxes($this->mailbox, $this->retrieveDelimiter());
6088                         $mailboxesArray = $this->generateFlatArrayFromMultiDimArray($mailboxes, $this->retrieveDelimiter());
6089                         $this->saveMailBoxFolders($mailboxesArray);
6090                         // save mailbox value of an inbound email account to email user
6091                         $this->saveMailBoxValueOfInboundEmail();
6092                 } else {
6093                         $mailboxes = $this->getMailboxes();
6094                 }
6095                 */
6096                 return $mailboxes;
6097         } // fn
6098
6099         function saveMailBoxFolders($value) {
6100                 if (is_array($value)) {
6101                         $value = implode(",", $value);
6102                 }
6103                 $this->mailboxarray = explode(",", $value);
6104                 $value = $this->db->helper->escape_quote($value);
6105                 //$query = "update config set value = '{$value}' where category='InboundEmail' and name='{$this->id}' )";
6106                 $query = "update inbound_email set mailbox = '{$value}' where id ='{$this->id}'";
6107                 $this->db->query($query);
6108         }
6109
6110         function insertMailBoxFolders($value) {
6111                 $query = "select value from config where category='InboundEmail' and name='{$this->id}'";
6112                 $r = $this->db->query($query);
6113                 $a = $this->db->fetchByAssoc($r);
6114                 if (empty($a['value'])) {
6115                         if (is_array($value)) {
6116                                 $value = implode(",", $value);
6117                         }
6118                         $this->mailboxarray = explode(",", $value);
6119                         $value = $this->db->helper->escape_quote($value);
6120
6121                         $query = "INSERT INTO config VALUES('InboundEmail', '{$this->id}', '{$value}')";
6122                         $this->db->query($query);
6123                 } // if
6124         }
6125
6126         function saveMailBoxValueOfInboundEmail() {
6127                 $query = "update Inbound_email set mailbox = '{$this->email_user}'";
6128                 $this->db->query($query);
6129         }
6130
6131         function retrieveMailBoxFolders() {
6132                 $this->mailboxarray = explode(",", $this->mailbox);
6133                 /*
6134                 $query = "select value from config where category='InboundEmail' and name='{$this->id}'";
6135                 $r = $this->db->query($query);
6136                 $a = $this->db->fetchByAssoc($r);
6137                 $this->mailboxarray = explode(",", $a['value']);
6138                 */
6139         } // fn
6140
6141
6142         function retrieveDelimiter() {
6143                 $delimiter = $this->get_stored_options('folderDelimiter');
6144         if (!$delimiter) {
6145                 $delimiter = '.';
6146         }
6147                 return $delimiter;
6148         } // fn
6149
6150         function generateFlatArrayFromMultiDimArray($arraymbox, $delimiter) {
6151                 $ret = array();
6152                 foreach($arraymbox as $key => $value) {
6153                         $this->generateArrayData($key, $value, $ret, $delimiter);
6154                 } // foreach
6155                 return $ret;
6156
6157         } // fn
6158
6159         function generateMultiDimArrayFromFlatArray($raw, $delimiter) {
6160                 // generate a multi-dimensional array to iterate through
6161                 $ret = array();
6162                 foreach($raw as $mbox) {
6163                         $ret = $this->sortMailboxes($mbox, $ret, $delimiter);
6164                 }
6165                 return $ret;
6166
6167         } // fn
6168
6169         function generateArrayData($key, $arraymbox, &$ret, $delimiter) {
6170                 $ret [] = $key;
6171                 if (is_array($arraymbox)) {
6172                         foreach($arraymbox as $mboxKey => $value) {
6173                                 $newKey = $key . $delimiter . $mboxKey;
6174                                 $this->generateArrayData($newKey, $value, $ret, $delimiter);
6175                         } // foreach
6176                 } // if
6177         }
6178
6179         /**
6180          * sorts the folders in a mailbox in a multi-dimensional array
6181          * @param string $MBOX
6182          * @param array $ret
6183          * @return array
6184          */
6185         function sortMailboxes($mbox, $ret, $delimeter = ".") {
6186                 if(strpos($mbox, $delimeter)) {
6187                         $node = substr($mbox, 0, strpos($mbox, $delimeter));
6188                         $nodeAfter = substr($mbox, strpos($mbox, $node) + strlen($node) + 1, strlen($mbox));
6189
6190                         if(!isset($ret[$node])) {
6191                                 $ret[$node] = array();
6192                         } elseif(isset($ret[$node]) && !is_array($ret[$node])) {
6193                                 $ret[$node] = array();
6194                         }
6195                         $ret[$node] = $this->sortMailboxes($nodeAfter, $ret[$node], $delimeter);
6196                 } else {
6197                         $ret[$mbox] = $mbox;
6198                 }
6199
6200                 return $ret;
6201         }
6202
6203         /**
6204          * parses Sugar's storage method for imap server service strings
6205          * @return string
6206          */
6207         function getServiceString() {
6208                 $service = '';
6209                 $exServ = explode('::', $this->service);
6210
6211                 foreach($exServ as $v) {
6212                         if(!empty($v) && ($v != 'imap' && $v !='pop3')) {
6213                                 $service .= '/'.$v;
6214                         }
6215                 }
6216                 return $service;
6217         }
6218
6219 } // end class definition
6220
6221
6222 /**
6223  * Simple class to mirror the passed object from an imap_fetch_overview() call
6224  */
6225 class Overview {
6226         var $subject;
6227         var $from;
6228         var $fromaddr;
6229         var $to;
6230         var $toaddr;
6231         var $date;
6232         var $message_id;
6233         var $size;
6234         var $uid;
6235         var $msgno;
6236         var $recent;
6237         var $flagged;
6238         var $answered;
6239         var $deleted;
6240         var $seen;
6241         var $draft;
6242         var $indices; /* = array(
6243
6244                         array(
6245                                 'name'                  => 'mail_date',
6246                                 'type'                  => 'index',
6247                                 'fields'                => array(
6248                                         'mbox',
6249                                         'senddate',
6250                                 )
6251                         ),
6252                         array(
6253                                 'name'                  => 'mail_from',
6254                                 'type'                  => 'index',
6255                                 'fields'                => array(
6256                                         'mbox',
6257                                         'fromaddr',
6258                                 )
6259                         ),
6260                         array(
6261                                 'name'                  => 'mail_subj',
6262                                 'type'                  => 'index',
6263                                 'fields'                => array(
6264                                         'mbox',
6265                                         'subject',
6266                                 )
6267                         ),
6268                 );
6269         */
6270         var $fieldDefs;/* = array(
6271                         'mbox' => array(
6272                                 'name'          => 'mbox',
6273                                 'type'          => 'varchar',
6274                                 'len'           => 60,
6275                                 'required'      => true,
6276                         ),
6277                         'subject' => array(
6278                                 'name'          => 'subject',
6279                                 'type'          => 'varchar',
6280                                 'len'           => 100,
6281                                 'required'      => false,
6282                         ),
6283                         'fromaddr' => array(
6284                                 'name'          => 'fromaddr',
6285                                 'type'          => 'varchar',
6286                                 'len'           => 100,
6287                                 'required'      => true,
6288                         ),
6289                         'toaddr' => array(
6290                                 'name'          => 'toaddr',
6291                                 'type'          => 'varchar',
6292                                 'len'           => 100,
6293                                 'required'      => true,
6294                         ),
6295                         'senddate' => array(
6296                                 'name'          => 'senddate',
6297                                 'type'          => 'datetime',
6298                                 'required'      => true,
6299                         ),
6300                         'message_id' => array(
6301                                 'name'          => 'message_id',
6302                                 'type'          => 'varchar',
6303                                 'len'           => 255,
6304                                 'required'      => false,
6305                         ),
6306                         'mailsize' => array(
6307                                 'name'          => 'mailsize',
6308                                 'type'          => 'uint',
6309                                 'len'           => 16,
6310                                 'required'      => true,
6311                         ),
6312                         'uid' => array(
6313                                 'name'          => 'uid',
6314                                 'type'          => 'uint',
6315                                 'len'           => 32,
6316                                 'required'      => true,
6317                         ),
6318                         'msgno' => array(
6319                                 'name'          => 'msgno',
6320                                 'type'          => 'uint',
6321                                 'len'           => 32,
6322                                 'required'      => false,
6323                         ),
6324                         'recent' => array(
6325                                 'name'          => 'recent',
6326                                 'type'          => 'tinyint',
6327                                 'len'           => 1,
6328                                 'required'      => true,
6329                         ),
6330                         'flagged' => array(
6331                                 'name'          => 'flagged',
6332                                 'type'          => 'tinyint',
6333                                 'len'           => 1,
6334                                 'required'      => true,
6335                         ),
6336                         'answered' => array(
6337                                 'name'          => 'answered',
6338                                 'type'          => 'tinyint',
6339                                 'len'           => 1,
6340                                 'required'      => true,
6341                         ),
6342                         'deleted' => array(
6343                                 'name'          => 'deleted',
6344                                 'type'          => 'tinyint',
6345                                 'len'           => 1,
6346                                 'required'      => true,
6347                         ),
6348                         'seen' => array(
6349                                 'name'          => 'seen',
6350                                 'type'          => 'tinyint',
6351                                 'len'           => 1,
6352                                 'required'      => true,
6353                         ),
6354                         'draft' => array(
6355                                 'name'          => 'draft',
6356                                 'type'          => 'tinyint',
6357                                 'len'           => 1,
6358                                 'required'      => true,
6359                         ),
6360                 );
6361         */
6362         function Overview() {
6363                 global $dictionary;
6364
6365                 if(!isset($dictionary['email_cache']) || empty($dictionary['email_cache'])) {
6366                         if(file_exists('custom/metadata/email_cacheMetaData.php')) {
6367                            include('custom/metadata/email_cacheMetaData.php');
6368                         } else {
6369                            include('metadata/email_cacheMetaData.php');
6370                         }
6371                 }
6372
6373                 $this->fieldDefs = $dictionary['email_cache']['fields'];
6374                 $this->indices = $dictionary['email_cache']['indices'];
6375         }
6376 }