]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/Emails/EmailUI.php
Release 6.2.0
[Github/sugarcrm.git] / modules / Emails / EmailUI.php
1 <?php
2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4  * SugarCRM Community Edition 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:
41  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. All Rights
42  * Reserved. Contributor(s): ______________________________________..
43  *********************************************************************************/
44
45 require_once("include/ytree/Tree.php");
46 require_once("include/ytree/ExtNode.php");
47 require_once("include/SugarFolders/SugarFolders.php");
48
49
50
51 class EmailUI {
52         var $db;
53         var $folder; // place holder for SugarFolder object
54         var $folderStates = array(); // array of folderPath names and their states (1/0)
55         var $smarty;
56         var $addressSeparators = array(";", ",");
57         var $rolloverStyle = "<style>div#rollover {position: relative;float: left;margin: none;text-decoration: none;}div#rollover a:hover {padding: 0;}div#rollover a span {display: none;}div#rollover a:hover span {text-decoration: none;display: block;width: 250px;margin-top: 5px;margin-left: 5px;position: absolute;padding: 10px;color: #333; border: 1px solid #ccc; background-color: #fff; font-size: 12px;z-index: 1000;}</style>\n";
58         var $groupCss = "<span class='groupInbox'>";
59         var $cacheTimeouts = array(
60                 'messages'              => 86400,       // 24 hours
61                 'folders'               => 300,         // 5 mins
62                 'attachments'   => 86400,       // 24 hours
63         );
64         var $userCacheDir = '';
65         var $coreDynamicFolderQuery = "SELECT emails.id polymorphic_id, 'Emails' polymorphic_module FROM emails
66                                                                    JOIN emails_text on emails.id = emails_text.email_id
67                                    WHERE (type = '::TYPE::' OR status = '::STATUS::') AND assigned_user_id = '::USER_ID::' AND emails.deleted = '0'";
68
69         /**
70          * Sole constructor
71          */
72         function EmailUI() {
73                 global $sugar_config;
74                 global $current_user;
75
76                 $folderStateSerial = $current_user->getPreference('folderOpenState', 'Emails');
77
78                 if(!empty($folderStateSerial)) {
79                         $this->folderStates = unserialize($folderStateSerial);
80                 }
81
82                 $this->smarty = new Sugar_Smarty();
83                 $this->folder = new SugarFolder();
84                 $this->userCacheDir = "{$sugar_config['cache_dir']}modules/Emails/{$current_user->id}";
85                 $this->db = DBManagerFactory::getInstance();
86         }
87
88
89         ///////////////////////////////////////////////////////////////////////////
90         ////    CORE
91         /**
92          * Renders the frame for emails
93          */
94         function displayEmailFrame() {
95
96                 require_once("include/OutboundEmail/OutboundEmail.php");
97
98                 global $app_strings, $app_list_strings;
99                 global $mod_strings;
100                 global $sugar_config;
101                 global $current_user;
102                 global $locale;
103                 global $timedate;
104                 global $theme;
105                 global $sugar_version;
106                 global $sugar_flavor;
107                 global $current_language;
108                 global $server_unique_key;
109
110                 $this->preflightUserCache();
111                 $ie = new InboundEmail();
112
113                 // focus listView
114                 $list = array(
115                         'mbox' => 'Home',
116                         'ieId' => '',
117                         'name' => 'Home',
118                         'unreadChecked' => 0,
119                         'out' => array(),
120                 );
121
122                 $this->_generateComposeConfigData('email_compose');
123
124
125         //Check quick create module access
126         $QCAvailableModules = $this->_loadQuickCreateModules();
127
128         //Get the quickSearch js needed for assigned user id on Search Tab
129         require_once('include/QuickSearchDefaults.php');
130         $qsd = new QuickSearchDefaults();
131         $qsd->setFormName('advancedSearchForm');
132         $quicksearchAssignedUser = "if(typeof sqs_objects == 'undefined'){var sqs_objects = new Array;}";
133         $quicksearchAssignedUser .= "sqs_objects['advancedSearchForm_assigned_user_name']=" . json_encode($qsd->getQSUser()) . ";";
134         $qsd->setFormName('Distribute');
135         $quicksearchAssignedUser .= "sqs_objects['Distribute_assigned_user_name']=" . json_encode($qsd->getQSUser()) . ";";
136         $this->smarty->assign('quickSearchForAssignedUser', $quicksearchAssignedUser);
137
138
139                 ///////////////////////////////////////////////////////////////////////
140                 ////    BASIC ASSIGNS
141                 $this->smarty->assign("currentUserId",$current_user->id);
142                 $this->smarty->assign("CURRENT_USER_EMAIL",$current_user->email1);
143         $this->smarty->assign("currentUserName",$current_user->name);
144                 $this->smarty->assign('yuiPath', 'modules/Emails/javascript/yui-ext/');
145                 $this->smarty->assign('app_strings', $app_strings);
146                 $this->smarty->assign('mod_strings', $mod_strings);
147                 $this->smarty->assign('theme', $theme);
148                 $this->smarty->assign('sugar_config', $sugar_config);
149                 $this->smarty->assign('is_admin', $current_user->is_admin);
150                 $this->smarty->assign('sugar_version', $sugar_version);
151                 $this->smarty->assign('sugar_flavor', $sugar_flavor);
152                 $this->smarty->assign('current_language', $current_language);
153                 $this->smarty->assign('server_unique_key', $server_unique_key);
154                 $this->smarty->assign('qcModules', json_encode($QCAvailableModules));
155                 $extAllDebugValue = "ext-all.js";
156                 $this->smarty->assign('extFileName', $extAllDebugValue);
157
158                 // settings: general
159                 $e2UserPreferences = $this->getUserPrefsJS();
160                 $emailSettings = $e2UserPreferences['emailSettings'];
161
162                 ///////////////////////////////////////////////////////////////////////
163                 ////    USER SETTINGS
164                 // settings: accounts
165
166                 $cuDatePref = $current_user->getUserDateTimePreferences();
167                 $this->smarty->assign('dateFormat', $cuDatePref['date']);
168                 $this->smarty->assign('dateFormatExample', str_replace(array("Y", "m", "d"), array("yyyy", "mm", "dd"), $cuDatePref['date']));
169                 $this->smarty->assign('calFormat', $timedate->get_cal_date_format());
170         $this->smarty->assign('TIME_FORMAT', $timedate->get_user_time_format());
171                 
172                 $ieAccounts = $ie->retrieveByGroupId($current_user->id);
173                 $ieAccountsOptions = "<option value=''>{$app_strings['LBL_NONE']}</option>\n";
174
175                 foreach($ieAccounts as $k => $v) {
176                         $disabled = (!$v->is_personal) ? "DISABLED" : "";
177                         $group = (!$v->is_personal) ? $app_strings['LBL_EMAIL_GROUP']."." : "";
178                         $ieAccountsOptions .= "<option value='{$v->id}' $disabled>{$group}{$v->name}</option>\n";
179                 }
180
181                 $this->smarty->assign('ieAccounts', $ieAccountsOptions);
182                 $this->smarty->assign('rollover', $this->rolloverStyle);
183
184                 $protocol = filterInboundEmailPopSelection($app_list_strings['dom_email_server_type']);
185                 $this->smarty->assign('PROTOCOL', get_select_options_with_id($protocol, ''));
186                 $this->smarty->assign('MAIL_SSL_OPTIONS', get_select_options_with_id($app_list_strings['email_settings_for_ssl'], ''));
187                 $this->smarty->assign('ie_mod_strings', return_module_language($current_language, 'InboundEmail'));
188
189                 $charsetSelectedValue = isset($emailSettings['defaultOutboundCharset']) ? $emailSettings['defaultOutboundCharset'] : false;
190                 if (!$charsetSelectedValue) {
191                         $charsetSelectedValue = $current_user->getPreference('default_export_charset', 'global');
192                         if (!$charsetSelectedValue) {
193                                 $charsetSelectedValue = $locale->getPrecedentPreference('default_email_charset');
194                         }
195                 }
196                 $charset = array(
197                         'options' => $locale->getCharsetSelect(),
198                         'selected' => $charsetSelectedValue,
199                 );
200                 $this->smarty->assign('charset', $charset);
201
202                 $emailCheckInterval = array('options' => $app_strings['LBL_EMAIL_CHECK_INTERVAL_DOM'], 'selected' => $emailSettings['emailCheckInterval']);
203                 $this->smarty->assign('emailCheckInterval', $emailCheckInterval);
204                 $this->smarty->assign('attachmentsSearchOptions', $app_list_strings['checkbox_dom']);
205                 $this->smarty->assign('sendPlainTextChecked', ($emailSettings['sendPlainText'] == 1) ? 'CHECKED' : '');
206                 $this->smarty->assign('showNumInList', get_select_options_with_id($app_list_strings['email_settings_num_dom'], $emailSettings['showNumInList']));
207
208                 ////    END USER SETTINGS
209                 ///////////////////////////////////////////////////////////////////////
210
211                 ///////////////////////////////////////////////////////////////////////
212                 ////    SIGNATURES
213                 $prependSignature = ($current_user->getPreference('signature_prepend')) ? 'true' : 'false';
214                 $defsigID = $current_user->getPreference('signature_default');
215                 $this->smarty->assign('signatures', $current_user->getSignatures(false, $defsigID));
216                 $this->smarty->assign('signaturesSettings', $current_user->getSignatures(false, $defsigID, false));
217                 $signatureButtons = $current_user->getSignatureButtons('SUGAR.email2.settings.createSignature', !empty($defsigID));
218                 if (!empty($defsigID)) {
219                         $signatureButtons = $signatureButtons . '<span name="delete_sig" id="delete_sig" style="visibility:inherit;"><input class="button" onclick="javascript:SUGAR.email2.settings.deleteSignature();" value="'.$app_strings['LBL_EMAIL_DELETE'].'" type="button" tabindex="392">&nbsp;
220                                         </span>';
221                 } else {
222                         $signatureButtons = $signatureButtons . '<span name="delete_sig" id="delete_sig" style="visibility:hidden;"><input class="button" onclick="javascript:SUGAR.email2.settings.deleteSignature();" value="'.$app_strings['LBL_EMAIL_DELETE'].'" type="button" tabindex="392">&nbsp;
223                                         </span>';
224                 }
225                 $this->smarty->assign('signatureButtons', $signatureButtons);
226                 $this->smarty->assign('signaturePrepend', $prependSignature == 'true' ? 'CHECKED' : '');
227                 ////    END SIGNATURES
228                 ///////////////////////////////////////////////////////////////////////
229
230                 ///////////////////////////////////////////////////////////////////////
231                 ////    EMAIL TEMPLATES
232                 $email_templates_arr = $this->getEmailTemplatesArray();
233                 natcasesort($email_templates_arr);
234                 $this->smarty->assign('EMAIL_TEMPLATE_OPTIONS', get_select_options_with_id($email_templates_arr, ''));
235                 ////    END EMAIL TEMPLATES
236                 ///////////////////////////////////////////////////////////////////////
237
238                 ///////////////////////////////////////////////////////////////////////
239                 ////    FOLDERS & TreeView
240                 $this->smarty->assign('groupUserOptions', $ie->getGroupsWithSelectOptions(array('' => $app_strings['LBL_EMAIL_CREATE_NEW'])));
241
242                 $tree = $this->getMailboxNodes();
243
244                 // preloaded folder
245                 $preloadFolder = 'lazyLoadFolder = ';
246                 $focusFolderSerial = $current_user->getPreference('focusFolder', 'Emails');
247                 if(!empty($focusFolderSerial)) {
248                         $focusFolder = unserialize($focusFolderSerial);
249                         //$focusFolder['ieId'], $focusFolder['folder']
250                         $preloadFolder .= json_encode($focusFolder).";";
251                 } else {
252                         $preloadFolder .= "new Object();";
253                 }
254                 ////    END FOLDERS
255                 ///////////////////////////////////////////////////////////////////////
256
257                 $out = "";
258                 $out .= $this->smarty->fetch("modules/Emails/templates/_baseEmail.tpl");
259                 $out .= $tree->generate_header();
260                 $out .= $tree->generateNodesNoInit(true, 'email2treeinit');
261                 $out .=<<<eoq
262                         <script type="text/javascript" language="javascript">
263
264                                 var loader = new YAHOO.util.YUILoader({
265                                     require : [
266                                         "layout", "element", "tabview", "menu",
267                                         "cookie", "sugarwidgets"
268                                     ],
269                                     loadOptional: true,
270                                     skin: { base: 'blank', defaultSkin: '' },
271                                     onSuccess: email2init,
272                                     allowRollup: true,
273                                     base: "include/javascript/yui/build/"
274                                 });
275                                 loader.addModule({
276                                     name :"sugarwidgets",
277                                     type : "js",
278                                     fullpath: "include/javascript/sugarwidgets/SugarYUIWidgets.js",
279                                     varName: "YAHOO.SUGAR",
280                                     requires: ["datatable", "dragdrop", "treeview", "tabview", "calendar"]
281                                 });
282                                 loader.insert();
283
284                                 {$preloadFolder};
285         
286                         </script>
287 eoq;
288
289
290                 return $out;
291         }
292
293         /**
294          * Generate the frame needed for the quick compose email UI.  This frame is loaded dynamically
295          * by an ajax call.
296          *
297          * @return JSON An object containing html markup and js script variables.
298          */
299         function displayQuickComposeEmailFrame()
300         {
301         $this->preflightUserCache();
302
303             $this->_generateComposeConfigData('email_compose_light');
304                 $javascriptOut = $this->smarty->fetch("modules/Emails/templates/_baseConfigData.tpl");
305
306         $divOut = $this->smarty->fetch("modules/Emails/templates/overlay.tpl");
307         $divOut .= $this->smarty->fetch("modules/Emails/templates/addressSearchContent.tpl");
308
309         $outData = array('jsData' => $javascriptOut,'divData'=> $divOut);
310         $out = json_encode($outData);
311         return $out;
312     }
313
314     /**
315      * Load the modules from the metadata file and include in a custom one if it exists
316      *
317      * @return array
318      */
319     protected function _loadQuickCreateModules()
320     {
321         $QCAvailableModules = array();
322         $QCModules = array();
323
324         include('modules/Emails/metadata/qcmodulesdefs.php');
325         if (file_exists('custom/modules/Emails/metadata/qcmodulesdefs.php')) {
326             include('custom/modules/Emails/metadata/qcmodulesdefs.php');
327         }
328
329         foreach($QCModules as $module) {
330             $seed = SugarModule::get($module)->loadBean();
331             if ( ( $seed instanceOf SugarBean ) && $seed->ACLAccess('edit') ) {
332                 $QCAvailableModules[] = $module;
333             }
334         }
335         
336         return $QCAvailableModules;
337     }
338
339     /**
340      * Given an email link url (eg. index.php?action=Compose&parent_type=Contacts...) break up the
341      * request components and create a compose package that can be used by the quick compose UI. The
342      * result is typically passed into the js call SUGAR.quickCompose.init which initalizes the quick compose
343      * UI.
344      *
345      * @param String $emailLinkUrl
346      * @return JSON Object containing the composePackage and full link url
347      */
348     function generateComposePackageForQuickCreateFromComposeUrl($emailLinkUrl, $lazyLoad=false)
349     {
350         $composeData = explode("&",$emailLinkUrl);
351         $a_composeData = array();
352         foreach ($composeData as $singleRequest)
353         {
354                 $tmp = explode("=",$singleRequest);
355                 $a_composeData[$tmp[0]] = urldecode($tmp[1]);
356         }
357
358         return $this->generateComposePackageForQuickCreate($a_composeData,$emailLinkUrl, $lazyLoad);
359     }
360     /**
361      * Generate the composePackage for the quick compose email UI.  The package contains
362      * key/value pairs generated by the Compose.php file which are then set into the
363      * quick compose email UI (eg. to addr, parent id, parent type, etc)
364      *
365      * @param Array $composeData Associative array read and processed by generateComposeDataPackage.
366      * @param String $fullLinkUrl A link that contains all pertinant information so the user can be
367      *                              directed to the full compose screen if needed
368      * @return JSON Object containg composePackage and fullLinkUrl
369      */
370     function generateComposePackageForQuickCreate($composeData,$fullLinkUrl, $lazyLoad=false)
371     {
372         $_REQUEST['forQuickCreate'] = true;
373
374         if(!$lazyLoad){
375             require_once('modules/Emails/Compose.php');
376             $composePackage = generateComposeDataPackage($composeData,FALSE);
377         }else{
378             $composePackage = $composeData;
379         }
380
381         // JSON object is passed into the function defined within the a href onclick event
382         // which is delimeted by '.  Need to escape all single quotes and &, <, >
383         // but not double quotes since json would escape them
384         foreach ($composePackage as $key => $singleCompose)
385         {
386            if (is_string($singleCompose))
387                $composePackage[$key] = str_replace("&nbsp;", " ", from_html($singleCompose));
388         }
389
390         $quickComposeOptions = array('fullComposeUrl' => $fullLinkUrl,'composePackage' => $composePackage);
391
392         $j_quickComposeOptions = JSON::encode($quickComposeOptions, false ,true);
393
394
395         return $j_quickComposeOptions;
396     }
397
398     /**
399      * Generate the config data needed for the Full Compose UI and the Quick Compose UI.  The set of config data
400      * returned is the minimum set needed by the quick compose UI.
401      *
402      * @param String $type Drives which tinyMCE options will be included.
403      */
404         function _generateComposeConfigData($type = "email_compose_light" )
405         {
406                 global $app_list_strings,$current_user, $app_strings, $mod_strings,$current_language,$locale;
407
408                 //Link drop-downs
409                 $parent_types = $app_list_strings['record_type_display'];
410                 $disabled_parent_types = ACLController::disabledModuleList($parent_types, false, 'list');
411
412                 foreach($disabled_parent_types as $disabled_parent_type) {
413                   unset($parent_types[$disabled_parent_type]);
414                 }
415                 asort($parent_types);
416                 $linkBeans = json_encode(get_select_options_with_id($parent_types, ''));
417
418                 //TinyMCE Config
419                 require_once("include/SugarTinyMCE.php");
420         $tiny = new SugarTinyMCE();
421         $tinyConf = $tiny->getConfig($type);
422
423         //Generate Language Packs
424                 $lang = "var app_strings = new Object();\n";
425                 foreach($app_strings as $k => $v) {
426                         if(strpos($k, 'LBL_EMAIL_') !== false) {
427                                 $lang .= "app_strings.{$k} = '{$v}';\n";
428                         }
429                 }
430                 //Get the email mod strings but don't use the global variable as this may be overridden by
431                 //other modules when the quick create is rendered.
432                 $email_mod_strings = return_module_language($current_language,'Emails');
433                 $modStrings = "var mod_strings = new Object();\n";
434                 foreach($email_mod_strings as $k => $v) {
435                         $v = str_replace("'", "\'", $v);
436                         $modStrings .= "mod_strings.{$k} = '{$v}';\n";
437                 }
438                 $lang .= "\n\n{$modStrings}\n";
439
440                 //Grab the Inboundemail language pack
441                 $ieModStrings = "var ie_mod_strings = new Object();\n";
442                 $ie_mod_strings = return_module_language($current_language,'InboundEmail');
443                 foreach($ie_mod_strings as $k => $v) {
444                         $v = str_replace("'", "\'", $v);
445                         $ieModStrings .= "ie_mod_strings.{$k} = '{$v}';\n";
446                 }
447                 $lang .= "\n\n{$ieModStrings}\n";
448
449                 $this->smarty->assign('linkBeans', $linkBeans);
450         $this->smarty->assign('linkBeansOptions', $parent_types);
451         $this->smarty->assign('tinyMCE', $tinyConf);
452         $this->smarty->assign('lang', $lang);
453         $this->smarty->assign('app_strings', $app_strings);
454                 $this->smarty->assign('mod_strings', $email_mod_strings);
455         $ie1 = new InboundEmail();
456
457         //Signatures
458         $defsigID = $current_user->getPreference('signature_default');
459                 $defaultSignature = $current_user->getDefaultSignature();
460                 $sigJson = !empty($defaultSignature) ? json_encode(array($defaultSignature['id'] => from_html($defaultSignature['signature_html']))) : "new Object()";
461                 $this->smarty->assign('defaultSignature', $sigJson);
462                 $this->smarty->assign('signatureDefaultId', (isset($defaultSignature['id'])) ? $defaultSignature['id'] : "");
463                 //User Preferences
464                 $this->smarty->assign('userPrefs', json_encode($this->getUserPrefsJS()));
465
466                 //Get the users default outbound id
467                 $defaultOutID = $ie1->getUsersDefaultOutboundServerId($current_user);
468                 $this->smarty->assign('defaultOutID', $defaultOutID);
469
470                 //Character Set
471                 $charsets = json_encode($locale->getCharsetSelect());
472                 $this->smarty->assign('emailCharsets', $charsets);
473
474                 //Relateable List of People for address book search
475                 //#20776 jchi
476                 $peopleTables = array("users",
477                                       "contacts",
478                                       "leads",
479                                       "prospects",
480                                       "accounts");
481                 $filterPeopleTables = array();
482                 global $app_list_strings, $app_strings;
483                 $filterPeopleTables['LBL_DROPDOWN_LIST_ALL'] = $app_strings['LBL_DROPDOWN_LIST_ALL'];
484                 foreach($peopleTables as $table) {
485                         $module = ucfirst($table);
486             $class = substr($module, 0, strlen($module) - 1);
487             require_once("modules/{$module}/{$class}.php");
488             $person = new $class();
489
490             if (!$person->ACLAccess('list')) continue;
491             $filterPeopleTables[$person->table_name] = $app_list_strings['moduleList'][$person->module_dir];
492                 }
493                 $this->smarty->assign('listOfPersons' , get_select_options_with_id($filterPeopleTables,''));
494
495         }
496
497
498
499         ////    END CORE
500         ///////////////////////////////////////////////////////////////////////////
501
502         ///////////////////////////////////////////////////////////////////////////
503         ////    ADDRESS BOOK
504         /**
505          * Retrieves all relationship metadata for a user's address book
506          * @return array
507          */
508         function getContacts() {
509                 global $current_user;
510
511                 $q = "SELECT * FROM address_book WHERE assigned_user_id = '{$current_user->id}' ORDER BY bean DESC";
512                 $r = $this->db->query($q);
513
514                 $ret = array();
515
516                 while($a = $this->db->fetchByAssoc($r)) {
517                         $ret[$a['bean_id']] = array(
518                                 'id'            => $a['bean_id'],
519                                 'module'        => $a['bean'],
520                         );
521                 }
522
523                 return $ret;
524         }
525
526         /**
527          * Saves changes to a user's address book
528          * @param array contacts
529          */
530         function setContacts($contacts) {
531                 global $current_user;
532
533                 $oldContacts = $this->getContacts();
534
535                 foreach($contacts as $cid => $contact) {
536                         if(!in_array($contact['id'], $oldContacts)) {
537                                 $q = "INSERT INTO address_book (assigned_user_id, bean, bean_id) VALUES ('{$current_user->id}', '{$contact['module']}', '{$contact['id']}')";
538                                 $r = $this->db->query($q, true);
539                         }
540                 }
541         }
542
543         /**
544          * Removes contacts from the user's address book
545          * @param array ids
546          */
547         function removeContacts($ids) {
548                 global $current_user;
549
550                 $concat = "";
551
552                 foreach($ids as $id) {
553                         if(!empty($concat))
554                                 $concat .= ", ";
555
556                         $concat .= "'{$id}'";
557                 }
558
559                 $q = "DELETE FROM address_book WHERE assigned_user_id = '{$current_user->id}' AND bean_id IN ({$concat})";
560                 $r = $this->db->query($q);
561         }
562
563         /**
564          * saves editted Contact info
565          * @param string $str JSON serialized object
566          */
567         function saveContactEdit($str) {
568
569                 $json = getJSONobj();
570
571                 $str = from_html($str);
572                 $obj = $json->decode($str);
573
574                 $contact = new Contact();
575                 $contact->retrieve($obj['contact_id']);
576                 $contact->first_name = $obj['contact_first_name'];
577                 $contact->last_name = $obj['contact_last_name'];
578                 $contact->save();
579
580                 // handle email address changes
581                 $addresses = array();
582
583                 foreach($obj as $k => $req) {
584                         if(strpos($k, 'emailAddress') !== false) {
585                                 $addresses[$k] = $req;
586                         }
587                 }
588
589                 // prefill some REQUEST vars for emailAddress save
590                 $_REQUEST['emailAddressOptOutFlag'] = $obj['optOut'];
591                 $_REQUEST['emailAddressInvalidFlag'] = $obj['invalid'];
592                 $contact->emailAddress->save($obj['contact_id'], 'Contacts', $addresses, $obj['primary'], '');
593         }
594
595         /**
596          * Prepares the Edit Contact mini-form via template assignment
597          * @param string id ID of contact in question
598          * @param string module Module in focus
599          * @return array
600          */
601         function getEditContact($id, $module) {
602                 global $app_strings;
603
604
605                 if(!class_exists("Contact")) {
606
607                 }
608
609                 $contact = new Contact();
610                 $contact->retrieve($_REQUEST['id']);
611                 $ret = array();
612
613                 if($contact->ACLAccess('edit')) {
614                         $contactMeta = array();
615                         $contactMeta['id'] = $contact->id;
616                         $contactMeta['module'] = $contact->module_dir;
617                         $contactMeta['first_name'] = $contact->first_name;
618                         $contactMeta['last_name'] = $contact->last_name;
619
620                         $this->smarty->assign("app_strings", $app_strings);
621                         $this->smarty->assign("contact_strings", return_module_language($_SESSION['authenticated_user_language'], 'Contacts'));
622                         $this->smarty->assign("contact", $contactMeta);
623
624                         $ea = new SugarEmailAddress();
625                         $newEmail = $ea->getEmailAddressWidgetEditView($id, $module, true);
626                         $this->smarty->assign("emailWidget", $newEmail['html']);
627
628                         $ret['form'] = $this->smarty->fetch("modules/Emails/templates/editContact.tpl");
629                         $ret['prefillData'] = $newEmail['prefillData'];
630                 } else {
631                         $id = "";
632                         $ret['form'] = $app_strings['LBL_EMAIL_ERROR_NO_ACCESS'];
633                         $ret['prefillData'] = '{}';
634                 }
635
636                 $ret['id'] = $id;
637                 $ret['contactName'] = $contact->full_name;
638
639                 return $ret;
640         }
641
642
643         /**
644          * Retrieves a concatenated list of contacts, those with assigned_user_id = user's id and those in the address_book
645          * table
646          * @param array $contacts Array of contact types -> IDs
647          * @param object $user User in focus
648          * @return array
649          */
650         function getUserContacts($contacts, $user=null) {
651
652                 global $current_user;
653                 global $locale;
654
655                 if(empty($user)) {
656                         $user = $current_user;
657                 }
658
659                 $emailAddress = new SugarEmailAddress();
660                 $ret = array();
661
662                 $union = '';
663
664                 $modules = array();
665                 foreach($contacts as $contact) {
666                         if(!isset($modules[$contact['module']])) {
667                                 $modules[$contact['module']] = array();
668                         }
669                         $modules[$contact['module']][] = $contact;
670                 }
671
672                 foreach($modules as $module => $contacts) {
673                         if(!empty($union)) {
674                                 $union .= " UNION ALL ";
675                         }
676
677                         $table = strtolower($module);
678                         $idsSerial = '';
679
680                         foreach($contacts as $contact) {
681                                 if(!empty($idsSerial)) {
682                                         $idsSerial .= ",";
683                                 }
684                                 $idsSerial .= "'{$contact['id']}'";
685                         }
686
687                         $union .= "(SELECT id, first_name, last_name, title, '{$module}' module FROM {$table} WHERE id IN({$idsSerial}) AND deleted = 0 )";
688                 }
689                 if(!empty($union)) {
690                         $union .= " ORDER BY last_name";
691                 }
692
693                 $r = $user->db->query($union);
694
695                 //_pp($union);
696
697                 while($a = $user->db->fetchByAssoc($r)) {
698                         $c = array();
699
700                         $c['name'] = $locale->getLocaleFormattedName($a['first_name'], "<b>{$a['last_name']}</b>", '', $a['title'], '', $user);
701                         $c['id'] = $a['id'];
702                         $c['module'] = $a['module'];
703                         $c['email'] = $emailAddress->getAddressesByGUID($a['id'], $a['module']);
704                         $ret[$a['id']] = $c;
705                 }
706
707                 return $ret;
708         }
709         ////    END ADDRESS BOOK
710         ///////////////////////////////////////////////////////////////////////////
711
712
713         ///////////////////////////////////////////////////////////////////////////
714         ////    EMAIL 2.0 Preferences
715         function getUserPrefsJS() {
716                 global $current_user;
717                 global $locale;
718
719                 // sort order per mailbox view
720                 $sortSerial = $current_user->getPreference('folderSortOrder', 'Emails');
721                 $sortArray = array();
722                 if(!empty($sortSerial)) {
723                         $sortArray = unserialize($sortSerial);
724                 }
725
726                 // treeview collapsed/open states
727                 $folderStateSerial = $current_user->getPreference('folderOpenState', 'Emails');
728                 $folderStates = array();
729                 if(!empty($folderStateSerial)) {
730                         $folderStates = unserialize($folderStateSerial);
731                 }
732
733                 // subscribed accounts
734                 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
735
736                 // general settings
737                 $emailSettings = $current_user->getPreference('emailSettings', 'Emails');
738
739                 if(empty($emailSettings)) {
740                         $emailSettings = array();
741                         $emailSettings['emailCheckInterval'] = -1;
742                         $emailSettings['autoImport'] = '';
743                         $emailSettings['alwaysSaveOutbound'] = '1';
744                         $emailSettings['sendPlainText'] = '';
745                         $emailSettings['defaultOutboundCharset'] = $GLOBALS['sugar_config']['default_email_charset'];
746                         $emailSettings['showNumInList'] = 20;
747                 }
748
749                 // focus folder
750                 $focusFolder = $current_user->getPreference('focusFolder', 'Emails');
751                 $focusFolder = !empty($focusFolder) ? unserialize($focusFolder) : array();
752
753                 // unread only flag
754                 $showUnreadOnly = $current_user->getPreference('showUnreadOnly', 'Emails');
755
756                 $listViewSort = array(
757                         "sortBy" => 'date',
758                         "sortDirection" => 'DESC',
759                 );
760
761                 // signature prefs
762                 $signaturePrepend = $current_user->getPreference('signature_prepend') ? 'true' : 'false';
763                 $signatureDefault = $current_user->getPreference('signature_default');
764                 $signatures = array(
765                         'signature_prepend' => $signaturePrepend,
766                         'signature_default' => $signatureDefault
767                 );
768
769
770                 // current_user
771                 $user = array(
772                         'emailAddresses' => $current_user->emailAddress->getAddressesByGUID($current_user->id, 'Users'),
773                         'full_name' => from_html($current_user->full_name),
774                 );
775
776                 $userPreferences = array();
777                 $userPreferences['sort'] = $sortArray;
778                 $userPreferences['folderStates'] = $folderStates;
779                 $userPreferences['showFolders'] = $showFolders;
780                 $userPreferences['emailSettings'] = $emailSettings;
781                 $userPreferences['focusFolder'] = $focusFolder;
782                 $userPreferences['showUnreadOnly'] = $showUnreadOnly;
783                 $userPreferences['listViewSort'] = $listViewSort;
784                 $userPreferences['signatures'] = $signatures;
785                 $userPreferences['current_user'] = $user;
786                 return $userPreferences;
787         }
788
789
790
791         ///////////////////////////////////////////////////////////////////////////
792         ////    FOLDER FUNCTIONS
793
794         /**
795          * Creates a new Sugar folder
796          * @param string $nodeLabel New sugar folder name
797          * @param string $parentLabel Parent folder name
798          */
799         function saveNewFolder($nodeLabel, $parentId, $isGroup=0) {
800                 global $current_user;
801
802                 $this->folder->name = $nodeLabel;
803                 $this->folder->is_group = $isGroup;
804                 $this->folder->parent_folder = ($parentId == 'Home') ? "" : $parentId;
805                 $this->folder->has_child = 0;
806                 $this->folder->created_by = $current_user->id;
807                 $this->folder->modified_by = $current_user->id;
808                 $this->folder->date_modified = $this->folder->date_created = TimeDate::getInstance()->nowDb();
809
810                 $this->folder->save();
811                 return array(
812                         'action' => 'newFolderSave',
813                         'id' => $this->folder->id,
814                         'name' => $this->folder->name,
815                         'is_group' => $this->folder->is_group,
816                         'is_dynamic' => $this->folder->is_dynamic
817                 );
818         }
819
820         /**
821          * Saves user sort prefernces
822          */
823         function saveListViewSortOrder($ieId, $focusFolder, $sortBy, $sortDir) {
824                 global $current_user;
825
826                 $sortArray = array();
827
828                 $sortSerial = $current_user->getPreference('folderSortOrder', 'Emails');
829                 if(!empty($sortSerial)) {
830                         $sortArray = unserialize($sortSerial);
831                 }
832
833                 $sortArray[$ieId][$focusFolder]['current']['sort'] = $sortBy;
834                 $sortArray[$ieId][$focusFolder]['current']['direction'] = $sortDir;
835                 $sortSerial = serialize($sortArray);
836                 $current_user->setPreference('folderSortOrder', $sortSerial, '', 'Emails');
837         }
838
839         /**
840          * Stickies folder collapse/open state
841          */
842         function saveFolderOpenState($focusFolder, $focusFolderOpen) {
843                 global $current_user;
844
845                 $folderStateSerial = $current_user->getPreference('folderOpenState', 'Emails');
846                 $folderStates = array();
847
848                 if(!empty($folderStateSerial)) {
849                         $folderStates = unserialize($folderStateSerial);
850                 }
851
852                 $folderStates[$focusFolder] = $focusFolderOpen;
853                 $newFolderStateSerial = serialize($folderStates);
854                 $current_user->setPreference('folderOpenState', $newFolderStateSerial, '', 'Emails');
855         }
856
857         /**
858          * saves a folder's view state
859          */
860         function saveListView($ieId, $folder) {
861                 global $current_user;
862
863                 $saveState = array();
864                 $saveState['ieId'] = $ieId;
865                 $saveState['folder'] = $folder;
866                 $saveStateSerial = serialize($saveState);
867                 $current_user->setPreference('focusFolder', $saveStateSerial, '', 'Emails');
868         }
869
870         /**
871          * Generates cache folder structure
872          */
873         function preflightEmailCache($cacheRoot) {
874                 // base
875                 if(!file_exists($cacheRoot))
876                         mkdir_recursive(clean_path($cacheRoot));
877
878                 // folders
879                 if(!file_exists($cacheRoot."/folders"))
880                         mkdir_recursive(clean_path("{$cacheRoot}/folders"));
881
882                 // messages
883                 if(!file_exists($cacheRoot."/messages"))
884                         mkdir_recursive(clean_path("{$cacheRoot}/messages"));
885
886                 // attachments
887                 if(!file_exists($cacheRoot."/attachments"))
888                         mkdir_recursive(clean_path("{$cacheRoot}/attachments"));
889         }
890
891         function deleteEmailCacheForFolders($cacheRoot) {
892                 $filePath = $cacheRoot."/folders/folders.php";
893                 if (file_exists($filePath)) {
894                         unlink($filePath);
895                 }
896         }
897         ///////////////////////////////////////////////////////////////////////////
898         ////    IMAP FUNCTIONS
899         /**
900          * Identifies subscribed mailboxes and empties the trash
901          * @param object $ie InboundEmail
902          */
903         function emptyTrash(&$ie) {
904                 global $current_user;
905
906                 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
907
908                 if(is_array($showFolders)) {
909                         foreach($showFolders as $ieId) {
910                                 if(!empty($ieId)) {
911                                         $ie->retrieve($ieId);
912                                         $ie->emptyTrash();
913                                 }
914                         }
915                 }
916         }
917
918         /**
919          * returns an array of nodes that correspond to IMAP mailboxes.
920          * @param bool $forceRefresh
921          * @return object TreeView object
922          */
923         function getMailboxNodes() {
924                 global $sugar_config;
925                 global $current_user;
926                 global $app_strings;
927
928                 $tree = new Tree("frameFolders");
929                 $tree->tree_style= 'include/ytree/TreeView/css/check/tree.css';
930
931                 $nodes = array();
932                 $ie = new InboundEmail();
933                 $refreshOffset = $this->cacheTimeouts['folders']; // 5 mins.  this will be set via user prefs
934
935                 $rootNode = new ExtNode($app_strings['LBL_EMAIL_HOME_FOLDER'], $app_strings['LBL_EMAIL_HOME_FOLDER']);
936                 $rootNode->dynamicloadfunction = '';
937                 $rootNode->expanded = true;
938                 $rootNode->dynamic_load = true;
939                 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
940
941                 if(empty($showFolders)) {
942                         $showFolders = array();
943                 }
944
945                 // INBOX NODES
946                 if($current_user->hasPersonalEmail()) {
947                         $personals = $ie->retrieveByGroupId($current_user->id);
948
949                         foreach($personals as $k => $personalAccount) {
950                                 if(in_array($personalAccount->id, $showFolders)) {
951                                         // check for cache value
952                                         $cacheRoot = "{$sugar_config['cache_dir']}modules/Emails/{$personalAccount->id}";
953                                         $this->preflightEmailCache($cacheRoot);
954
955                                         if($this->validCacheFileExists($personalAccount->id, 'folders', "folders.php")) {
956                                                 $mailboxes = $this->getMailBoxesFromCacheValue($personalAccount);
957                                         } else {
958                                                 $mailboxes = $personalAccount->getMailboxes();
959                                         }
960
961                                         $acctNode = new ExtNode('Home::' . $personalAccount->name, $personalAccount->name);
962                                         $acctNode->dynamicloadfunction = '';
963                                         $acctNode->expanded = false;
964                                         $acctNode->set_property('cls', 'ieFolder');
965                                         $acctNode->set_property('ieId', $personalAccount->id);
966                                 $acctNode->set_property('protocol', $personalAccount->protocol);
967
968                                         if(array_key_exists('Home::'.$personalAccount->name, $this->folderStates)) {
969                                                 if($this->folderStates['Home::'.$personalAccount->name] == 'open') {
970                                                         $acctNode->expanded = true;
971                                                 }
972                                         }
973                                         $acctNode->dynamic_load = true;
974
975                                         $nodePath = $acctNode->_properties['id'];
976
977                                         foreach($mailboxes as $k => $mbox) {
978                                                 $acctNode->add_node($this->buildTreeNode($k, $k, $mbox, $personalAccount->id,
979                                                     $nodePath, false, $personalAccount));
980                                         }
981
982                                         $rootNode->add_node($acctNode);
983                                 }
984                         }
985                 }
986
987                 // GROUP INBOX NODES
988                 $beans = $ie->retrieveAllByGroupId($current_user->id, false);
989                 foreach($beans as $k => $groupAccount) {
990                         if(in_array($groupAccount->id, $showFolders)) {
991                                 // check for cache value
992                                 $cacheRoot = "{$sugar_config['cache_dir']}modules/Emails/{$groupAccount->id}";
993                                 $this->preflightEmailCache($cacheRoot);
994                                 //$groupAccount->connectMailserver();
995
996                                 if($this->validCacheFileExists($groupAccount->id, 'folders', "folders.php")) {
997                                         $mailboxes = $this->getMailBoxesFromCacheValue($groupAccount);
998                                 } else {
999                                         $mailboxes = $groupAccount->getMailBoxesForGroupAccount();
1000                                 }
1001
1002                                 $acctNode = new ExtNode($groupAccount->name, "group.{$groupAccount->name}");
1003                                 $acctNode->dynamicloadfunction = '';
1004                                 $acctNode->expanded = false;
1005                         $acctNode->set_property('isGroup', 'true');
1006                         $acctNode->set_property('ieId', $groupAccount->id);
1007                         $acctNode->set_property('protocol', $groupAccount->protocol);
1008
1009                                 if(array_key_exists('Home::'.$groupAccount->name, $this->folderStates)) {
1010                                         if($this->folderStates['Home::'.$groupAccount->name] == 'open') {
1011                                                 $acctNode->expanded = true;
1012                                         }
1013                                 }
1014                                 $acctNode->dynamic_load = true;
1015                                 $nodePath = $rootNode->_properties['id']."::".$acctNode->_properties['id'];
1016
1017                                 foreach($mailboxes as $k => $mbox) {
1018                                         $acctNode->add_node($this->buildTreeNode($k, $k, $mbox, $groupAccount->id,
1019                                            $nodePath, true, $groupAccount));
1020                                 }
1021
1022                                 $rootNode->add_node($acctNode);
1023                         }
1024                 }
1025
1026                 // SugarFolder nodes
1027                 /* SugarFolders are built at onload when the UI renders */
1028
1029                 $tree->add_node($rootNode);
1030                 return $tree;
1031         }
1032
1033         function getMailBoxesFromCacheValue($mailAccount) {
1034                 $foldersCache = $this->getCacheValue($mailAccount->id, 'folders', "folders.php", 'foldersCache');
1035                 $mailboxes = $foldersCache['mailboxes'];
1036                 $mailboxesArray = $mailAccount->generateFlatArrayFromMultiDimArray($mailboxes, $mailAccount->retrieveDelimiter());
1037                 $mailAccount->saveMailBoxFolders($mailboxesArray);
1038                 $this->deleteEmailCacheForFolders($cacheRoot);
1039                 return $mailboxes;
1040         } // fn
1041
1042         /**
1043          * Builds up a TreeView Node object
1044          * @param mixed
1045          * @param mixed
1046          * @param string
1047          * @param string ID of InboundEmail instance
1048          * @param string nodePath Serialized path from root node to current node
1049          * @param bool isGroup
1050          * @param bool forceRefresh
1051          * @return mixed
1052          */
1053         function buildTreeNode($key, $label, $mbox, $ieId, $nodePath, $isGroup, $ie) {
1054                 global $sugar_config;
1055
1056                 // get unread counts
1057                 $exMbox = explode("::", $nodePath);
1058                 $unseen = 0;
1059                 $GLOBALS['log']->debug("$key --- $nodePath::$label");
1060
1061                 if(count($exMbox) >= 2) {
1062                         $mailbox = "";
1063                         for($i=2; $i<count($exMbox); $i++) {
1064                                 if($mailbox != "") {
1065                                         $mailbox .= ".";
1066                                 }
1067                                 $mailbox .= "{$exMbox[$i]}";
1068                         }
1069
1070                     $mailbox = substr($key, strpos($key, '.'));
1071
1072                         $unseen = $this->getUnreadCount($ie, $mailbox);
1073
1074                         if($unseen > 0) {
1075                                 //$label = " <span id='span{$ie->id}{$ie->mailbox}' style='font-weight:bold'>{$label} (<span id='span{$ie->id}{$ie->mailbox}nums'>{$unseen}</span>)</span>";
1076                         }
1077                 }
1078
1079                 $nodePath = $nodePath."::".$label;
1080         $node = new ExtNode($nodePath, $label);
1081         $node->dynamicloadfunction = '';
1082         $node->expanded = false;
1083         $node->set_property('labelStyle', "remoteFolder");
1084
1085
1086         if(array_key_exists($nodePath, $this->folderStates)) {
1087                 if($this->folderStates[$nodePath] == 'open') {
1088                         $node->expanded = true;
1089                 }
1090         }
1091
1092                 $group = ($isGroup) ? 'true' : 'false';
1093         $node->dynamic_load = true;
1094         //$node->set_property('href', " SUGAR.email2.listView.populateListFrame(YAHOO.namespace('frameFolders').selectednode, '{$ieId}', 'false');");
1095         $node->set_property('isGroup', $group);
1096         $node->set_property('isDynamic', 'false');
1097         $node->set_property('ieId', $ieId);
1098         $node->set_property('mbox', $key);
1099         $node->set_property('unseen', $unseen);
1100         $node->set_property('cls', 'ieFolder');
1101
1102         if(is_array($mbox)) {
1103                 foreach($mbox as $k => $v) {
1104                         $node->add_node($this->buildTreeNode("$key.$k", $k, $v, $ieId, $nodePath, $isGroup, $ie));
1105                 }
1106         }
1107
1108         return $node;
1109         }
1110
1111         /**
1112          * Totals the unread emails
1113          */
1114         function getUnreadCount(&$ie, $mailbox) {
1115                 global $sugar_config;
1116                 $unseen = 0;
1117
1118                 // use cache
1119                 return $ie->getCacheUnreadCount($mailbox);
1120         }
1121
1122         ///////////////////////////////////////////////////////////////////////////
1123         ////    DISPLAY CODE
1124         /**
1125          * Used exclusively by draft code.  Returns Notes and Documents as attachments.
1126          * @param array $ret
1127          * @return array
1128          */
1129         function getDraftAttachments($ret) {
1130                 global $db;
1131
1132                 // $ret['uid'] is the draft Email object's GUID
1133                 $ret['attachments'] = array();
1134
1135                 $q = "SELECT id, filename FROM notes WHERE parent_id = '{$ret['uid']}' AND deleted = 0";
1136                 $r = $db->query($q);
1137
1138                 while($a = $db->fetchByAssoc($r)) {
1139                         $ret['attachments'][$a['id']] = array(
1140                                 'id'            => $a['id'],
1141                                 'filename'      => $a['filename'],
1142                         );
1143                 }
1144
1145                 return $ret;
1146         }
1147
1148         function createCopyOfInboundAttachment($ie, $ret, $uid) {
1149                 global $sugar_config;
1150                 if ($ie->isPop3Protocol()) {
1151                         // get the UIDL from database;
1152                         $cachedUIDL = md5($uid);
1153                         $cache = "{$sugar_config['cache_dir']}modules/Emails/{$ie->id}/messages/{$ie->mailbox}{$cachedUIDL}.php";
1154                 } else {
1155                         $cache = "{$sugar_config['cache_dir']}modules/Emails/{$ie->id}/messages/{$ie->mailbox}{$uid}.php";
1156                 }
1157                 if(file_exists($cache)) {
1158                         include($cache); // profides $cacheFile
1159                         $metaOut = unserialize($cacheFile['out']);
1160                         $meta = $metaOut['meta']['email'];
1161                         if (isset($meta['attachments'])) {
1162                                 $attachmentHtmlData = $meta['attachments'];
1163                                 $actualAttachmentInfo = array();
1164                                 $this->parseAttachmentInfo($actualAttachmentInfo, $attachmentHtmlData);
1165                                 if (sizeof($actualAttachmentInfo) > 0) {
1166                                         foreach($actualAttachmentInfo as $key => $value) {
1167                                                 $attachmentid;
1168                                                 $fileName;
1169                                                 $datasplit = explode("&", $value);
1170                                                 $attachmentIdArray = explode("=", $datasplit[0]);
1171                                                 $attachmentid = $attachmentIdArray[1];
1172
1173                                                 $fileNameArray = explode("=", $datasplit[4]);
1174                                                 $fileName = $fileNameArray[1];
1175                                                 $guid = create_guid();
1176                                                 //$destination = clean_path("{$this->userCacheDir}/{$guid}{$fileName}");
1177                                                 $destination = clean_path("{$this->userCacheDir}/{$guid}");
1178
1179                                                 $attachmentFilePath = "{$sugar_config['cache_dir']}modules/Emails/{$ie->id}/attachments/{$attachmentid}";
1180                                                 copy($attachmentFilePath, $destination);
1181                                                 $ret['attachments'][$guid] = array();
1182                                                 $ret['attachments'][$guid]['id'] = $guid . $fileName;
1183                                                 $ret['attachments'][$guid]['filename'] = $fileName;
1184                                         } // for
1185                                 } // if
1186                         } // if
1187
1188                 } // if
1189                 return $ret;
1190
1191         } // fn
1192
1193         function parseAttachmentInfo(&$actualAttachmentInfo, $attachmentHtmlData) {
1194                 $downLoadPHP = strpos($attachmentHtmlData, "index.php?entryPoint=download&");
1195                 while ($downLoadPHP) {
1196                         $attachmentHtmlData = substr($attachmentHtmlData, $downLoadPHP+30);
1197                         $final = strpos($attachmentHtmlData, "\">");
1198                         $actualAttachmentInfo[] = substr($attachmentHtmlData, 0, $final);
1199                         $attachmentHtmlData = substr($attachmentHtmlData, $final);
1200                         $downLoadPHP = strpos($attachmentHtmlData, "index.php?entryPoint=download&");
1201                 } // while
1202         }
1203         /**
1204          * Renders the QuickCreate form from Smarty and returns HTML
1205          * @param array $vars request variable global
1206          * @param object $email Fetched email object
1207          * @param bool $addToAddressBook
1208          * @return array
1209          */
1210         function getQuickCreateForm($vars, $email, $addToAddressBookButton=false) {
1211                 require_once("include/EditView/EditView2.php");
1212                 global $app_strings;
1213                 global $mod_strings;
1214                 global $current_user;
1215                 global $beanList;
1216                 global $beanFiles;
1217                 global $current_language;
1218
1219                 //Setup the current module languge
1220                 $mod_strings = return_module_language($current_language, $_REQUEST['qc_module']);
1221
1222                 $bean = $beanList[$_REQUEST['qc_module']];
1223                 $class = $beanFiles[$bean];
1224                 require_once($class);
1225
1226                 $focus = new $bean();
1227
1228                 $people = array(
1229                 'Contact'
1230                 ,'Lead'
1231                 );
1232                 $emailAddress = array();
1233
1234                 // people
1235                 if(in_array($bean, $people)) {
1236                         // lead specific
1237                         $focus->lead_source = 'Email';
1238                         $focus->lead_source_description = trim($email->name);
1239
1240                         $from = (isset($email->from_name) && !empty($email->from_name)) ? $email->from_name : $email->from_addr;
1241
1242                         if(isset($_REQUEST['sugarEmail']) && !empty($_REQUEST['sugarEmail']))
1243                 $from = (isset($email->from_name) && !empty($email->from_name)) ? $email->from_name : $email->from_addr_name;
1244
1245
1246                         $name = explode(" ", trim($from));
1247
1248                         $address = trim(array_pop($name));
1249                         $address = str_replace(array("<",">","&lt;","&gt;"), "", $address);
1250
1251                         $emailAddress[] = array(
1252                                 'email_address'         => $address,
1253                                 'primary_address'       => 1,
1254                                 'invalid_email'         => 0,
1255                                 'opt_out'                       => 0,
1256                                 'reply_to_address'      => 1
1257                         );
1258
1259                         $focus->email1 = $address;
1260
1261                         if(!empty($name)) {
1262                                 $focus->last_name = trim(array_pop($name));
1263
1264                                 foreach($name as $first) {
1265                                         if(!empty($focus->first_name)) {
1266                                                 $focus->first_name .= " ";
1267                                         }
1268                                         $focus->first_name .= trim($first);
1269                                 }
1270                         }
1271                 } else {
1272                         // bugs, cases, tasks
1273                         $focus->name = trim($email->name);
1274                 }
1275
1276                 $focus->description = trim(strip_tags($email->description));
1277                 $focus->assigned_user_id = $current_user->id;
1278
1279
1280                 $EditView = new EditView();
1281                 $EditView->ss = new Sugar_Smarty();
1282                 //MFH BUG#20283 - checks for custom quickcreate fields
1283                 $EditView->setup($_REQUEST['qc_module'], $focus, 'custom/modules/'.$focus->module_dir.'/metadata/editviewdefs.php', 'include/EditView/EditView.tpl');
1284                 $EditView->process();
1285                 $EditView->render();
1286
1287                 $EditView->defs['templateMeta']['form']['buttons'] = array(
1288                         'email2save' => array(
1289                                 'id' => 'e2AjaxSave',
1290                                 'customCode' => '<input type="button" class="button" value="   '.$app_strings['LBL_SAVE_BUTTON_LABEL']
1291                                               . '   " onclick="SUGAR.email2.detailView.saveQuickCreate(false);" />'
1292                         ),
1293                         'email2saveandreply' => array(
1294                             'id' => 'e2SaveAndReply',
1295                             'customCode' => '<input type="button" class="button" value="   '.$app_strings['LBL_EMAIL_SAVE_AND_REPLY']
1296                                           . '   " onclick="SUGAR.email2.detailView.saveQuickCreate(\'reply\');" />'
1297                         ),
1298                         'email2cancel' => array(
1299                              'id' => 'e2cancel',
1300                              'customCode' => '<input type="button" class="button" value="   '.$app_strings['LBL_EMAIL_CANCEL']
1301                               . '   " onclick="SUGAR.email2.detailView.quickCreateDialog.hide();" />'
1302                         )
1303                 );
1304
1305
1306                 if($addToAddressBookButton) {
1307                         $EditView->defs['templateMeta']['form']['buttons']['email2saveAddToAddressBook'] = array(
1308                                 'id' => 'e2addToAddressBook',
1309                                 'customCode' => '<input type="button" class="button" value="   '.$app_strings['LBL_EMAIL_ADDRESS_BOOK_SAVE_AND_ADD']
1310                                               . '   " onclick="SUGAR.email2.detailView.saveQuickCreate(true);" />'
1311                         );
1312                 }
1313
1314                 //Get the module language for javascript
1315             if(!is_file($GLOBALS['sugar_config']['cache_dir'] . 'jsLanguage/' . $_REQUEST['qc_module'] . '/' . $GLOBALS['current_language'] . '.js')) {
1316             require_once('include/language/jsLanguage.php');
1317             jsLanguage::createModuleStringsCache($_REQUEST['qc_module'], $GLOBALS['current_language']);
1318         }
1319                 $jsLanguage = '<script type="text/javascript" src="' . $GLOBALS['sugar_config']['cache_dir'] . 'jsLanguage/'
1320                             . $_REQUEST['qc_module'] . '/' . $GLOBALS['current_language'] . '.js?s=' . $GLOBALS['sugar_version'] . '&c='
1321                             . $GLOBALS['sugar_config']['js_custom_version'] . '&j=' . $GLOBALS['sugar_config']['js_lang_version'] . '"></script>';
1322
1323
1324
1325                 $EditView->view = 'EmailQCView';
1326                 $EditView->defs['templateMeta']['form']['headerTpl'] = 'include/EditView/header.tpl';
1327                 $EditView->defs['templateMeta']['form']['footerTpl'] = 'include/EditView/footer.tpl';
1328                 $meta = array();
1329                 $meta['html'] = $jsLanguage . $EditView->display(false, true);
1330                 $meta['html'] = str_replace("src='include/SugarEmailAddress/SugarEmailAddress.js?s={$GLOBALS['js_version_key']}&c={$GLOBALS['sugar_config']['js_custom_version']}'", '', $meta['html']);
1331                 $meta['emailAddress'] = $emailAddress;
1332
1333                 $mod_strings = return_module_language($current_language, 'Emails');
1334
1335                 return $meta;
1336         }
1337
1338         /**
1339      * Renders the Import form from Smarty and returns HTML
1340      * @param array $vars request variable global
1341      * @param object $email Fetched email object
1342      * @param bool $addToAddressBook
1343      * @return array
1344      */
1345     function getImportForm($vars, $email, $formName = 'ImportEditView') {
1346                 require_once("include/EditView/EditView2.php");
1347         require_once("include/TemplateHandler/TemplateHandler.php");
1348                 require_once('include/QuickSearchDefaults.php');
1349                 $qsd = new QuickSearchDefaults();
1350                 $qsd->setFormName($formName);
1351
1352         global $app_strings;
1353         global $current_user;
1354         global $app_list_strings;
1355                 $sqs_objects = array(
1356                                      "{$formName}_parent_name" => $qsd->getQSParent(),
1357                 );
1358         $smarty = new Sugar_Smarty();
1359         $smarty->assign("APP",$app_strings);
1360         $smarty->assign('formName',$formName);
1361         $showAssignTo = false;
1362         if (!isset($vars['showAssignTo']) || $vars['showAssignTo'] == true) {
1363                 $showAssignTo = true;
1364                 } // if
1365                 if ($showAssignTo) {
1366                 if(empty($email->assigned_user_id) && empty($email->id))
1367                     $email->assigned_user_id = $current_user->id;
1368                 if(empty($email->assigned_name) && empty($email->id))
1369                     $email->assigned_user_name = $current_user->user_name;
1370                 $sqs_objects["{$formName}_assigned_user_name"] = $qsd->getQSUser();
1371                 }
1372                 $smarty->assign("showAssignedTo",$showAssignTo);
1373
1374         $showDelete = false;
1375         if (!isset($vars['showDelete']) || $vars['showDelete'] == true) {
1376             $showDelete = true;
1377         }
1378         $smarty->assign("showDelete",$showDelete);
1379
1380         $smarty->assign("userId",$email->assigned_user_id);
1381         $smarty->assign("userName",$email->assigned_user_name);
1382         $parent_types = $app_list_strings['record_type_display'];
1383         $smarty->assign('parentOptions', get_select_options_with_id($parent_types, $email->parent_type));
1384
1385                 $quicksearch_js = '<script type="text/javascript" language="javascript">sqs_objects = ' . json_encode($sqs_objects) . '</script>';
1386         $smarty->assign('SQS', $quicksearch_js);
1387
1388         $meta = array();
1389         $meta['html'] = $smarty->fetch("modules/Emails/templates/importRelate.tpl");
1390         return $meta;
1391     }
1392
1393     /**
1394      * This function returns the detail view for email in new 2.0 interface
1395      *
1396      */
1397     function getDetailViewForEmail2($emailId) {
1398
1399                 require_once('include/DetailView/DetailView.php');
1400                 global $app_strings, $app_list_strings;
1401                 global $mod_strings;
1402
1403         $smarty = new Sugar_Smarty();
1404
1405                 // SETTING DEFAULTS
1406                 $focus          = new Email();
1407                 $focus->retrieve($emailId);
1408                 $detailView->ss = new Sugar_Smarty();
1409                 $detailView     = new DetailView();
1410                 $title = "";
1411                 $offset         = 0;
1412                 if($focus->type == 'out') {
1413                         $title = getClassicModuleTitle('Emails', array($mod_strings['LBL_SENT_MODULE_NAME'],$focus->name), true);
1414                 } elseif ($focus->type == 'draft') {
1415                         $title = getClassicModuleTitle('Emails', array($mod_strings['LBL_LIST_FORM_DRAFTS_TITLE'],$focus->name), true);
1416                 } elseif($focus->type == 'inbound') {
1417                         $title = getClassicModuleTitle('Emails', array($mod_strings['LBL_INBOUND_TITLE'],$focus->name), true);
1418                 }
1419                 $smarty->assign("emailTitle", $title);
1420
1421                 // DEFAULT TO TEXT IF NO HTML CONTENT:
1422                 $html = trim(from_html($focus->description_html));
1423                 if(empty($html)) {
1424                         $smarty->assign('SHOW_PLAINTEXT', 'true');
1425                         $description = nl2br($focus->description);
1426                 } else {
1427                         $smarty->assign('SHOW_PLAINTEXT', 'false');
1428                         $description = from_html($focus->description_html);
1429                 }
1430
1431                 //if not empty or set to test (from test campaigns)
1432                 if (!empty($focus->parent_type) && $focus->parent_type !='test') {
1433                         $smarty->assign('PARENT_MODULE', $focus->parent_type);
1434                         $smarty->assign('PARENT_TYPE', $app_list_strings['record_type_display'][$focus->parent_type] . ":");
1435                 }
1436
1437         global $gridline;
1438                 $smarty->assign('MOD', $mod_strings);
1439                 $smarty->assign('APP', $app_strings);
1440                 $smarty->assign('GRIDLINE', $gridline);
1441                 $smarty->assign('PRINT_URL', 'index.php?'.$GLOBALS['request_string']);
1442                 $smarty->assign('ID', $focus->id);
1443                 $smarty->assign('TYPE', $focus->type);
1444                 $smarty->assign('PARENT_NAME', $focus->parent_name);
1445                 $smarty->assign('PARENT_ID', $focus->parent_id);
1446                 $smarty->assign('NAME', $focus->name);
1447                 $smarty->assign('ASSIGNED_TO', $focus->assigned_user_name);
1448                 $smarty->assign('DATE_MODIFIED', $focus->date_modified);
1449                 $smarty->assign('DATE_ENTERED', $focus->date_entered);
1450                 $smarty->assign('DATE_START', $focus->date_start);
1451                 $smarty->assign('TIME_START', $focus->time_start);
1452                 $smarty->assign('FROM', $focus->from_addr);
1453                 $smarty->assign('TO', nl2br($focus->to_addrs));
1454                 $smarty->assign('CC', nl2br($focus->cc_addrs));
1455                 $smarty->assign('BCC', nl2br($focus->bcc_addrs));
1456                 $smarty->assign('CREATED_BY', $focus->created_by_name);
1457                 $smarty->assign('MODIFIED_BY', $focus->modified_by_name);
1458                 $smarty->assign('DESCRIPTION', nl2br($focus->description));
1459                 $smarty->assign('DESCRIPTION_HTML', from_html($focus->description_html));
1460                 $smarty->assign('DATE_SENT', $focus->date_entered);
1461                 $smarty->assign('EMAIL_NAME', 'RE: '.$focus->name);
1462                 $smarty->assign("TAG", $focus->listviewACLHelper());
1463                 $smarty->assign("SUGAR_VERSION", $GLOBALS['sugar_version']);
1464                 $smarty->assign("JS_CUSTOM_VERSION", $GLOBALS['sugar_config']['js_custom_version']);
1465                 if(!empty($focus->reply_to_email)) {
1466                         $replyTo = "
1467                                 <tr>
1468                         <td class=\"tabDetailViewDL\"><slot>".$mod_strings['LBL_REPLY_TO_NAME']."</slot></td>
1469                         <td colspan=3 class=\"tabDetailViewDF\"><slot>".$focus->reply_to_addr."</slot></td>
1470                         </tr>";
1471                         $smarty->assign("REPLY_TO", $replyTo);
1472                 }
1473                 ///////////////////////////////////////////////////////////////////////////////
1474                 ////    JAVASCRIPT VARS
1475                 $jsVars  = '';
1476                 $jsVars .= "var showRaw = '{$mod_strings['LBL_BUTTON_RAW_LABEL']}';";
1477                 $jsVars .= "var hideRaw = '{$mod_strings['LBL_BUTTON_RAW_LABEL_HIDE']}';";
1478                 $smarty->assign("JS_VARS", $jsVars);
1479                 ///////////////////////////////////////////////////////////////////////////////
1480                 ////    NOTES (attachements, etc.)
1481                 ///////////////////////////////////////////////////////////////////////////////
1482
1483                 $note = new Note();
1484                 $where = "notes.parent_id='{$focus->id}'";
1485                 //take in account if this is from campaign and the template id is stored in the macros.
1486
1487                 if(isset($macro_values) && isset($macro_values['email_template_id'])){
1488                     $where = "notes.parent_id='{$macro_values['email_template_id']}'";
1489                 }
1490                 $notes_list = $note->get_full_list("notes.name", $where, true);
1491
1492                 if(! isset($notes_list)) {
1493                         $notes_list = array();
1494                 }
1495
1496                 $attachments = '';
1497                 for($i=0; $i<count($notes_list); $i++) {
1498                         $the_note = $notes_list[$i];
1499                         //$attachments .= "<a href=\"".UploadFile::get_url($the_note->filename,$the_note->id)."\" target=\"_blank\">".$the_note->name.$the_note->description ."</a><br>";
1500                         $attachments .= "<a href=\"index.php?entryPoint=download&id=".$the_note->id."&type=Notes\">".$the_note->name."</a><br />";
1501                 }
1502                 $smarty->assign("ATTACHMENTS", $attachments);
1503                 ///////////////////////////////////////////////////////////////////////////////
1504                 ////    SUBPANELS
1505                 ///////////////////////////////////////////////////////////////////////////////
1506                 $show_subpanels = true;
1507                 if ($show_subpanels) {
1508                     require_once('include/SubPanel/SubPanelTiles.php');
1509                     $subpanel = new SubPanelTiles($focus, 'Emails');
1510                     $smarty->assign("SUBPANEL", $subpanel->display());
1511                 }
1512         $meta['html'] = $smarty->fetch("modules/Emails/templates/emailDetailView.tpl");
1513         return $meta;
1514
1515     } // fn
1516
1517         /**
1518          * Sets the "read" flag in the overview cache
1519          */
1520         function setReadFlag($ieId, $mbox, $uid) {
1521                 $this->markEmails('read', $ieId, $mbox, $uid);
1522         }
1523
1524         /**
1525          * Marks emails with the passed flag type.  This will be applied to local
1526          * cache files as well as remote emails.
1527          * @param string $type Flag type
1528          * @param string $ieId
1529          * @param string $folder IMAP folder structure or SugarFolder GUID
1530          * @param string $uids Comma sep list of UIDs or GUIDs
1531          */
1532         function markEmails($type, $ieId, $folder, $uids) {
1533
1534                 global $app_strings;
1535                 $uids = $this->_cleanUIDList($uids);
1536                 $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
1537
1538                 if(strpos($folder, 'sugar::') !== false) {
1539                         // dealing with a sugar email object, uids are GUIDs
1540                         foreach($exUids as $id) {
1541                                 $email = new Email();
1542                                 $email->retrieve($id);
1543
1544                                 switch($type) {
1545                                         case "unread":
1546                                                 $email->status = 'unread';
1547                                                 $email->save();
1548                                         break;
1549
1550                                         case "read":
1551                                                 $email->status = 'read';
1552                                                 $email->save();
1553                                         break;
1554
1555                                         case "deleted":
1556                                                 $email->delete();
1557                                         break;
1558
1559                                         case "flagged":
1560                                                 $email->flagged = 1;
1561                                                 $email->save();
1562                                         break;
1563
1564                                         case "unflagged":
1565                                                 $email->flagged = 0;
1566                                                 $email->save();
1567                                         break;
1568
1569                                 }
1570                         }
1571                 } else {
1572                         /* dealing with IMAP email, uids are IMAP uids */
1573                         global $ie; // provided by EmailUIAjax.php
1574                         if(empty($ie)) {
1575
1576                                 $ie = new InboundEmail();
1577                         }
1578                         $ie->retrieve($ieId);
1579                         $ie->mailbox = $folder;
1580                         $ie->connectMailserver();
1581                         // mark cache files
1582                         if($type == 'deleted') {
1583                                 $ie->deleteMessageOnMailServer($uids);
1584                                 $ie->deleteMessageFromCache($uids);
1585                         } else {
1586                                 $overviews = $ie->getCacheValueForUIDs($ie->mailbox, $exUids);
1587                                 $manipulated = array();
1588
1589                                 foreach($overviews['retArr'] as $k => $overview) {
1590                                         if(in_array($overview->uid, $exUids)) {
1591                                                 switch($type) {
1592                                                         case "unread":
1593                                                                 $overview->seen = 0;
1594                                                         break;
1595
1596                                                         case "read":
1597                                                                 $overview->seen = 1;
1598                                                         break;
1599
1600                                                         case "flagged":
1601                                                                 $overview->flagged = 1;
1602                                                         break;
1603
1604                                                         case "unflagged":
1605                                                                 $overview->flagged = 0;
1606                                                         break;
1607                                                 }
1608                                                 $manipulated[] = $overview;
1609                                         }
1610                                 }
1611
1612                                 if(!empty($manipulated)) {
1613                                         $ie->setCacheValue($ie->mailbox, array(), $manipulated);
1614                                         /* now mark emails on email server */
1615                                         $ie->markEmails(implode(",", explode($app_strings['LBL_EMAIL_DELIMITER'], $uids)), $type);
1616                                 }
1617                         } // end not type == deleted
1618                 }
1619         }
1620
1621 function doAssignment($distributeMethod, $ieid, $folder, $uids, $users) {
1622         global $app_strings;
1623         $users = explode(",", $users);
1624         $emailIds = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
1625         $out = "";
1626         if($folder != 'sugar::Emails') {
1627                 $emailIds = array();
1628                 $uids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
1629                 $ie = new InboundEmail();
1630                 $ie->retrieve($ieid);
1631                 $messageIndex = 1;
1632                 // dealing with an inbound email data so we need to import an email and then
1633                 foreach($uids as $uid) {
1634                         $ie->mailbox = $folder;
1635                         $ie->connectMailserver();
1636                         $msgNo = $uid;
1637                         if (!$ie->isPop3Protocol()) {
1638                                 $msgNo = imap_msgno($ie->conn, $uid);
1639                         } else {
1640                                 $msgNo = $ie->getCorrectMessageNoForPop3($uid);
1641                         }
1642
1643                         if(!empty($msgNo)) {
1644                                 if ($ie->importOneEmail($msgNo, $uid)) {
1645                                         $emailIds[] = $ie->email->id;
1646                                         $ie->deleteMessageOnMailServer($uid);
1647                                         //$ie->retrieve($ieid);
1648                                         //$ie->connectMailserver();
1649                                         $ie->mailbox = $folder;
1650                                         $ie->deleteMessageFromCache(($uids[] = $uid));
1651                                 } else {
1652                                         $out = $out . "Message No : " . $messageIndex . " failed. Reason : Message already imported \r\n";
1653                                 }
1654                         }
1655                         $messageIndex++;
1656                 } // for
1657         } // if
1658
1659         if (count($emailIds) > 0) {
1660                 $this->doDistributionWithMethod($users, $emailIds, $distributeMethod);
1661         } // if
1662         return $out;
1663 } // fn
1664
1665 /**
1666  * get team id and team set id from request
1667  * @return  array
1668  */
1669 function getTeams() {
1670 }
1671
1672 function doDistributionWithMethod($users, $emailIds, $distributionMethod) {
1673         // we have users and the items to distribute
1674         if($distributionMethod == 'roundRobin') {
1675                 $this->distRoundRobin($users, $emailIds);
1676         } elseif($distributionMethod == 'leastBusy') {
1677                 $this->distLeastBusy($users, $emailIds);
1678         } elseif($distributionMethod == 'direct') {
1679                 if(count($users) > 1) {
1680                         // only 1 user allowed in direct assignment
1681                         $error = 1;
1682                 } else {
1683                         $user = $users[0];
1684                         $this->distDirect($user, $emailIds);
1685                 } // else
1686         } // elseif
1687
1688 } // fn
1689
1690 /**
1691  * distributes emails to users on Round Robin basis
1692  * @param       $userIds        array of users to dist to
1693  * @param       $mailIds        array of email ids to push on those users
1694  * @return  boolean             true on success
1695  */
1696 function distRoundRobin($userIds, $mailIds) {
1697         // check if we have a 'lastRobin'
1698         $lastRobin = $userIds[0];
1699         foreach($mailIds as $k => $mailId) {
1700                 $userIdsKeys = array_flip($userIds); // now keys are values
1701                 $thisRobinKey = $userIdsKeys[$lastRobin] + 1;
1702                 if(!empty($userIds[$thisRobinKey])) {
1703                         $thisRobin = $userIds[$thisRobinKey];
1704                         $lastRobin = $userIds[$thisRobinKey];
1705                 } else {
1706                         $thisRobin = $userIds[0];
1707                         $lastRobin = $userIds[0];
1708                 }
1709
1710                 $email = new Email();
1711                 $email->retrieve($mailId);
1712                 $email->assigned_user_id = $thisRobin;
1713                 $email->status = 'unread';
1714                 $email->save();
1715         }
1716
1717         return true;
1718 }
1719
1720 /**
1721  * distributes emails to users on Least Busy basis
1722  * @param       $userIds        array of users to dist to
1723  * @param       $mailIds        array of email ids to push on those users
1724  * @return  boolean             true on success
1725  */
1726 function distLeastBusy($userIds, $mailIds) {
1727         foreach($mailIds as $k => $mailId) {
1728                 $email = new Email();
1729                 $email->retrieve($mailId);
1730                 foreach($userIds as $k => $id) {
1731                         $r = $this->db->query("SELECT count(*) AS c FROM emails WHERE assigned_user_id = '.$id.' AND status = 'unread'");
1732                         $a = $this->db->fetchByAssoc($r);
1733                         $counts[$id] = $a['c'];
1734                 }
1735                 asort($counts); // lowest to highest
1736                 $countsKeys = array_flip($counts); // keys now the 'count of items'
1737                 $leastBusy = array_shift($countsKeys); // user id of lowest item count
1738                 $email->assigned_user_id = $leastBusy;
1739                 $email->status = 'unread';
1740                 $email->save();
1741         }
1742         return true;
1743 }
1744
1745 /**
1746  * distributes emails to 1 user
1747  * @param       $user           users to dist to
1748  * @param       $mailIds        array of email ids to push
1749  * @return  boolean             true on success
1750  */
1751 function distDirect($user, $mailIds) {
1752         foreach($mailIds as $k => $mailId) {
1753                 $email = new Email();
1754                 $email->retrieve($mailId);
1755                 $email->assigned_user_id = $user;
1756                 $email->status = 'unread';
1757
1758                 $email->save();
1759         }
1760         return true;
1761 }
1762
1763 function getAssignedEmailsCountForUsers($userIds) {
1764         $counts = array();
1765         foreach($userIds as $id) {
1766                 $r = $this->db->query("SELECT count(*) AS c FROM emails WHERE assigned_user_id = '$id' AND status = 'unread'");
1767                 $a = $this->db->fetchByAssoc($r);
1768                 $counts[$id] = $a['c'];
1769         } // foreach
1770         return $counts;
1771 } // fn
1772
1773 function getLastRobin($ie) {
1774         $lastRobin = "";
1775         if($this->validCacheFileExists($ie->id, 'folders', "robin.cache.php")) {
1776                 $lastRobin = $this->getCacheValue($ie->id, 'folders', "robin.cache.php", 'robin');
1777         } // if
1778         return $lastRobin;
1779 } // fn
1780
1781 function setLastRobin($ie, $lastRobin) {
1782     global $sugar_config;
1783     $cacheFolderPath = clean_path("{$sugar_config['cache_dir']}modules/Emails/{$ie->id}/folders");
1784     if (!file_exists($cacheFolderPath)) {
1785         mkdir_recursive($cacheFolderPath);
1786     }
1787         $this->writeCacheFile('robin', $lastRobin, $ie->id, 'folders', "robin.cache.php");
1788 } // fn
1789
1790         /**
1791          * returns the metadata defining a single email message for display.  Uses cache file if it exists
1792          * @return array
1793          */
1794 function getSingleMessage($ie) {
1795
1796                 global $timedate;
1797                 global $app_strings,$mod_strings;
1798                 $ie->retrieve($_REQUEST['ieId']);
1799                 $noCache = true;
1800
1801                 $ie->mailbox = $_REQUEST['mbox'];
1802                 $filename = $_REQUEST['mbox'].$_REQUEST['uid'].".php";
1803                 $md5uidl = "";
1804                 if ($ie->isPop3Protocol()) {
1805                         $md5uidl = md5($_REQUEST['uid']);
1806                         $filename = $_REQUEST['mbox'].$md5uidl.".php";
1807                 } // if
1808
1809                 if($this->validCacheFileExists($_REQUEST['ieId'], 'messages', $filename)) {
1810                         $out = $this->getCacheValue($_REQUEST['ieId'], 'messages', $filename, 'out');
1811                         $noCache = false;
1812
1813                         // something fubar'd the cache?
1814                         if(empty($out['meta']['email']['name']) && empty($out['meta']['email']['description'])) {
1815                                 $noCache = true;
1816                         } else {
1817                                 // When sending data from cache, convert date into users preffered format
1818                                 $dateTimeInGMTFormat = $out['meta']['email']['date_start'];
1819                                 $out['meta']['email']['date_start'] = $timedate->to_display_date_time($dateTimeInGMTFormat);
1820                         } // else
1821                 }
1822
1823                 if($noCache) {
1824                         $writeToCacheFile = true;
1825                         if ($ie->isPop3Protocol()) {
1826                                 $status = $ie->setEmailForDisplay($_REQUEST['uid'], true, true, true);
1827                         } else {
1828                                 $status = $ie->setEmailForDisplay($_REQUEST['uid'], false, true, true);
1829                         }
1830                         $out = $ie->displayOneEmail($_REQUEST['uid'], $_REQUEST['mbox']);
1831                         // modify the out object to store date in GMT format on the local cache file
1832                         $dateTimeInUserFormat = $out['meta']['email']['date_start'];
1833                         $out['meta']['email']['date_start'] = $timedate->to_db($dateTimeInUserFormat);
1834                         if ($status == 'error') {
1835                                 $writeToCacheFile = false;
1836                         }
1837                         if ($writeToCacheFile) {
1838                                 if ($ie->isPop3Protocol()) {
1839                                         $this->writeCacheFile('out', $out, $_REQUEST['ieId'], 'messages', "{$_REQUEST['mbox']}{$md5uidl}.php");
1840                                 } else {
1841                                         $this->writeCacheFile('out', $out, $_REQUEST['ieId'], 'messages', "{$_REQUEST['mbox']}{$_REQUEST['uid']}.php");
1842                                 } // else
1843                         // restore date in the users preferred format to be send on to UI for diaply
1844                         $out['meta']['email']['date_start'] = $dateTimeInUserFormat;
1845                         } // if
1846                 }
1847                 $out['meta']['email']['toaddrs'] = $this->generateExpandableAddrs($out['meta']['email']['toaddrs']);
1848                 if(!empty($out['meta']['email']['cc_addrs'])) {
1849             $ccs = $this->generateExpandableAddrs($out['meta']['email']['cc_addrs']);
1850                     $out['meta']['cc'] = <<<eoq
1851                                 <tr>
1852                                         <td NOWRAP valign="top" class="displayEmailLabel">
1853                                                 {$app_strings['LBL_EMAIL_CC']}:
1854                                         </td>
1855                                         <td class="displayEmailValue">
1856                                                 {$ccs}
1857                                         </td>
1858                                 </tr>
1859 eoq;
1860                 }
1861
1862                  if(empty($out['meta']['email']['description']))
1863                 $out['meta']['email']['description'] = $mod_strings['LBL_EMPTY_EMAIL_BODY'];
1864
1865                 if($noCache) {
1866                         $GLOBALS['log']->debug("EMAILUI: getSingleMessage() NOT using cache file");
1867                 } else {
1868                         $GLOBALS['log']->debug("EMAILUI: getSingleMessage() using cache file [ ".$_REQUEST['mbox'].$_REQUEST['uid'].".php ]");
1869                 }
1870
1871                 $this->setReadFlag($_REQUEST['ieId'], $_REQUEST['mbox'], $_REQUEST['uid']);
1872                 return $out;
1873         }
1874
1875
1876         /**
1877          * Returns the HTML for a list of emails in a given folder
1878          * @param GUID $ieId GUID to InboundEmail instance
1879          * @param string $mbox Mailbox path name in dot notation
1880          * @param int $folderListCacheOffset Seconds for valid cache file
1881          * @return string HTML render of list.
1882          */
1883         function getListEmails($ieId, $mbox, $folderListCacheOffset, $forceRefresh='false') {
1884                 global $sugar_config;
1885
1886
1887                 $ie = new InboundEmail();
1888                 $ie->retrieve($ieId);
1889                 $list = $ie->displayFolderContents($mbox, $forceRefresh);
1890
1891                 return $list;
1892         }
1893
1894         /**
1895          * Returns the templatized compose screen.  Used by reply, forwards and draft status messages.
1896          * @param object email Email bean in focus
1897          */
1898         function displayComposeEmail($email) {
1899                 global $locale;
1900                 global $current_user;
1901
1902
1903                 $ea = new SugarEmailAddress();
1904
1905                 if(!empty($email)) {
1906                         $description = (empty($email->description_html)) ? $email->description : $email->description_html;
1907                 }
1908
1909                 //Get the most complete address list availible for this email
1910                 $addresses = array('toAddresses' => 'to', 'ccAddresses' => 'cc', 'bccAddresses' => 'bcc');
1911                 foreach($addresses as $var => $type)
1912                 {
1913                         $$var = "";
1914                         foreach (array("{$type}_addrs_names", "{$type}addrs", "{$type}_addrs") as $emailVar)
1915                         {
1916                                 if (!empty($email->$emailVar)) {
1917                                         $$var = $email->$emailVar;
1918                                         break;
1919                                 }
1920                         }
1921                 }
1922
1923                 $ret = array();
1924                 $ret['type'] = $email->type;
1925                 $ret['name'] = $email->name;
1926                 $ret['description'] = $description;
1927                 $ret['from'] = (isset($_REQUEST['composeType']) && $_REQUEST['composeType'] == 'forward') ? "" : $email->from_addr;
1928                 $ret['to'] = from_html($toAddresses);
1929                 $ret['uid'] = $email->id;
1930                 $ret['parent_name'] = $email->parent_name;
1931                 $ret['parent_type'] = $email->parent_type;
1932                 $ret['parent_id'] = $email->parent_id;
1933
1934                 // reply all
1935                 if(isset($_REQUEST['composeType']) && $_REQUEST['composeType'] == 'replyAll') {
1936                     $ret['cc'] = from_html($ccAddresses);
1937                     $ret['bcc'] = $bccAddresses;
1938
1939                         $userEmails = array();
1940                         $userEmailsMeta = $ea->getAddressesByGUID($current_user->id, 'Users');
1941                         foreach($userEmailsMeta as $emailMeta) {
1942                                 $userEmails[] = from_html(strtolower(trim($emailMeta['email_address'])));
1943                         }
1944                         $userEmails[] = from_html(strtolower(trim($email->from_addr)));
1945
1946                         $ret['cc'] = from_html($email->cc_addrs);
1947                         $toAddresses = from_html($toAddresses);
1948                         $to = str_replace($this->addressSeparators, "::", $toAddresses);
1949                         $exTo = explode("::", $to);
1950
1951                         if(is_array($exTo)) {
1952                                 foreach($exTo as $addr) {
1953                                         $addr = strtolower(trim($addr));
1954                                         if(!in_array($addr, $userEmails)) {
1955                                                 if(!empty($ret['cc'])) {
1956                                                         $ret['cc'] = $ret['cc'].", ";
1957                                                 }
1958                                                 $ret['cc'] = $ret['cc'].trim($addr);
1959                                         }
1960                                 }
1961                         } elseif(!empty($exTo)) {
1962                                 $exTo = trim($exTo);
1963                                 if(!in_array($exTo, $userEmails)) {
1964                                         $ret['cc'] = $ret['cc'].", ".$exTo;
1965                                 }
1966                         }
1967                 }
1968                 return $ret;
1969         }
1970         /**
1971          * Formats email body on reply/forward
1972          * @param object email Email object in focus
1973          * @param string type
1974          * @return object email
1975          */
1976         function handleReplyType($email, $type) {
1977                 global $mod_strings;
1978                  $GLOBALS['log']->debug("****At Handle Reply Type: $type");
1979                 switch($type) {
1980                         case "reply":
1981                         case "replyAll":
1982                                 $header = $email->getReplyHeader();
1983                 if(!preg_match('/^(re:)+/i', $email->name)) {
1984                     $email->name = "{$mod_strings['LBL_RE']} {$email->name}";
1985                 }
1986                                 if ($type == "reply") {
1987                                         $email->cc_addrs = "";
1988                                         if (!empty($email->reply_to_addr)) {
1989                                                 $email->from_addr = $email->reply_to_addr;
1990                                         } // if
1991                                 } else {
1992                                         if (!empty($email->reply_to_addr)) {
1993                                                 $email->to_addrs = $email->to_addrs . "," . $email->reply_to_addr;
1994                                         } // if
1995                                 } // else
1996                         break;
1997
1998                         case "forward":
1999                                 $header = $email->getForwardHeader();
2000                                 if(!preg_match('/^(fw:)+/i', $email->name)) {
2001                     $email->name = "{$mod_strings['LBL_FW']} {$email->name}";
2002                 }
2003                                 $email->cc_addrs = "";
2004                         break;
2005
2006                         case "replyCase":
2007                                 $GLOBALS['log']->debug("EMAILUI: At reply case");
2008                                 $header = $email->getReplyHeader();
2009
2010                 $myCase = new aCase();
2011                 $myCase->retrieve($email->parent_id);
2012                 $myCaseMacro = $myCase->getEmailSubjectMacro();
2013                 $email->parent_name = $myCase->name;
2014                 $GLOBALS['log']->debug("****Case # : {$myCase->case_number} macro: $myCaseMacro");
2015                                 if(!strpos($email->name, str_replace('%1',$myCase->case_number,$myCaseMacro))) {
2016                                 $GLOBALS['log']->debug("Replacing");
2017                             $email->name = str_replace('%1',$myCase->case_number,$myCaseMacro) . ' '. $email->name;
2018                         }
2019                 $email->name = "{$mod_strings['LBL_RE']} {$email->name}";
2020             break;
2021                 }
2022
2023                 $html = trim($email->description_html);
2024                 $plain = trim($email->description);
2025
2026                 $desc = (!empty($html)) ? $html : $plain;
2027
2028                 $email->description = $header.$email->quoteHtmlEmailForNewEmailUI($desc);
2029                 return $email;
2030
2031         }
2032
2033         ///////////////////////////////////////////////////////////////////////////
2034         ////    PRIVATE HELPERS
2035         /**
2036          * Generates a UNION query to get one list of users, contacts, leads, and
2037          * prospects; used specifically for the addressBook
2038          */
2039         function _getPeopleUnionQuery($whereArr , $person) {
2040                 global $current_user , $app_strings;
2041                 global $db;
2042                 if(!isset($person) || $person === 'LBL_DROPDOWN_LIST_ALL'){
2043                         $peopleTables = array("users",
2044                                               "contacts",
2045                                               "leads",
2046                                               "prospects",
2047                                               "accounts"
2048                                              );
2049                 }else{
2050                         $peopleTables = array($person);
2051                 }
2052                 $q = '';
2053
2054                 $whereAdd = "";
2055
2056                 foreach($whereArr as $column => $clause) {
2057                         if(!empty($whereAdd)) {
2058                                 $whereAdd .= " AND ";
2059                         }
2060                         $clause = $current_user->db->helper->escape_quote($clause);
2061                         $whereAdd .= "{$column} LIKE '{$clause}%'";
2062                 }
2063
2064
2065                 foreach($peopleTables as $table) {
2066                         $module = ucfirst($table);
2067             $class = substr($module, 0, strlen($module) - 1);
2068             require_once("modules/{$module}/{$class}.php");
2069             $person = new $class();
2070                         if (!$person->ACLAccess('list')) {
2071                                 continue;
2072                         } // if
2073                         $where = "({$table}.deleted = 0 AND eabr.primary_address = 1 AND {$table}.id <> '{$current_user->id}')";
2074
2075             if (ACLController::requireOwner($module, 'list')) {
2076                 $where = $where . " AND ({$table}.assigned_user_id = '{$current_user->id}')";
2077             } // if
2078                         if(!empty($whereAdd)) {
2079                                 $where .= " AND ({$whereAdd})";
2080                         }
2081
2082                         if ($person === 'accounts') {
2083                                 $t = "SELECT {$table}.id, '' first_name, {$table}.name, eabr.primary_address, ea.email_address, '{$module}' module ";
2084                         } else {
2085                                 $t = "SELECT {$table}.id, {$table}.first_name, {$table}.last_name, eabr.primary_address, ea.email_address, '{$module}' module ";
2086                         }
2087                         $t .= "FROM {$table} ";
2088                         $t .= "JOIN email_addr_bean_rel eabr ON ({$table}.id = eabr.bean_id and eabr.deleted=0) ";
2089                         $t .= "JOIN email_addresses ea ON (eabr.email_address_id = ea.id) ";
2090                         $t .= " WHERE {$where}";
2091
2092                         if(!empty($q)) {
2093                                 $q .= "\n UNION ALL \n";
2094                         }
2095
2096                         $q .= "({$t})";
2097                 }
2098                 $countq = "SELECT count(people.id) c from ($q) people";
2099                 $q .= "ORDER BY last_name";
2100
2101                 return array('query' => $q, 'countQuery' => $countq);
2102     }
2103
2104     /**
2105      * get emails of related bean for a given bean id
2106      * @param $beanType
2107      * @param $condition array of conditions inclued bean id
2108      * @return array('query' => $q, 'countQuery' => $countq);
2109      */
2110     function getRelatedEmail($beanType, $whereArr, $relatedBeanInfoArr = ''){
2111         global $beanList, $current_user, $app_strings, $db;
2112         $finalQuery = '';
2113                 $searchBeans = null;
2114                 if($beanType === 'LBL_DROPDOWN_LIST_ALL')
2115                         $searchBeans = array("users",
2116                                              "contacts",
2117                                              "leads",
2118                                              "prospects",
2119                                              "accounts"
2120                                             );
2121
2122         if ($relatedBeanInfoArr == '' || empty($relatedBeanInfoArr['related_bean_type']) )
2123         {
2124                         if ($searchBeans != null)
2125                         {
2126                                 $q = array();
2127                                 foreach ($searchBeans as $searchBean)
2128                                 {
2129                                     $searchq = $this->findEmailFromBeanIds('', $searchBean, $whereArr);
2130                                     if(!empty($searchq)) {
2131                                             $q[] = "($searchq)";
2132                                     }
2133                                 }
2134                                 if (!empty($q))
2135                             $finalQuery .= implode("\n UNION ALL \n", $q);
2136                         }
2137                         else
2138                                 $finalQuery = $this->findEmailFromBeanIds('', $beanType, $whereArr);
2139         }
2140         else
2141         {
2142             $class = $beanList[$relatedBeanInfoArr['related_bean_type']];
2143             $focus = new $class();
2144             $focus->retrieve($relatedBeanInfoArr['related_bean_id']);
2145             if ($searchBeans != null)
2146             {
2147                 $q = array();
2148                 foreach ($searchBeans as $searchBean)
2149                 {
2150                     if ($focus->load_relationship($searchBean))
2151                     {
2152                         $data = $focus->$searchBean->get();
2153                         if (count($data) != 0)
2154                         $q[] = '('.$this->findEmailFromBeanIds($data, $searchBean, $whereArr).')';
2155                     }
2156                 }
2157                 if (!empty($q))
2158                 $finalQuery .= implode("\n UNION ALL \n", $q);
2159             }
2160             else
2161             {
2162                 if ($focus->load_relationship($beanType))
2163                 {
2164                     $data = $focus->$beanType->get();
2165                     if (count($data) != 0)
2166                     $finalQuery = $this->findEmailFromBeanIds($data, $beanType, $whereArr);
2167                 }
2168             }
2169         }
2170         $countq = "SELECT count(people.id) c from ($finalQuery) people";
2171                 return array('query' => $finalQuery, 'countQuery' => $countq);
2172     }
2173
2174     function findEmailFromBeanIds($beanIds, $beanType, $whereArr) {
2175         global $current_user;
2176                 $q = '';
2177                 $whereAdd = "";
2178                 $relatedIDs = '';
2179                 if ($beanIds != '') {
2180                         foreach ($beanIds as $key => $value) {
2181                                 $beanIds[$key] = '\''.$value.'\'';
2182                         }
2183                         $relatedIDs = implode(',', $beanIds);
2184                 }
2185
2186                 if ($beanType == 'accounts') {
2187                         if (isset($whereArr['first_name'])) {
2188                                 $whereArr['name'] = $whereArr['first_name'];
2189                         }
2190                         unset($whereArr['last_name']);
2191                         unset($whereArr['first_name']);
2192                 }
2193
2194                 foreach($whereArr as $column => $clause) {
2195                         if(!empty($whereAdd)) {
2196                                 $whereAdd .= " OR ";
2197                         }
2198                         $clause = $current_user->db->helper->escape_quote($clause);
2199                         $whereAdd .= "{$column} LIKE '{$clause}%'";
2200                 }
2201                 $table = $beanType;
2202                 $module = ucfirst($table);
2203             $class = substr($module, 0, strlen($module) - 1);
2204             require_once("modules/{$module}/{$class}.php");
2205             $person = new $class();
2206                 if ($person->ACLAccess('list')) {
2207                         if ($relatedIDs != '') {
2208                                 $where = "({$table}.deleted = 0 AND eabr.primary_address = 1 AND {$table}.id in ($relatedIDs))";
2209                         } else {
2210                                 $where = "({$table}.deleted = 0 AND eabr.primary_address = 1)";
2211                         }
2212
2213                         if (ACLController::requireOwner($module, 'list')) {
2214                                 $where = $where . " AND ({$table}.assigned_user_id = '{$current_user->id}')";
2215                         } // if
2216                         if(!empty($whereAdd)) {
2217                                 $where .= " AND ({$whereAdd})";
2218                         }
2219
2220                         if ($beanType === 'accounts') {
2221                                 $t = "SELECT {$table}.id, '' first_name, {$table}.name last_name, eabr.primary_address, ea.email_address, '{$module}' module ";
2222                         } else {
2223                                 $t = "SELECT {$table}.id, {$table}.first_name, {$table}.last_name, eabr.primary_address, ea.email_address, '{$module}' module ";
2224                         }
2225
2226                         $t .= "FROM {$table} ";
2227                         $t .= "JOIN email_addr_bean_rel eabr ON ({$table}.id = eabr.bean_id and eabr.deleted=0) ";
2228                         $t .= "JOIN email_addresses ea ON (eabr.email_address_id = ea.id) ";
2229                         $t .= " WHERE {$where}";
2230                 } // if
2231                 return $t;
2232     }
2233
2234         /**
2235          * Cleans UID lists
2236          * @param mixed $uids
2237          * @param bool $returnString False will return an array
2238          * @return mixed
2239          */
2240         function _cleanUIDList($uids, $returnString=false) {
2241                 global $app_strings;
2242                 $GLOBALS['log']->debug("_cleanUIDList: before - [ {$uids} ]");
2243
2244                 if(!is_array($uids)) {
2245                         $returnString = true;
2246
2247                         $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
2248                         $uids = $exUids;
2249                 }
2250
2251                 $cleanUids = array();
2252                 foreach($uids as $uid) {
2253                         $cleanUids[$uid] = $uid;
2254                 }
2255
2256                 sort($cleanUids);
2257
2258                 if($returnString) {
2259                         $cleanImplode = implode($app_strings['LBL_EMAIL_DELIMITER'], $cleanUids);
2260                         $GLOBALS['log']->debug("_cleanUIDList: after - [ {$cleanImplode} ]");
2261                         return $cleanImplode;
2262                 }
2263
2264                 return $cleanUids;
2265         }
2266
2267         /**
2268          * Creates defaults for the User
2269          * @param object $user User in focus
2270          */
2271         function preflightUser(&$user) {
2272                 global $mod_strings;
2273
2274                 $goodToGo = $user->getPreference("email2Preflight", "Emails");
2275                         $q = "SELECT count(*) count FROM folders f where f.created_by = '{$user->id}' AND f.folder_type = 'inbound' AND f.deleted = 0";
2276                         $r = $user->db->query($q);
2277                         $a = $user->db->fetchByAssoc($r);
2278
2279                         if($a['count'] < 1) {
2280                                 require_once("include/SugarFolders/SugarFolders.php");
2281                                 // My Emails
2282                                 $folder = new SugarFolder();
2283                                 $folder->new_with_id = true;
2284                                 $folder->id = create_guid();
2285                                 $folder->name = $mod_strings['LNK_MY_INBOX'];
2286                                 $folder->has_child = 1;
2287                                 $folder->created_by = $user->id;
2288                                 $folder->modified_by = $user->id;
2289                                 $folder->is_dynamic = 1;
2290                                 $folder->folder_type = "inbound";
2291                                 $folder->dynamic_query = $this->generateDynamicFolderQuery('inbound', $user->id);
2292                                 $folder->save();
2293
2294                                 // My Drafts
2295                                 $drafts = new SugarFolder();
2296                                 $drafts->name = $mod_strings['LNK_MY_DRAFTS'];
2297                                 $drafts->has_child = 0;
2298                                 $drafts->parent_folder = $folder->id;
2299                                 $drafts->created_by = $user->id;
2300                                 $drafts->modified_by = $user->id;
2301                                 $drafts->is_dynamic = 1;
2302                                 $drafts->folder_type = "draft";
2303                                 $drafts->dynamic_query = $this->generateDynamicFolderQuery('draft', $user->id);
2304                                 $drafts->save();
2305
2306
2307                                 // Sent Emails
2308                                 $archived = new SugarFolder();
2309                                 $archived->name = $mod_strings['LNK_SENT_EMAIL_LIST'];
2310                                 $archived->has_child = 0;
2311                                 $archived->parent_folder = $folder->id;
2312                                 $archived->created_by = $user->id;
2313                                 $archived->modified_by = $user->id;
2314                                 $archived->is_dynamic = 1;
2315                                 $archived->folder_type = "sent";
2316                                 $archived->dynamic_query = $this->generateDynamicFolderQuery('sent', $user->id);
2317                                 $archived->save();
2318
2319                         // set flag to show that this was run
2320                         $user->setPreference("email2Preflight", true, 1, "Emails");
2321                 }
2322         }
2323
2324         /**
2325          * Parses the core dynamic folder query
2326          * @param string $type 'inbound', 'draft', etc.
2327          * @param string $userId
2328          * @return string
2329          */
2330         function generateDynamicFolderQuery($type, $userId) {
2331                 $q = $this->coreDynamicFolderQuery;
2332
2333                 $status = $type;
2334
2335                 if($type == "sent") {
2336                         $type = "out";
2337                 }
2338
2339                 $replacee = array("::TYPE::", "::STATUS::", "::USER_ID::");
2340                 $replacer = array($type, $status, $userId);
2341
2342                 $ret = str_replace($replacee, $replacer, $q);
2343
2344                 if($type == 'inbound') {
2345                         $ret .= " AND status NOT IN ('sent', 'archived', 'draft') AND type NOT IN ('out', 'archived', 'draft')";
2346                 } else {
2347                         $ret .= " AND status NOT IN ('archived') AND type NOT IN ('archived')";
2348                 }
2349
2350                 return $ret;
2351         }
2352
2353         /**
2354          * Preps the User's cache dir
2355          */
2356         function preflightUserCache() {
2357                 $path = clean_path($this->userCacheDir);
2358                 if(!file_exists($this->userCacheDir))
2359                         mkdir_recursive($path);
2360
2361                 $files = findAllFiles($path, array());
2362
2363                 foreach($files as $file) {
2364                         unlink($file);
2365                 }
2366         }
2367
2368         function clearInboundAccountCache($ieId) {
2369                 global $sugar_config;
2370                 $cacheRoot = getcwd()."/{$sugar_config['cache_dir']}modules/Emails/{$ieId}";
2371                 $files = findAllFiles($cacheRoot."/messages/", array());
2372                 foreach($files as $file) {
2373                         unlink($file);
2374                 } // fn
2375                 $files = findAllFiles($cacheRoot."/attachments/", array());
2376                 foreach($files as $file) {
2377                         unlink($file);
2378                 } // for
2379         } // fn
2380
2381         /**
2382          * returns an array of EmailTemplates that the user has access to for the compose email screen
2383          * @return array
2384          */
2385         function getEmailTemplatesArray() {
2386
2387                 global $app_strings;
2388
2389                 if(ACLController::checkAccess('EmailTemplates', 'list', true) && ACLController::checkAccess('EmailTemplates', 'view', true)) {
2390                         $et = new EmailTemplate();
2391                         $etResult = $et->db->query($et->create_new_list_query('','',array(),array(),''));
2392                         $email_templates_arr = array('' => $app_strings['LBL_NONE']);
2393                         while($etA = $et->db->fetchByAssoc($etResult)) {
2394                                 $email_templates_arr[$etA['id']] = $etA['name'];
2395                         }
2396                 } else {
2397                         $email_templates_arr = array('' => $app_strings['LBL_NONE']);
2398                 }
2399
2400                 return $email_templates_arr;
2401         }
2402
2403         function getFromAccountsArray($ie) {
2404         global $current_user;
2405         global $app_strings;
2406
2407         $ieAccountsFull = $ie->retrieveAllByGroupIdWithGroupAccounts($current_user->id);
2408         $ieAccountsFrom= array();
2409
2410         $oe = new OutboundEmail();
2411         $system = $oe->getSystemMailerSettings();
2412         $ret = $current_user->getUsersNameAndEmail();
2413                 $ret['name'] = from_html($ret['name']);
2414                 $useMyAccountString = true;
2415
2416         if(empty($ret['email'])) {
2417                 $systemReturn = $current_user->getSystemDefaultNameAndEmail();
2418                 $ret['email'] = $systemReturn['email'];
2419                 $ret['name'] = from_html($systemReturn['name']);
2420                 $useMyAccountString = false;
2421                 } // if
2422
2423                 $myAccountString = '';
2424                 if ($useMyAccountString) {
2425                         $myAccountString = " - {$app_strings['LBL_MY_ACCOUNT']}";
2426                 } // if
2427
2428                 //Check to make sure that the user has set the associated inbound email acount -> outbound acount is active.
2429                 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
2430         $sf = new SugarFolder();
2431         $groupSubs = $sf->getSubscriptions($current_user);
2432
2433         foreach($ieAccountsFull as $k => $v)
2434         {
2435             $personalSelected = (!empty($showFolders) && in_array($v->id, $showFolders));
2436
2437             $allowOutboundGroupUsage = $v->get_stored_options('allow_outbound_group_usage',FALSE);
2438             $groupSelected = ( in_array($v->groupfolder_id, $groupSubs)  && $allowOutboundGroupUsage);
2439             $selected = ( $personalSelected || $groupSelected );
2440
2441             if(!$selected)
2442             {
2443                 $GLOBALS['log']->debug("Inbound Email {$v->name}, not selected and will not be available for selection within compose UI.");
2444                 continue;
2445             }
2446
2447                 $name = $v->get_stored_options('from_name');
2448                 $addr = $v->get_stored_options('from_addr');
2449                 if ($name != null && $addr != null) {
2450                         $name = from_html($name);
2451                         if (!$v->is_personal) {
2452                         $ieAccountsFrom[] = array("value" => $v->id, "text" => "{$name} ({$addr}) - {$app_strings['LBL_EMAIL_UPPER_CASE_GROUP']}");
2453                         } else {
2454                         $ieAccountsFrom[] = array("value" => $v->id, "text" => "{$name} ({$addr})");
2455                         } // else
2456                 } // if
2457         } // foreach
2458
2459
2460         $userSystemOverride = $oe->getUsersMailerForSystemOverride($current_user->id);
2461         //Substitute in the users system override if its available.
2462         if($userSystemOverride != null)
2463                     $system = $userSystemOverride;
2464
2465         if( !empty($system->mail_smtpserver) )
2466         {
2467             $admin = new Administration();
2468             $admin->retrieveSettings(); //retrieve all admin settings.
2469             $ieAccountsFrom[] = array("value" => $system->id, "text" =>
2470                 "{$ret['name']} ({$ret['email']}){$myAccountString}");
2471         }
2472
2473         return $ieAccountsFrom;
2474     } // fn
2475
2476     /**
2477      * This function will return all the accounts this user has access to based on the
2478      * match of the emailId passed in as a parameter
2479      *
2480      * @param unknown_type $ie
2481      * @return unknown
2482      */
2483         function getFromAllAccountsArray($ie, $ret) {
2484         global $current_user;
2485         global $app_strings;
2486
2487         $ret['fromAccounts'] = array();
2488         if (!isset($ret['to']) && !empty($ret['from'])) {
2489                 $ret['fromAccounts']['status'] = false;
2490                 return $ret;
2491         }
2492         $ieAccountsFull = $ie->retrieveAllByGroupIdWithGroupAccounts($current_user->id);
2493                 $foundInPersonalAccounts = false;
2494                 $foundInGroupAccounts = false;
2495                 $foundInSystemAccounts = false;
2496
2497                 //$toArray = array();
2498                 if ($ret['type'] == "draft") {
2499                         $toArray = explode(",", $ret['from']);
2500                 } else {
2501                         $toArray = $ie->email->email2ParseAddressesForAddressesOnly($ret['to']);
2502                 } // else
2503         foreach($ieAccountsFull as $k => $v) {
2504                 $storedOptions = unserialize(base64_decode($v->stored_options));
2505                         if (  array_search_insensitive($storedOptions['from_addr'], $toArray)) {
2506                         if ($v->is_personal) {
2507                                         $foundInPersonalAccounts = true;
2508                                         break;
2509                                 } else  {
2510                                         $foundInGroupAccounts = true;
2511                                 } // else
2512                         } // if
2513         } // foreach
2514
2515             $oe = new OutboundEmail();
2516         $system = $oe->getSystemMailerSettings();
2517
2518         $return = $current_user->getUsersNameAndEmail();
2519                 $return['name'] = from_html($return['name']);
2520                 $useMyAccountString = true;
2521
2522         if(empty($return['email'])) {
2523                 $systemReturn = $current_user->getSystemDefaultNameAndEmail();
2524                 $return['email'] = $systemReturn['email'];
2525                 $return['name'] = from_html($systemReturn['name']);
2526                 $useMyAccountString = false;
2527                 } // if
2528
2529                 $myAccountString = '';
2530                 if ($useMyAccountString) {
2531                         $myAccountString = " - {$app_strings['LBL_MY_ACCOUNT']}";
2532                 } // if
2533
2534         if(!empty($system->id)) {
2535
2536             $admin = new Administration();
2537             $admin->retrieveSettings(); //retrieve all admin settings.
2538             if (in_array(trim($return['email']), $toArray)) {
2539                 $foundInSystemAccounts = true;
2540             } // if
2541         } // if
2542
2543         if (!$foundInPersonalAccounts && !$foundInGroupAccounts && !$foundInSystemAccounts) {
2544                 $ret['fromAccounts']['status'] = false;
2545                 return $ret;
2546         } // if
2547
2548         $ieAccountsFrom= array();
2549         foreach($ieAccountsFull as $k => $v) {
2550                 $storedOptions = unserialize(base64_decode($v->stored_options));
2551                 $storedOptionsName = from_html($storedOptions['from_name']);
2552
2553                 $selected = false;
2554                         if (array_search_insensitive($storedOptions['from_addr'], $toArray)) {
2555                 //if ($ret['to'] == $storedOptions['from_addr']) {
2556                         $selected = true;
2557                         } // if
2558                 if ($foundInPersonalAccounts) {
2559                         if ($v->is_personal) {
2560                         $ieAccountsFrom[] = array("value" => $v->id, "selected" => $selected, "text" => "{$storedOptionsName} ({$storedOptions['from_addr']})");
2561                         } // if
2562                 } else {
2563                 $ieAccountsFrom[] = array("value" => $v->id, "selected" => $selected, "text" => "{$storedOptionsName} ({$storedOptions['from_addr']}) - {$app_strings['LBL_EMAIL_UPPER_CASE_GROUP']}");
2564                 } // else
2565         } // foreach
2566
2567         if(!empty($system->id)) {
2568             if (!$foundInPersonalAccounts && !$foundInGroupAccounts && $foundInSystemAccounts) {
2569             $ieAccountsFrom[] = array("value" => $system->id, "selected" => true, "text" =>
2570                 "{$return['name']} ({$return['email']}){$myAccountString}");
2571             } else {
2572             $ieAccountsFrom[] = array("value" => $system->id, "text" =>
2573                 "{$return['name']} ({$return['email']}){$myAccountString}");
2574             } // else
2575         } // if
2576
2577         $ret['fromAccounts']['status'] = ($foundInPersonalAccounts || $foundInGroupAccounts || $foundInSystemAccounts) ? true : false;
2578                 $ret['fromAccounts']['data'] = $ieAccountsFrom;
2579         return $ret;
2580     } // fn
2581
2582
2583         /**
2584          * takes an array and creates XML
2585          * @param array Array to convert
2586          * @param string Name to wrap highest level items in array
2587          * @return string XML
2588          */
2589         function arrayToXML($a, $paramName) {
2590                 if(!is_array($a))
2591                         return '';
2592
2593                 $bad = array("<",">","'",'"',"&");
2594                 $good = array("&lt;", "&gt;", "&#39;", "&quot;","&amp;");
2595
2596                 $ret = "";
2597
2598                 for($i=0; $i<count($a); $i++) {
2599                         $email = $a[$i];
2600                         $ret .= "\n<{$paramName}>";
2601
2602                         foreach($email as $k => $v) {
2603                                 $ret .= "\n\t<{$k}>".str_replace($bad, $good, $v)."</{$k}>";
2604                         }
2605                         $ret .= "\n</{$paramName}>";
2606                 }
2607                 return $ret;
2608         }
2609
2610         /**
2611          * Re-used option getter for Show Accounts multiselect pane
2612          */
2613         function getShowAccountsOptions(&$ie) {
2614                 global $current_user;
2615                 global $app_strings;
2616                 global $mod_strings;
2617
2618                 $ieAccountsFull = $ie->retrieveAllByGroupId($current_user->id);
2619                 $ieAccountsShowOptionsMeta = array();
2620                 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
2621
2622                 $defaultIEAccount = $ie->getUsersDefaultOutboundServerId($current_user);
2623
2624                 foreach($ieAccountsFull as $k => $v) {
2625                         $selected = (!empty($showFolders) && in_array($v->id, $showFolders)) ? true : false;
2626                         $default = ($defaultIEAccount == $v->id) ? TRUE : FALSE;
2627                         $has_groupfolder = !empty($v->groupfolder_id) ? TRUE : FALSE;
2628                         $type = ($v->is_personal) ? $mod_strings['LBL_MAILBOX_TYPE_PERSONAL'] : $mod_strings['LBL_MAILBOX_TYPE_GROUP'];
2629
2630                         $ieAccountsShowOptionsMeta[] = array("id" => $v->id, "name" => $v->name, 'is_active' => $selected,
2631                                                                                                         'server_url' => $v->server_url, 'is_group' => !$v->is_personal,'group_id' => $v->group_id,
2632                                                                                                         'is_default' => $default, 'has_groupfolder' => $has_groupfolder,'type' => $type );
2633                 }
2634
2635                 //Retrieve the grou folders
2636                 $f = new SugarFolder();
2637                 $groupFolders = $f->getGroupFoldersForSettings($current_user);
2638
2639                 foreach ($groupFolders as $singleGroup)
2640                 {
2641                     //Retrieve the related IE accounts.
2642             $relatedIEAccounts = $ie->retrieveByGroupFolderId($singleGroup['id']);
2643
2644             if(count($relatedIEAccounts) == 0)
2645                 $server_url = $app_strings['LBL_EMAIL_MULT_GROUP_FOLDER_ACCOUNTS_EMPTY'];
2646             else if(count($relatedIEAccounts) == 1)
2647             {
2648                 if($relatedIEAccounts[0]->status != 'Active' || $relatedIEAccounts[0]->mailbox_type == 'bounce')
2649                     continue;
2650
2651                 $server_url = $relatedIEAccounts[0]->server_url;
2652             }
2653             else
2654                 $server_url = $app_strings['LBL_EMAIL_MULT_GROUP_FOLDER_ACCOUNTS'];
2655
2656             $type = $mod_strings['LBL_MAILBOX_TYPE_GROUP_FOLDER'];
2657                     $ieAccountsShowOptionsMeta[] = array("id" => $singleGroup['id'], "name" => $singleGroup['origName'], 'is_active' => $singleGroup['selected'],
2658                                                                                                         'server_url' => $server_url, 'is_group' => true,'group_id' => $singleGroup['id'],
2659                                                                                                         'is_default' => FALSE, 'has_groupfolder' => true,'type' => $type);
2660                 }
2661
2662
2663                 return $ieAccountsShowOptionsMeta;
2664         }
2665
2666         function getShowAccountsOptionsForSearch(&$ie) {
2667                 global $current_user;
2668                 global $app_strings;
2669
2670                 $ieAccountsFull = $ie->retrieveAllByGroupId($current_user->id);
2671                 //$ieAccountsShowOptions = "<option value=''>{$app_strings['LBL_NONE']}</option>\n";
2672                 $ieAccountsShowOptionsMeta = array();
2673                 $ieAccountsShowOptionsMeta[] = array("value" => "", "text" => $app_strings['LBL_NONE'], 'selected' => '');
2674                 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
2675
2676                 foreach($ieAccountsFull as $k => $v) {
2677                         if(!in_array($v->id, $showFolders)) {
2678                                 continue;
2679                         }
2680                         $group = (!$v->is_personal) ? $app_strings['LBL_EMAIL_GROUP']."." : "";
2681                         $ieAccountsShowOptionsMeta[] = array("value" => $v->id, "text" => $group.$v->name, 'protocol' => $v->protocol);
2682                 }
2683
2684                 return $ieAccountsShowOptionsMeta;
2685         }
2686         /**
2687          * Formats a display message on successful async call
2688          * @param string $type Type of message to display
2689          */
2690         function displaySuccessMessage($type) {
2691                 global $app_strings;
2692
2693                 switch($type) {
2694                         case "delete":
2695                                 $message = $app_strings['LBL_EMAIL_DELETE_SUCCESS'];
2696                         break;
2697
2698                         default:
2699                                 $message = "NOOP: invalid type";
2700                         break;
2701                 }
2702
2703                 $this->smarty->assign('app_strings', $app_strings);
2704                 $this->smarty->assign('message', $message);
2705                 echo $this->smarty->fetch("modules/Emails/templates/successMessage.tpl");
2706         }
2707
2708         /**
2709          * Validates existence and expiration of a cache file
2710          * @param string $ieId
2711          * @param string $type Type of cache file: folders, messages, etc.
2712          * @param string $file The cachefile name
2713          * @param int refreshOffset Refresh time in secs.
2714          * @return mixed.
2715          */
2716         function validCacheFileExists($ieId, $type, $file, $refreshOffset=-1) {
2717                 global $sugar_config;
2718
2719                 if($refreshOffset == -1) {
2720                         $refreshOffset = $this->cacheTimeouts[$type]; // use defaults
2721                 }
2722
2723                 $cacheFilePath = getcwd()."/{$sugar_config['cache_dir']}modules/Emails/{$ieId}/{$type}/{$file}";
2724                 if(file_exists($cacheFilePath)) {
2725                         return true;
2726                 }
2727
2728                 return false;
2729         }
2730
2731         /**
2732          * retrieves the cached value
2733          * @param string $ieId
2734          * @param string $type Type of cache file: folders, messages, etc.
2735          * @param string $file The cachefile name
2736          * @param string $key name of cache value
2737          * @return mixed
2738          */
2739         function getCacheValue($ieId, $type, $file, $key) {
2740                 global $sugar_config;
2741
2742                 $cacheFilePath = "{$sugar_config['cache_dir']}modules/Emails/{$ieId}/{$type}/{$file}";
2743                 $cacheFile = array();
2744
2745                 if(file_exists($cacheFilePath)) {
2746                         include($cacheFilePath); // provides $cacheFile
2747
2748                         if(isset($cacheFile[$key])) {
2749                                 $ret = unserialize($cacheFile[$key]);
2750                                 return $ret;
2751                         }
2752                 } else {
2753                         $GLOBALS['log']->debug("EMAILUI: cache file not found [ {$cacheFilePath} ] - creating blank cache file");
2754                         $this->writeCacheFile('retArr', array(), $ieId, $type, $file);
2755                 }
2756
2757                 return null;
2758         }
2759
2760         /**
2761          * retrieves the cache file last touched time
2762          * @param string $ieId
2763          * @param string $type Type of cache file: folders, messages, etc.
2764          * @param string $file The cachefile name
2765          * @return string
2766          */
2767         function getCacheTimestamp($ieId, $type, $file) {
2768                 global $sugar_config;
2769
2770                 $cacheFilePath = "{$sugar_config['cache_dir']}modules/Emails/{$ieId}/{$type}/{$file}";
2771                 $cacheFile = array();
2772
2773                 if(file_exists($cacheFilePath)) {
2774                         include($cacheFilePath); // provides $cacheFile['timestamp']
2775
2776                         if(isset($cacheFile['timestamp'])) {
2777                                 $GLOBALS['log']->debug("EMAILUI: found timestamp [ {$cacheFile['timestamp']} ]");
2778                                 return $cacheFile['timestamp'];
2779                         }
2780                 }
2781
2782                 return '';
2783         }
2784
2785         /**
2786          * Updates the timestamp for a cache file - usually to mark a "check email"
2787          * process
2788          * @param string $ieId
2789          * @param string $type Type of cache file: folders, messages, etc.
2790          * @param string $file The cachefile name
2791          */
2792         function setCacheTimestamp($ieId, $type, $file) {
2793                 global $sugar_config;
2794
2795                 $cacheFilePath = "{$sugar_config['cache_dir']}modules/Emails/{$ieId}/{$type}/{$file}";
2796                 $cacheFile = array();
2797
2798                 if(file_exists($cacheFilePath)) {
2799                         include($cacheFilePath); // provides $cacheFile['timestamp']
2800
2801                         if(isset($cacheFile['timestamp'])) {
2802                                 $cacheFile['timestamp'] = strtotime('now');
2803                                 $GLOBALS['log']->debug("EMAILUI: setting updated timestamp [ {$cacheFile['timestamp']} ]");
2804                                 return $this->_writeCacheFile($cacheFile, $cacheFilePath);
2805                         }
2806                 }
2807         }
2808
2809
2810         /**
2811          * Writes caches to flat file in cache dir.
2812          * @param string $key Key to the main cache entry (not timestamp)
2813          * @param mixed $var Variable to be cached
2814          * @param string $ieId I-E focus ID
2815          * @param string $type Folder in cache
2816          * @param string $file Cache file name
2817          */
2818         function writeCacheFile($key, $var, $ieId, $type, $file) {
2819                 global $sugar_config;
2820
2821                 $the_file = clean_path("{$sugar_config['cache_dir']}/modules/Emails/{$ieId}/{$type}/{$file}");
2822                 $timestamp = strtotime('now');
2823                 $array = array();
2824                 $array['timestamp'] = $timestamp;
2825                 $array[$key] = serialize($var); // serialized since varexport_helper() can't handle PHP objects
2826
2827                 return $this->_writeCacheFile($array, $the_file);
2828         }
2829
2830         /**
2831          * Performs the actual file write.  Abstracted from writeCacheFile() for
2832          * flexibility
2833          * @param array $array The array to write to the cache
2834          * @param string $file Full path (relative) with cache file name
2835          * @return bool
2836          */
2837         function _writeCacheFile($array, $file) {
2838                 global $sugar_config;
2839
2840                 $arrayString = var_export_helper($array);
2841
2842                 $date = date("r");
2843             $the_string =<<<eoq
2844 <?php // created: {$date}
2845         \$cacheFile = {$arrayString};
2846 ?>
2847 eoq;
2848             if($fh = @sugar_fopen($file, "w")) {
2849                 fputs($fh, $the_string);
2850                 fclose($fh);
2851                 return true;
2852             } else {
2853                 $GLOBALS['log']->debug("EMAILUI: Could not write cache file [ {$file} ]");
2854                 return false;
2855             }
2856         }
2857
2858         /**
2859          * Generate JSON encoded data to be consumed by yui datatable.
2860          *
2861          * @param array $data
2862          * @param string $resultsParam The resultsList name
2863          * @return string
2864          */
2865         function jsonOuput($data, $resultsParam, $count=0, $fromCache=true, $unread=-1) {
2866             global $app_strings;
2867
2868                 $count = ($count > 0) ? $count : 0;
2869
2870                 if(isset($a['fromCache']))
2871                         $cached = ($a['fromCache'] == 1) ? 1 : 0;
2872                 else
2873                         $cached = ($fromCache) ? 1 : 0;
2874
2875                 if($data['mbox'] == 'undefined' || empty($data['mbox']))
2876                         $data['mbox'] = $app_strings['LBL_NONE'];
2877
2878                 $jsonOut = array('TotalCount' => $count, 'FromCache' => $cached, 'UnreadCount' => $unread, $resultsParam => $data['out']);
2879
2880                 return json_encode($jsonOut);
2881         }
2882         /**
2883          * generates XML output from an array
2884          * @param array
2885          * @param string master list Item
2886          * @return string
2887          */
2888         function xmlOutput($a, $paramName, $count=0, $fromCache=true, $unread=-1) {
2889                 global $app_strings;
2890                 $count = ($count > 0) ? $count : 0;
2891
2892                 if(isset($a['fromCache'])) {
2893                         $cached = ($a['fromCache'] == 1) ? 1 : 0;
2894                 } else {
2895                         $cached = ($fromCache) ? 1 : 0;
2896                 }
2897
2898                 if($a['mbox'] == 'undefined' || empty($a['mbox'])) {
2899                         $a['mbox'] = $app_strings['LBL_NONE'];
2900                 }
2901
2902                 $xml = $this->arrayToXML($a['out'], $paramName);
2903
2904                 $ret =<<<eoq
2905 <?xml version="1.0" encoding="UTF-8"?>
2906 <EmailPage>
2907 <TotalCount>{$count}</TotalCount>
2908 <UnreadCount>{$unread}</UnreadCount>
2909 <FromCache> {$cached} </FromCache>
2910 <{$paramName}s>
2911 {$xml}
2912 </{$paramName}s>
2913 </EmailPage>
2914 eoq;
2915                 return $ret;
2916         }
2917
2918     /**
2919      * Generate to/cc addresses string in email detailview.
2920      *
2921      * @param string $str
2922      * @param string $target values: to, cc
2923      * @param int $defaultNum
2924      * @return string $str
2925      */
2926         function generateExpandableAddrs($str) {
2927             global $mod_strings;
2928             $tempStr = $str.',';
2929         $tempStr = html_entity_decode($tempStr);
2930             $tempStr = $this->unifyEmailString($tempStr);
2931         $defaultNum = 2;
2932         $pattern = '/@.*,/U';
2933         preg_match_all($pattern, $tempStr, $matchs);
2934         $totalCount = count($matchs[0]);
2935
2936         if(!empty($matchs[0]) && $totalCount > $defaultNum) {
2937             $position = strpos($tempStr, $matchs[0][$defaultNum]);
2938             $hiddenCount = $totalCount - $defaultNum;
2939             $frontStr = substr($tempStr, 0, $position);
2940             $backStr = substr($tempStr, $position, -1);
2941             $str = htmlentities($frontStr) . '<a class="utilsLink" onclick="javascript: SUGAR.email2.detailView.displayAllAddrs(this);">...['.$mod_strings['LBL_EMAIL_DETAIL_VIEW_SHOW'].$hiddenCount.$mod_strings['LBL_EMAIL_DETAIL_VIEW_MORE'].']</a><span style="display: none;">' .htmlentities($backStr).'</span>';
2942         }
2943
2944         return $str;
2945     }
2946
2947     /**
2948      * Unify the seperator as ,
2949      *
2950      * @param String $str email address string
2951      * @return String converted string
2952      */
2953     function unifyEmailString($str) {
2954         preg_match_all('/@.*;/U', $str, $matches);
2955         if(!empty($matches[0])) {
2956             foreach($matches[0] as $key => $value) {
2957                 $new[] = str_replace(";",",",$value);
2958             }
2959             return str_replace($matches[0], $new, $str);
2960         }
2961         return $str;
2962     }
2963 } // end class def