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