2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4 * SugarCRM Community Edition is a customer relationship management program developed by
5 * SugarCRM, Inc. Copyright (C) 2004-2012 SugarCRM Inc.
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.
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
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
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.
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.
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 ********************************************************************************/
38 /*********************************************************************************
41 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. All Rights
42 * Reserved. Contributor(s): ______________________________________..
43 *********************************************************************************/
45 require_once("include/ytree/Tree.php");
46 require_once("include/ytree/ExtNode.php");
47 require_once("include/SugarFolders/SugarFolders.php");
53 var $folder; // place holder for SugarFolder object
54 var $folderStates = array(); // array of folderPath names and their states (1/0)
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
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'";
76 $folderStateSerial = $current_user->getPreference('folderOpenState', 'Emails');
78 if(!empty($folderStateSerial)) {
79 $this->folderStates = unserialize($folderStateSerial);
82 $this->smarty = new Sugar_Smarty();
83 $this->folder = new SugarFolder();
84 $this->userCacheDir = sugar_cached("modules/Emails/{$current_user->id}");
85 $this->db = DBManagerFactory::getInstance();
89 ///////////////////////////////////////////////////////////////////////////
92 * Renders the frame for emails
94 function displayEmailFrame() {
96 require_once("include/OutboundEmail/OutboundEmail.php");
98 global $app_strings, $app_list_strings;
100 global $sugar_config;
101 global $current_user;
105 global $sugar_version;
106 global $sugar_flavor;
107 global $current_language;
108 global $server_unique_key;
110 $this->preflightUserCache();
111 $ie = new InboundEmail();
118 'unreadChecked' => 0,
122 $this->_generateComposeConfigData('email_compose');
125 //Check quick create module access
126 $QCAvailableModules = $this->_loadQuickCreateModules();
128 //Get the quickSearch js needed for assigned user id on Search Tab
129 require_once('include/QuickSearchDefaults.php');
130 $qsd = QuickSearchDefaults::getQuickSearchDefaults();
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);
139 ///////////////////////////////////////////////////////////////////////
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);
159 $e2UserPreferences = $this->getUserPrefsJS();
160 $emailSettings = $e2UserPreferences['emailSettings'];
162 ///////////////////////////////////////////////////////////////////////
164 // settings: accounts
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());
172 $ieAccounts = $ie->retrieveByGroupId($current_user->id);
173 $ieAccountsOptions = "<option value=''>{$app_strings['LBL_NONE']}</option>\n";
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";
181 $this->smarty->assign('ieAccounts', $ieAccountsOptions);
182 $this->smarty->assign('rollover', $this->rolloverStyle);
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'));
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');
197 'options' => $locale->getCharsetSelect(),
198 'selected' => $charsetSelectedValue,
200 $this->smarty->assign('charset', $charset);
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']));
208 //// END USER SETTINGS
209 ///////////////////////////////////////////////////////////////////////
211 ///////////////////////////////////////////////////////////////////////
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">
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">
225 $this->smarty->assign('signatureButtons', $signatureButtons);
226 $this->smarty->assign('signaturePrepend', $prependSignature == 'true' ? 'CHECKED' : '');
228 ///////////////////////////////////////////////////////////////////////
230 ///////////////////////////////////////////////////////////////////////
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 ///////////////////////////////////////////////////////////////////////
238 ///////////////////////////////////////////////////////////////////////
239 //// FOLDERS & TreeView
240 $this->smarty->assign('groupUserOptions', $ie->getGroupsWithSelectOptions(array('' => $app_strings['LBL_EMAIL_CREATE_NEW'])));
242 $tree = $this->getMailboxNodes();
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).";";
252 $preloadFolder .= "new Object();";
255 ///////////////////////////////////////////////////////////////////////
258 $out .= $this->smarty->fetch("modules/Emails/templates/_baseEmail.tpl");
259 $out .= $tree->generate_header();
260 $out .= $tree->generateNodesNoInit(true, 'email2treeinit');
262 <script type="text/javascript" language="javascript">
264 var loader = new YAHOO.util.YUILoader({
266 "layout", "element", "tabview", "menu",
267 "cookie", "sugarwidgets"
270 skin: { base: 'blank', defaultSkin: '' },
271 onSuccess: email2init,
273 base: "include/javascript/yui/build/"
276 name :"sugarwidgets",
278 fullpath: "include/javascript/sugarwidgets/SugarYUIWidgets.js",
279 varName: "YAHOO.SUGAR",
280 requires: ["datatable", "dragdrop", "treeview", "tabview", "calendar"]
294 * Generate the frame needed for the quick compose email UI. This frame is loaded dynamically
297 * @return JSON An object containing html markup and js script variables.
299 function displayQuickComposeEmailFrame()
301 $this->preflightUserCache();
303 $this->_generateComposeConfigData('email_compose_light');
304 $javascriptOut = $this->smarty->fetch("modules/Emails/templates/_baseConfigData.tpl");
306 $divOut = $this->smarty->fetch("modules/Emails/templates/overlay.tpl");
307 $divOut .= $this->smarty->fetch("modules/Emails/templates/addressSearchContent.tpl");
309 $outData = array('jsData' => $javascriptOut,'divData'=> $divOut);
310 $out = json_encode($outData);
315 * Load the modules from the metadata file and include in a custom one if it exists
319 protected function _loadQuickCreateModules()
321 $QCAvailableModules = array();
322 $QCModules = array();
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');
329 foreach($QCModules as $module) {
330 $seed = SugarModule::get($module)->loadBean();
331 if ( ( $seed instanceOf SugarBean ) && $seed->ACLAccess('edit') ) {
332 $QCAvailableModules[] = $module;
336 return $QCAvailableModules;
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
345 * @param String $emailLinkUrl
346 * @return JSON Object containing the composePackage and full link url
348 function generateComposePackageForQuickCreateFromComposeUrl($emailLinkUrl, $lazyLoad=false)
350 $composeData = explode("&",$emailLinkUrl);
351 $a_composeData = array();
352 foreach ($composeData as $singleRequest)
354 $tmp = explode("=",$singleRequest);
355 $a_composeData[$tmp[0]] = urldecode($tmp[1]);
358 return $this->generateComposePackageForQuickCreate($a_composeData,$emailLinkUrl, $lazyLoad);
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)
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 * @param SugarBean $bean Optional - the parent object bean with data
369 * @return JSON Object containg composePackage and fullLinkUrl
371 function generateComposePackageForQuickCreate($composeData,$fullLinkUrl, $lazyLoad=false, $bean = null)
373 $_REQUEST['forQuickCreate'] = true;
376 require_once('modules/Emails/Compose.php');
377 $composePackage = generateComposeDataPackage($composeData,FALSE, $bean);
379 $composePackage = $composeData;
382 // JSON object is passed into the function defined within the a href onclick event
383 // which is delimeted by '. Need to escape all single quotes and &, <, >
384 // but not double quotes since json would escape them
385 foreach ($composePackage as $key => $singleCompose)
387 if (is_string($singleCompose))
388 $composePackage[$key] = str_replace(" ", " ", from_html($singleCompose));
391 $quickComposeOptions = array('fullComposeUrl' => $fullLinkUrl,'composePackage' => $composePackage);
393 $j_quickComposeOptions = JSON::encode($quickComposeOptions, false ,true);
396 return $j_quickComposeOptions;
400 * Generate the config data needed for the Full Compose UI and the Quick Compose UI. The set of config data
401 * returned is the minimum set needed by the quick compose UI.
403 * @param String $type Drives which tinyMCE options will be included.
405 function _generateComposeConfigData($type = "email_compose_light" )
407 global $app_list_strings,$current_user, $app_strings, $mod_strings,$current_language,$locale;
410 $parent_types = $app_list_strings['record_type_display'];
411 $disabled_parent_types = ACLController::disabledModuleList($parent_types, false, 'list');
413 foreach($disabled_parent_types as $disabled_parent_type) {
414 unset($parent_types[$disabled_parent_type]);
416 asort($parent_types);
417 $linkBeans = json_encode(get_select_options_with_id($parent_types, ''));
420 require_once("include/SugarTinyMCE.php");
421 $tiny = new SugarTinyMCE();
422 $tinyConf = $tiny->getConfig($type);
424 //Generate Language Packs
425 $lang = "var app_strings = new Object();\n";
426 foreach($app_strings as $k => $v) {
427 if(strpos($k, 'LBL_EMAIL_') !== false) {
428 $lang .= "app_strings.{$k} = '{$v}';\n";
431 //Get the email mod strings but don't use the global variable as this may be overridden by
432 //other modules when the quick create is rendered.
433 $email_mod_strings = return_module_language($current_language,'Emails');
434 $modStrings = "var mod_strings = new Object();\n";
435 foreach($email_mod_strings as $k => $v) {
436 $v = str_replace("'", "\'", $v);
437 $modStrings .= "mod_strings.{$k} = '{$v}';\n";
439 $lang .= "\n\n{$modStrings}\n";
441 //Grab the Inboundemail language pack
442 $ieModStrings = "var ie_mod_strings = new Object();\n";
443 $ie_mod_strings = return_module_language($current_language,'InboundEmail');
444 foreach($ie_mod_strings as $k => $v) {
445 $v = str_replace("'", "\'", $v);
446 $ieModStrings .= "ie_mod_strings.{$k} = '{$v}';\n";
448 $lang .= "\n\n{$ieModStrings}\n";
450 $this->smarty->assign('linkBeans', $linkBeans);
451 $this->smarty->assign('linkBeansOptions', $parent_types);
452 $this->smarty->assign('tinyMCE', $tinyConf);
453 $this->smarty->assign('lang', $lang);
454 $this->smarty->assign('app_strings', $app_strings);
455 $this->smarty->assign('mod_strings', $email_mod_strings);
456 $ie1 = new InboundEmail();
459 $defsigID = $current_user->getPreference('signature_default');
460 $defaultSignature = $current_user->getDefaultSignature();
461 $sigJson = !empty($defaultSignature) ? json_encode(array($defaultSignature['id'] => from_html($defaultSignature['signature_html']))) : "new Object()";
462 $this->smarty->assign('defaultSignature', $sigJson);
463 $this->smarty->assign('signatureDefaultId', (isset($defaultSignature['id'])) ? $defaultSignature['id'] : "");
465 $this->smarty->assign('userPrefs', json_encode($this->getUserPrefsJS()));
467 //Get the users default outbound id
468 $defaultOutID = $ie1->getUsersDefaultOutboundServerId($current_user);
469 $this->smarty->assign('defaultOutID', $defaultOutID);
472 $charsets = json_encode($locale->getCharsetSelect());
473 $this->smarty->assign('emailCharsets', $charsets);
475 //Relateable List of People for address book search
477 $peopleTables = array("users",
482 $filterPeopleTables = array();
483 global $app_list_strings, $app_strings;
484 $filterPeopleTables['LBL_DROPDOWN_LIST_ALL'] = $app_strings['LBL_DROPDOWN_LIST_ALL'];
485 foreach($peopleTables as $table) {
486 $module = ucfirst($table);
487 $class = substr($module, 0, strlen($module) - 1);
488 require_once("modules/{$module}/{$class}.php");
489 $person = new $class();
491 if (!$person->ACLAccess('list')) continue;
492 $filterPeopleTables[$person->table_name] = $app_list_strings['moduleList'][$person->module_dir];
494 $this->smarty->assign('listOfPersons' , get_select_options_with_id($filterPeopleTables,''));
501 ///////////////////////////////////////////////////////////////////////////
503 ///////////////////////////////////////////////////////////////////////////
506 * Retrieves all relationship metadata for a user's address book
509 function getContacts() {
510 global $current_user;
512 $q = "SELECT * FROM address_book WHERE assigned_user_id = '{$current_user->id}' ORDER BY bean DESC";
513 $r = $this->db->query($q);
517 while($a = $this->db->fetchByAssoc($r)) {
518 $ret[$a['bean_id']] = array(
519 'id' => $a['bean_id'],
520 'module' => $a['bean'],
528 * Saves changes to a user's address book
529 * @param array contacts
531 function setContacts($contacts) {
532 global $current_user;
534 $oldContacts = $this->getContacts();
536 foreach($contacts as $cid => $contact) {
537 if(!in_array($contact['id'], $oldContacts)) {
538 $q = "INSERT INTO address_book (assigned_user_id, bean, bean_id) VALUES ('{$current_user->id}', '{$contact['module']}', '{$contact['id']}')";
539 $r = $this->db->query($q, true);
545 * Removes contacts from the user's address book
548 function removeContacts($ids) {
549 global $current_user;
553 foreach($ids as $id) {
557 $concat .= "'{$id}'";
560 $q = "DELETE FROM address_book WHERE assigned_user_id = '{$current_user->id}' AND bean_id IN ({$concat})";
561 $r = $this->db->query($q);
565 * saves editted Contact info
566 * @param string $str JSON serialized object
568 function saveContactEdit($str) {
570 $json = getJSONobj();
572 $str = from_html($str);
573 $obj = $json->decode($str);
575 $contact = new Contact();
576 $contact->retrieve($obj['contact_id']);
577 $contact->first_name = $obj['contact_first_name'];
578 $contact->last_name = $obj['contact_last_name'];
581 // handle email address changes
582 $addresses = array();
584 foreach($obj as $k => $req) {
585 if(strpos($k, 'emailAddress') !== false) {
586 $addresses[$k] = $req;
590 // prefill some REQUEST vars for emailAddress save
591 $_REQUEST['emailAddressOptOutFlag'] = $obj['optOut'];
592 $_REQUEST['emailAddressInvalidFlag'] = $obj['invalid'];
593 $contact->emailAddress->save($obj['contact_id'], 'Contacts', $addresses, $obj['primary'], '');
597 * Prepares the Edit Contact mini-form via template assignment
598 * @param string id ID of contact in question
599 * @param string module Module in focus
602 function getEditContact($id, $module) {
606 if(!class_exists("Contact")) {
610 $contact = new Contact();
611 $contact->retrieve($_REQUEST['id']);
614 if($contact->ACLAccess('edit')) {
615 $contactMeta = array();
616 $contactMeta['id'] = $contact->id;
617 $contactMeta['module'] = $contact->module_dir;
618 $contactMeta['first_name'] = $contact->first_name;
619 $contactMeta['last_name'] = $contact->last_name;
621 $this->smarty->assign("app_strings", $app_strings);
622 $this->smarty->assign("contact_strings", return_module_language($_SESSION['authenticated_user_language'], 'Contacts'));
623 $this->smarty->assign("contact", $contactMeta);
625 $ea = new SugarEmailAddress();
626 $newEmail = $ea->getEmailAddressWidgetEditView($id, $module, true);
627 $this->smarty->assign("emailWidget", $newEmail['html']);
629 $ret['form'] = $this->smarty->fetch("modules/Emails/templates/editContact.tpl");
630 $ret['prefillData'] = $newEmail['prefillData'];
633 $ret['form'] = $app_strings['LBL_EMAIL_ERROR_NO_ACCESS'];
634 $ret['prefillData'] = '{}';
638 $ret['contactName'] = $contact->full_name;
645 * Retrieves a concatenated list of contacts, those with assigned_user_id = user's id and those in the address_book
647 * @param array $contacts Array of contact types -> IDs
648 * @param object $user User in focus
651 function getUserContacts($contacts, $user=null) {
653 global $current_user;
657 $user = $current_user;
660 $emailAddress = new SugarEmailAddress();
666 foreach($contacts as $contact) {
667 if(!isset($modules[$contact['module']])) {
668 $modules[$contact['module']] = array();
670 $modules[$contact['module']][] = $contact;
673 foreach($modules as $module => $contacts) {
675 $union .= " UNION ALL ";
678 $table = strtolower($module);
681 foreach($contacts as $contact) {
682 if(!empty($idsSerial)) {
685 $idsSerial .= "'{$contact['id']}'";
688 $union .= "(SELECT id, first_name, last_name, title, '{$module}' module FROM {$table} WHERE id IN({$idsSerial}) AND deleted = 0 )";
691 $union .= " ORDER BY last_name";
694 $r = $user->db->query($union);
698 while($a = $user->db->fetchByAssoc($r)) {
701 $c['name'] = $locale->getLocaleFormattedName($a['first_name'], "<b>{$a['last_name']}</b>", '', $a['title'], '', $user);
703 $c['module'] = $a['module'];
704 $c['email'] = $emailAddress->getAddressesByGUID($a['id'], $a['module']);
710 //// END ADDRESS BOOK
711 ///////////////////////////////////////////////////////////////////////////
714 ///////////////////////////////////////////////////////////////////////////
715 //// EMAIL 2.0 Preferences
716 function getUserPrefsJS() {
717 global $current_user;
720 // sort order per mailbox view
721 $sortSerial = $current_user->getPreference('folderSortOrder', 'Emails');
722 $sortArray = array();
723 if(!empty($sortSerial)) {
724 $sortArray = unserialize($sortSerial);
727 // treeview collapsed/open states
728 $folderStateSerial = $current_user->getPreference('folderOpenState', 'Emails');
729 $folderStates = array();
730 if(!empty($folderStateSerial)) {
731 $folderStates = unserialize($folderStateSerial);
734 // subscribed accounts
735 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
738 $emailSettings = $current_user->getPreference('emailSettings', 'Emails');
740 if(empty($emailSettings)) {
741 $emailSettings = array();
742 $emailSettings['emailCheckInterval'] = -1;
743 $emailSettings['autoImport'] = '';
744 $emailSettings['alwaysSaveOutbound'] = '1';
745 $emailSettings['sendPlainText'] = '';
746 $emailSettings['defaultOutboundCharset'] = $GLOBALS['sugar_config']['default_email_charset'];
747 $emailSettings['showNumInList'] = 20;
751 $focusFolder = $current_user->getPreference('focusFolder', 'Emails');
752 $focusFolder = !empty($focusFolder) ? unserialize($focusFolder) : array();
755 $showUnreadOnly = $current_user->getPreference('showUnreadOnly', 'Emails');
757 $listViewSort = array(
759 "sortDirection" => 'DESC',
763 $signaturePrepend = $current_user->getPreference('signature_prepend') ? 'true' : 'false';
764 $signatureDefault = $current_user->getPreference('signature_default');
766 'signature_prepend' => $signaturePrepend,
767 'signature_default' => $signatureDefault
773 'emailAddresses' => $current_user->emailAddress->getAddressesByGUID($current_user->id, 'Users'),
774 'full_name' => from_html($current_user->full_name),
777 $userPreferences = array();
778 $userPreferences['sort'] = $sortArray;
779 $userPreferences['folderStates'] = $folderStates;
780 $userPreferences['showFolders'] = $showFolders;
781 $userPreferences['emailSettings'] = $emailSettings;
782 $userPreferences['focusFolder'] = $focusFolder;
783 $userPreferences['showUnreadOnly'] = $showUnreadOnly;
784 $userPreferences['listViewSort'] = $listViewSort;
785 $userPreferences['signatures'] = $signatures;
786 $userPreferences['current_user'] = $user;
787 return $userPreferences;
792 ///////////////////////////////////////////////////////////////////////////
793 //// FOLDER FUNCTIONS
796 * Creates a new Sugar folder
797 * @param string $nodeLabel New sugar folder name
798 * @param string $parentLabel Parent folder name
800 function saveNewFolder($nodeLabel, $parentId, $isGroup=0) {
801 global $current_user;
803 $this->folder->name = $nodeLabel;
804 $this->folder->is_group = $isGroup;
805 $this->folder->parent_folder = ($parentId == 'Home') ? "" : $parentId;
806 $this->folder->has_child = 0;
807 $this->folder->created_by = $current_user->id;
808 $this->folder->modified_by = $current_user->id;
809 $this->folder->date_modified = $this->folder->date_created = TimeDate::getInstance()->nowDb();
811 $this->folder->save();
813 'action' => 'newFolderSave',
814 'id' => $this->folder->id,
815 'name' => $this->folder->name,
816 'is_group' => $this->folder->is_group,
817 'is_dynamic' => $this->folder->is_dynamic
822 * Saves user sort prefernces
824 function saveListViewSortOrder($ieId, $focusFolder, $sortBy, $sortDir) {
825 global $current_user;
827 $sortArray = array();
829 $sortSerial = $current_user->getPreference('folderSortOrder', 'Emails');
830 if(!empty($sortSerial)) {
831 $sortArray = unserialize($sortSerial);
834 $sortArray[$ieId][$focusFolder]['current']['sort'] = $sortBy;
835 $sortArray[$ieId][$focusFolder]['current']['direction'] = $sortDir;
836 $sortSerial = serialize($sortArray);
837 $current_user->setPreference('folderSortOrder', $sortSerial, '', 'Emails');
841 * Stickies folder collapse/open state
843 function saveFolderOpenState($focusFolder, $focusFolderOpen) {
844 global $current_user;
846 $folderStateSerial = $current_user->getPreference('folderOpenState', 'Emails');
847 $folderStates = array();
849 if(!empty($folderStateSerial)) {
850 $folderStates = unserialize($folderStateSerial);
853 $folderStates[$focusFolder] = $focusFolderOpen;
854 $newFolderStateSerial = serialize($folderStates);
855 $current_user->setPreference('folderOpenState', $newFolderStateSerial, '', 'Emails');
859 * saves a folder's view state
861 function saveListView($ieId, $folder) {
862 global $current_user;
864 $saveState = array();
865 $saveState['ieId'] = $ieId;
866 $saveState['folder'] = $folder;
867 $saveStateSerial = serialize($saveState);
868 $current_user->setPreference('focusFolder', $saveStateSerial, '', 'Emails');
872 * Generates cache folder structure
874 function preflightEmailCache($cacheRoot) {
876 if(!file_exists($cacheRoot))
877 mkdir_recursive(clean_path($cacheRoot));
880 if(!file_exists($cacheRoot."/folders"))
881 mkdir_recursive(clean_path("{$cacheRoot}/folders"));
884 if(!file_exists($cacheRoot."/messages"))
885 mkdir_recursive(clean_path("{$cacheRoot}/messages"));
888 if(!file_exists($cacheRoot."/attachments"))
889 mkdir_recursive(clean_path("{$cacheRoot}/attachments"));
892 function deleteEmailCacheForFolders($cacheRoot) {
893 $filePath = $cacheRoot."/folders/folders.php";
894 if (file_exists($filePath)) {
898 ///////////////////////////////////////////////////////////////////////////
901 * Identifies subscribed mailboxes and empties the trash
902 * @param object $ie InboundEmail
904 function emptyTrash(&$ie) {
905 global $current_user;
907 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
909 if(is_array($showFolders)) {
910 foreach($showFolders as $ieId) {
912 $ie->retrieve($ieId);
920 * returns an array of nodes that correspond to IMAP mailboxes.
921 * @param bool $forceRefresh
922 * @return object TreeView object
924 function getMailboxNodes() {
925 global $sugar_config;
926 global $current_user;
929 $tree = new Tree("frameFolders");
930 $tree->tree_style= 'include/ytree/TreeView/css/check/tree.css';
933 $ie = new InboundEmail();
934 $refreshOffset = $this->cacheTimeouts['folders']; // 5 mins. this will be set via user prefs
936 $rootNode = new ExtNode($app_strings['LBL_EMAIL_HOME_FOLDER'], $app_strings['LBL_EMAIL_HOME_FOLDER']);
937 $rootNode->dynamicloadfunction = '';
938 $rootNode->expanded = true;
939 $rootNode->dynamic_load = true;
940 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
942 if(empty($showFolders)) {
943 $showFolders = array();
947 if($current_user->hasPersonalEmail()) {
948 $personals = $ie->retrieveByGroupId($current_user->id);
950 foreach($personals as $k => $personalAccount) {
951 if(in_array($personalAccount->id, $showFolders)) {
952 // check for cache value
953 $cacheRoot = sugar_cached("modules/Emails/{$personalAccount->id}");
954 $this->preflightEmailCache($cacheRoot);
956 if($this->validCacheFileExists($personalAccount->id, 'folders', "folders.php")) {
957 $mailboxes = $this->getMailBoxesFromCacheValue($personalAccount);
959 $mailboxes = $personalAccount->getMailboxes();
962 $acctNode = new ExtNode('Home::' . $personalAccount->name, $personalAccount->name);
963 $acctNode->dynamicloadfunction = '';
964 $acctNode->expanded = false;
965 $acctNode->set_property('cls', 'ieFolder');
966 $acctNode->set_property('ieId', $personalAccount->id);
967 $acctNode->set_property('protocol', $personalAccount->protocol);
969 if(array_key_exists('Home::'.$personalAccount->name, $this->folderStates)) {
970 if($this->folderStates['Home::'.$personalAccount->name] == 'open') {
971 $acctNode->expanded = true;
974 $acctNode->dynamic_load = true;
976 $nodePath = $acctNode->_properties['id'];
978 foreach($mailboxes as $k => $mbox) {
979 $acctNode->add_node($this->buildTreeNode($k, $k, $mbox, $personalAccount->id,
980 $nodePath, false, $personalAccount));
983 $rootNode->add_node($acctNode);
989 $beans = $ie->retrieveAllByGroupId($current_user->id, false);
990 foreach($beans as $k => $groupAccount) {
991 if(in_array($groupAccount->id, $showFolders)) {
992 // check for cache value
993 $cacheRoot = sugar_cached("modules/Emails/{$groupAccount->id}");
994 $this->preflightEmailCache($cacheRoot);
995 //$groupAccount->connectMailserver();
997 if($this->validCacheFileExists($groupAccount->id, 'folders', "folders.php")) {
998 $mailboxes = $this->getMailBoxesFromCacheValue($groupAccount);
1000 $mailboxes = $groupAccount->getMailBoxesForGroupAccount();
1003 $acctNode = new ExtNode($groupAccount->name, "group.{$groupAccount->name}");
1004 $acctNode->dynamicloadfunction = '';
1005 $acctNode->expanded = false;
1006 $acctNode->set_property('isGroup', 'true');
1007 $acctNode->set_property('ieId', $groupAccount->id);
1008 $acctNode->set_property('protocol', $groupAccount->protocol);
1010 if(array_key_exists('Home::'.$groupAccount->name, $this->folderStates)) {
1011 if($this->folderStates['Home::'.$groupAccount->name] == 'open') {
1012 $acctNode->expanded = true;
1015 $acctNode->dynamic_load = true;
1016 $nodePath = $rootNode->_properties['id']."::".$acctNode->_properties['id'];
1018 foreach($mailboxes as $k => $mbox) {
1019 $acctNode->add_node($this->buildTreeNode($k, $k, $mbox, $groupAccount->id,
1020 $nodePath, true, $groupAccount));
1023 $rootNode->add_node($acctNode);
1027 // SugarFolder nodes
1028 /* SugarFolders are built at onload when the UI renders */
1030 $tree->add_node($rootNode);
1034 function getMailBoxesFromCacheValue($mailAccount) {
1035 $foldersCache = $this->getCacheValue($mailAccount->id, 'folders', "folders.php", 'foldersCache');
1036 $mailboxes = $foldersCache['mailboxes'];
1037 $mailboxesArray = $mailAccount->generateFlatArrayFromMultiDimArray($mailboxes, $mailAccount->retrieveDelimiter());
1038 $mailAccount->saveMailBoxFolders($mailboxesArray);
1039 $this->deleteEmailCacheForFolders($cacheRoot);
1044 * Builds up a TreeView Node object
1048 * @param string ID of InboundEmail instance
1049 * @param string nodePath Serialized path from root node to current node
1050 * @param bool isGroup
1051 * @param bool forceRefresh
1054 function buildTreeNode($key, $label, $mbox, $ieId, $nodePath, $isGroup, $ie) {
1055 global $sugar_config;
1057 // get unread counts
1058 $exMbox = explode("::", $nodePath);
1060 $GLOBALS['log']->debug("$key --- $nodePath::$label");
1062 if(count($exMbox) >= 2) {
1064 for($i=2; $i<count($exMbox); $i++) {
1065 if($mailbox != "") {
1068 $mailbox .= "{$exMbox[$i]}";
1071 $mailbox = substr($key, strpos($key, '.'));
1073 $unseen = $this->getUnreadCount($ie, $mailbox);
1076 //$label = " <span id='span{$ie->id}{$ie->mailbox}' style='font-weight:bold'>{$label} (<span id='span{$ie->id}{$ie->mailbox}nums'>{$unseen}</span>)</span>";
1080 $nodePath = $nodePath."::".$label;
1081 $node = new ExtNode($nodePath, $label);
1082 $node->dynamicloadfunction = '';
1083 $node->expanded = false;
1084 $node->set_property('labelStyle', "remoteFolder");
1087 if(array_key_exists($nodePath, $this->folderStates)) {
1088 if($this->folderStates[$nodePath] == 'open') {
1089 $node->expanded = true;
1093 $group = ($isGroup) ? 'true' : 'false';
1094 $node->dynamic_load = true;
1095 //$node->set_property('href', " SUGAR.email2.listView.populateListFrame(YAHOO.namespace('frameFolders').selectednode, '{$ieId}', 'false');");
1096 $node->set_property('isGroup', $group);
1097 $node->set_property('isDynamic', 'false');
1098 $node->set_property('ieId', $ieId);
1099 $node->set_property('mbox', $key);
1100 $node->set_property('unseen', $unseen);
1101 $node->set_property('cls', 'ieFolder');
1103 if(is_array($mbox)) {
1104 foreach($mbox as $k => $v) {
1105 $node->add_node($this->buildTreeNode("$key.$k", $k, $v, $ieId, $nodePath, $isGroup, $ie));
1113 * Totals the unread emails
1115 function getUnreadCount(&$ie, $mailbox) {
1116 global $sugar_config;
1120 return $ie->getCacheUnreadCount($mailbox);
1123 ///////////////////////////////////////////////////////////////////////////
1126 * Used exclusively by draft code. Returns Notes and Documents as attachments.
1130 function getDraftAttachments($ret) {
1133 // $ret['uid'] is the draft Email object's GUID
1134 $ret['attachments'] = array();
1136 $q = "SELECT id, filename FROM notes WHERE parent_id = '{$ret['uid']}' AND deleted = 0";
1137 $r = $db->query($q);
1139 while($a = $db->fetchByAssoc($r)) {
1140 $ret['attachments'][$a['id']] = array(
1142 'filename' => $a['filename'],
1149 function createCopyOfInboundAttachment($ie, $ret, $uid) {
1150 global $sugar_config;
1151 if ($ie->isPop3Protocol()) {
1152 // get the UIDL from database;
1153 $cachedUIDL = md5($uid);
1154 $cache = sugar_cached("modules/Emails/{$ie->id}/messages/{$ie->mailbox}{$cachedUIDL}.php");
1156 $cache = sugar_cached("modules/Emails/{$ie->id}/messages/{$ie->mailbox}{$uid}.php");
1158 if(file_exists($cache)) {
1159 include($cache); // profides $cacheFile
1160 $metaOut = unserialize($cacheFile['out']);
1161 $meta = $metaOut['meta']['email'];
1162 if (isset($meta['attachments'])) {
1163 $attachmentHtmlData = $meta['attachments'];
1164 $actualAttachmentInfo = array();
1165 $this->parseAttachmentInfo($actualAttachmentInfo, $attachmentHtmlData);
1166 if (sizeof($actualAttachmentInfo) > 0) {
1167 foreach($actualAttachmentInfo as $key => $value) {
1168 $info_vars = array();
1169 parse_str($value, $info_vars);
1170 $fileName = $info_vars['tempName'];
1171 $attachmentid = $info_vars['id'];
1172 $guid = create_guid();
1173 $destination = clean_path("{$this->userCacheDir}/{$guid}");
1175 $attachmentFilePath = sugar_cached("modules/Emails/{$ie->id}/attachments/{$attachmentid}");
1176 copy($attachmentFilePath, $destination);
1177 $ret['attachments'][$guid] = array();
1178 $ret['attachments'][$guid]['id'] = $guid . $fileName;
1179 $ret['attachments'][$guid]['filename'] = $fileName;
1189 function parseAttachmentInfo(&$actualAttachmentInfo, $attachmentHtmlData) {
1190 $downLoadPHP = strpos($attachmentHtmlData, "index.php?entryPoint=download&");
1191 while ($downLoadPHP) {
1192 $attachmentHtmlData = substr($attachmentHtmlData, $downLoadPHP+30);
1193 $final = strpos($attachmentHtmlData, "\">");
1194 $actualAttachmentInfo[] = substr($attachmentHtmlData, 0, $final);
1195 $attachmentHtmlData = substr($attachmentHtmlData, $final);
1196 $downLoadPHP = strpos($attachmentHtmlData, "index.php?entryPoint=download&");
1200 * Renders the QuickCreate form from Smarty and returns HTML
1201 * @param array $vars request variable global
1202 * @param object $email Fetched email object
1203 * @param bool $addToAddressBook
1206 function getQuickCreateForm($vars, $email, $addToAddressBookButton=false) {
1207 require_once("include/EditView/EditView2.php");
1208 global $app_strings;
1209 global $mod_strings;
1210 global $current_user;
1213 global $current_language;
1215 //Setup the current module languge
1216 $mod_strings = return_module_language($current_language, $_REQUEST['qc_module']);
1218 $bean = $beanList[$_REQUEST['qc_module']];
1219 $class = $beanFiles[$bean];
1220 require_once($class);
1222 $focus = new $bean();
1228 $emailAddress = array();
1231 if(in_array($bean, $people)) {
1233 $focus->lead_source = 'Email';
1234 $focus->lead_source_description = trim($email->name);
1236 $from = (isset($email->from_name) && !empty($email->from_name)) ? $email->from_name : $email->from_addr;
1238 if(isset($_REQUEST['sugarEmail']) && !empty($_REQUEST['sugarEmail']))
1239 $from = (isset($email->to_addrs_names) && !empty($email->to_addrs_names)) ? $email->to_addrs_names : $email->to_addrs;
1242 $name = explode(" ", trim($from));
1244 $address = trim(array_pop($name));
1245 $address = str_replace(array("<",">","<",">"), "", $address);
1247 $emailAddress[] = array(
1248 'email_address' => $address,
1249 'primary_address' => 1,
1250 'invalid_email' => 0,
1252 'reply_to_address' => 1
1255 $focus->email1 = $address;
1258 $focus->last_name = trim(array_pop($name));
1260 foreach($name as $first) {
1261 if(!empty($focus->first_name)) {
1262 $focus->first_name .= " ";
1264 $focus->first_name .= trim($first);
1268 // bugs, cases, tasks
1269 $focus->name = trim($email->name);
1272 $focus->description = trim(strip_tags($email->description));
1273 $focus->assigned_user_id = $current_user->id;
1276 $EditView = new EditView();
1277 $EditView->ss = new Sugar_Smarty();
1278 //MFH BUG#20283 - checks for custom quickcreate fields
1279 $EditView->setup($_REQUEST['qc_module'], $focus, 'custom/modules/'.$focus->module_dir.'/metadata/editviewdefs.php', 'include/EditView/EditView.tpl');
1280 $EditView->process();
1281 $EditView->render();
1283 $EditView->defs['templateMeta']['form']['buttons'] = array(
1284 'email2save' => array(
1285 'id' => 'e2AjaxSave',
1286 'customCode' => '<input type="button" class="button" value=" '.$app_strings['LBL_SAVE_BUTTON_LABEL']
1287 . ' " onclick="SUGAR.email2.detailView.saveQuickCreate(false);" />'
1289 'email2saveandreply' => array(
1290 'id' => 'e2SaveAndReply',
1291 'customCode' => '<input type="button" class="button" value=" '.$app_strings['LBL_EMAIL_SAVE_AND_REPLY']
1292 . ' " onclick="SUGAR.email2.detailView.saveQuickCreate(\'reply\');" />'
1294 'email2cancel' => array(
1296 'customCode' => '<input type="button" class="button" value=" '.$app_strings['LBL_EMAIL_CANCEL']
1297 . ' " onclick="SUGAR.email2.detailView.quickCreateDialog.hide();" />'
1302 if($addToAddressBookButton) {
1303 $EditView->defs['templateMeta']['form']['buttons']['email2saveAddToAddressBook'] = array(
1304 'id' => 'e2addToAddressBook',
1305 'customCode' => '<input type="button" class="button" value=" '.$app_strings['LBL_EMAIL_ADDRESS_BOOK_SAVE_AND_ADD']
1306 . ' " onclick="SUGAR.email2.detailView.saveQuickCreate(true);" />'
1310 //Get the module language for javascript
1311 if(!is_file(sugar_cached('jsLanguage/') . $_REQUEST['qc_module'] . '/' . $GLOBALS['current_language'] . '.js')) {
1312 require_once('include/language/jsLanguage.php');
1313 jsLanguage::createModuleStringsCache($_REQUEST['qc_module'], $GLOBALS['current_language']);
1315 $jsLanguage = getVersionedScript("cache/jsLanguage/{$_REQUEST['qc_module']}/{$GLOBALS['current_language']}.js", $GLOBALS['sugar_config']['js_lang_version']);
1318 $EditView->view = 'EmailQCView';
1319 $EditView->defs['templateMeta']['form']['headerTpl'] = 'include/EditView/header.tpl';
1320 $EditView->defs['templateMeta']['form']['footerTpl'] = 'include/EditView/footer.tpl';
1322 $meta['html'] = $jsLanguage . $EditView->display(false, true);
1323 $meta['html'] = str_replace("src='".getVersionedPath('include/SugarEmailAddress/SugarEmailAddress.js')."'", '', $meta['html']);
1324 $meta['emailAddress'] = $emailAddress;
1326 $mod_strings = return_module_language($current_language, 'Emails');
1332 * Renders the Import form from Smarty and returns HTML
1333 * @param array $vars request variable global
1334 * @param object $email Fetched email object
1335 * @param bool $addToAddressBook
1338 function getImportForm($vars, $email, $formName = 'ImportEditView') {
1339 require_once("include/EditView/EditView2.php");
1340 require_once("include/TemplateHandler/TemplateHandler.php");
1341 require_once('include/QuickSearchDefaults.php');
1342 $qsd = QuickSearchDefaults::getQuickSearchDefaults();
1343 $qsd->setFormName($formName);
1345 global $app_strings;
1346 global $current_user;
1347 global $app_list_strings;
1348 $sqs_objects = array(
1349 "{$formName}_parent_name" => $qsd->getQSParent(),
1351 $smarty = new Sugar_Smarty();
1352 $smarty->assign("APP",$app_strings);
1353 $smarty->assign('formName',$formName);
1354 $showAssignTo = false;
1355 if (!isset($vars['showAssignTo']) || $vars['showAssignTo'] == true) {
1356 $showAssignTo = true;
1358 if ($showAssignTo) {
1359 if(empty($email->assigned_user_id) && empty($email->id))
1360 $email->assigned_user_id = $current_user->id;
1361 if(empty($email->assigned_name) && empty($email->id))
1362 $email->assigned_user_name = $current_user->user_name;
1363 $sqs_objects["{$formName}_assigned_user_name"] = $qsd->getQSUser();
1365 $smarty->assign("showAssignedTo",$showAssignTo);
1367 $showDelete = false;
1368 if (!isset($vars['showDelete']) || $vars['showDelete'] == true) {
1371 $smarty->assign("showDelete",$showDelete);
1373 $smarty->assign("userId",$email->assigned_user_id);
1374 $smarty->assign("userName",$email->assigned_user_name);
1375 $parent_types = $app_list_strings['record_type_display'];
1376 $smarty->assign('parentOptions', get_select_options_with_id($parent_types, $email->parent_type));
1378 $quicksearch_js = '<script type="text/javascript" language="javascript">sqs_objects = ' . json_encode($sqs_objects) . '</script>';
1379 $smarty->assign('SQS', $quicksearch_js);
1382 $meta['html'] = $smarty->fetch("modules/Emails/templates/importRelate.tpl");
1387 * This function returns the detail view for email in new 2.0 interface
1390 function getDetailViewForEmail2($emailId) {
1392 require_once('include/DetailView/DetailView.php');
1393 global $app_strings, $app_list_strings;
1394 global $mod_strings;
1396 $smarty = new Sugar_Smarty();
1399 $focus = new Email();
1400 $focus->retrieve($emailId);
1401 $detailView->ss = new Sugar_Smarty();
1402 $detailView = new DetailView();
1405 if($focus->type == 'out') {
1406 $title = getClassicModuleTitle('Emails', array($mod_strings['LBL_SENT_MODULE_NAME'],$focus->name), true);
1407 } elseif ($focus->type == 'draft') {
1408 $title = getClassicModuleTitle('Emails', array($mod_strings['LBL_LIST_FORM_DRAFTS_TITLE'],$focus->name), true);
1409 } elseif($focus->type == 'inbound') {
1410 $title = getClassicModuleTitle('Emails', array($mod_strings['LBL_INBOUND_TITLE'],$focus->name), true);
1412 $smarty->assign("emailTitle", $title);
1414 // DEFAULT TO TEXT IF NO HTML CONTENT:
1415 $html = trim(from_html($focus->description_html));
1417 $smarty->assign('SHOW_PLAINTEXT', 'true');
1419 $smarty->assign('SHOW_PLAINTEXT', 'false');
1422 //if not empty or set to test (from test campaigns)
1423 if (!empty($focus->parent_type) && $focus->parent_type !='test') {
1424 $smarty->assign('PARENT_MODULE', $focus->parent_type);
1425 $smarty->assign('PARENT_TYPE', $app_list_strings['record_type_display'][$focus->parent_type] . ":");
1429 $smarty->assign('MOD', $mod_strings);
1430 $smarty->assign('APP', $app_strings);
1431 $smarty->assign('GRIDLINE', $gridline);
1432 $smarty->assign('PRINT_URL', 'index.php?'.$GLOBALS['request_string']);
1433 $smarty->assign('ID', $focus->id);
1434 $smarty->assign('TYPE', $focus->type);
1435 $smarty->assign('PARENT_NAME', $focus->parent_name);
1436 $smarty->assign('PARENT_ID', $focus->parent_id);
1437 $smarty->assign('NAME', $focus->name);
1438 $smarty->assign('ASSIGNED_TO', $focus->assigned_user_name);
1439 $smarty->assign('DATE_MODIFIED', $focus->date_modified);
1440 $smarty->assign('DATE_ENTERED', $focus->date_entered);
1441 $smarty->assign('DATE_START', $focus->date_start);
1442 $smarty->assign('TIME_START', $focus->time_start);
1443 $smarty->assign('FROM', $focus->from_addr);
1444 $smarty->assign('TO', nl2br($focus->to_addrs));
1445 $smarty->assign('CC', nl2br($focus->cc_addrs));
1446 $smarty->assign('BCC', nl2br($focus->bcc_addrs));
1447 $smarty->assign('CREATED_BY', $focus->created_by_name);
1448 $smarty->assign('MODIFIED_BY', $focus->modified_by_name);
1449 $smarty->assign('DATE_SENT', $focus->date_entered);
1450 $smarty->assign('EMAIL_NAME', 'RE: '.$focus->name);
1451 $smarty->assign("TAG", $focus->listviewACLHelper());
1452 $smarty->assign("SUGAR_VERSION", $GLOBALS['sugar_version']);
1453 $smarty->assign("JS_CUSTOM_VERSION", $GLOBALS['sugar_config']['js_custom_version']);
1454 if(!empty($focus->reply_to_email)) {
1457 <td class=\"tabDetailViewDL\"><slot>".$mod_strings['LBL_REPLY_TO_NAME']."</slot></td>
1458 <td colspan=3 class=\"tabDetailViewDF\"><slot>".$focus->reply_to_addr."</slot></td>
1460 $smarty->assign("REPLY_TO", $replyTo);
1462 ///////////////////////////////////////////////////////////////////////////////
1463 //// JAVASCRIPT VARS
1465 $jsVars .= "var showRaw = '{$mod_strings['LBL_BUTTON_RAW_LABEL']}';";
1466 $jsVars .= "var hideRaw = '{$mod_strings['LBL_BUTTON_RAW_LABEL_HIDE']}';";
1467 $smarty->assign("JS_VARS", $jsVars);
1468 ///////////////////////////////////////////////////////////////////////////////
1469 //// NOTES (attachements, etc.)
1470 ///////////////////////////////////////////////////////////////////////////////
1473 $where = "notes.parent_id='{$focus->id}'";
1474 //take in account if this is from campaign and the template id is stored in the macros.
1476 if(isset($macro_values) && isset($macro_values['email_template_id'])){
1477 $where = "notes.parent_id='{$macro_values['email_template_id']}'";
1479 $notes_list = $note->get_full_list("notes.name", $where, true);
1481 if(! isset($notes_list)) {
1482 $notes_list = array();
1486 for($i=0; $i<count($notes_list); $i++) {
1487 $the_note = $notes_list[$i];
1488 $attachments .= "<a href=\"index.php?entryPoint=download&id={$the_note->id}&type=Notes\">".$the_note->name."</a><br />";
1489 $focus->cid2Link($the_note->id, $the_note->file_mime_type);
1491 $smarty->assign('DESCRIPTION', nl2br($focus->description));
1492 $smarty->assign('DESCRIPTION_HTML', from_html($focus->description_html));
1493 $smarty->assign("ATTACHMENTS", $attachments);
1494 ///////////////////////////////////////////////////////////////////////////////
1496 ///////////////////////////////////////////////////////////////////////////////
1497 $show_subpanels = true;
1498 if ($show_subpanels) {
1499 require_once('include/SubPanel/SubPanelTiles.php');
1500 $subpanel = new SubPanelTiles($focus, 'Emails');
1501 $smarty->assign("SUBPANEL", $subpanel->display());
1503 $meta['html'] = $smarty->fetch("modules/Emails/templates/emailDetailView.tpl");
1509 * Sets the "read" flag in the overview cache
1511 function setReadFlag($ieId, $mbox, $uid) {
1512 $this->markEmails('read', $ieId, $mbox, $uid);
1516 * Marks emails with the passed flag type. This will be applied to local
1517 * cache files as well as remote emails.
1518 * @param string $type Flag type
1519 * @param string $ieId
1520 * @param string $folder IMAP folder structure or SugarFolder GUID
1521 * @param string $uids Comma sep list of UIDs or GUIDs
1523 function markEmails($type, $ieId, $folder, $uids) {
1525 global $app_strings;
1526 $uids = $this->_cleanUIDList($uids);
1527 $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
1529 if(strpos($folder, 'sugar::') !== false) {
1530 // dealing with a sugar email object, uids are GUIDs
1531 foreach($exUids as $id) {
1532 $email = new Email();
1533 $email->retrieve($id);
1537 $email->status = 'unread';
1542 $email->status = 'read';
1551 $email->flagged = 1;
1556 $email->flagged = 0;
1563 /* dealing with IMAP email, uids are IMAP uids */
1564 global $ie; // provided by EmailUIAjax.php
1567 $ie = new InboundEmail();
1569 $ie->retrieve($ieId);
1570 $ie->mailbox = $folder;
1571 $ie->connectMailserver();
1573 if($type == 'deleted') {
1574 $ie->deleteMessageOnMailServer($uids);
1575 $ie->deleteMessageFromCache($uids);
1577 $overviews = $ie->getCacheValueForUIDs($ie->mailbox, $exUids);
1578 $manipulated = array();
1580 foreach($overviews['retArr'] as $k => $overview) {
1581 if(in_array($overview->uid, $exUids)) {
1584 $overview->seen = 0;
1588 $overview->seen = 1;
1592 $overview->flagged = 1;
1596 $overview->flagged = 0;
1599 $manipulated[] = $overview;
1603 if(!empty($manipulated)) {
1604 $ie->setCacheValue($ie->mailbox, array(), $manipulated);
1605 /* now mark emails on email server */
1606 $ie->markEmails(implode(",", explode($app_strings['LBL_EMAIL_DELIMITER'], $uids)), $type);
1608 } // end not type == deleted
1612 function doAssignment($distributeMethod, $ieid, $folder, $uids, $users) {
1613 global $app_strings;
1614 $users = explode(",", $users);
1615 $emailIds = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
1617 if($folder != 'sugar::Emails') {
1618 $emailIds = array();
1619 $uids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
1620 $ie = new InboundEmail();
1621 $ie->retrieve($ieid);
1623 // dealing with an inbound email data so we need to import an email and then
1624 foreach($uids as $uid) {
1625 $ie->mailbox = $folder;
1626 $ie->connectMailserver();
1628 if (!$ie->isPop3Protocol()) {
1629 $msgNo = imap_msgno($ie->conn, $uid);
1631 $msgNo = $ie->getCorrectMessageNoForPop3($uid);
1634 if(!empty($msgNo)) {
1635 if ($ie->importOneEmail($msgNo, $uid)) {
1636 $emailIds[] = $ie->email->id;
1637 $ie->deleteMessageOnMailServer($uid);
1638 //$ie->retrieve($ieid);
1639 //$ie->connectMailserver();
1640 $ie->mailbox = $folder;
1641 $ie->deleteMessageFromCache(($uids[] = $uid));
1643 $out = $out . "Message No : " . $messageIndex . " failed. Reason : Message already imported \r\n";
1650 if (count($emailIds) > 0) {
1651 $this->doDistributionWithMethod($users, $emailIds, $distributeMethod);
1657 * get team id and team set id from request
1660 function getTeams() {
1663 function doDistributionWithMethod($users, $emailIds, $distributionMethod) {
1664 // we have users and the items to distribute
1665 if($distributionMethod == 'roundRobin') {
1666 $this->distRoundRobin($users, $emailIds);
1667 } elseif($distributionMethod == 'leastBusy') {
1668 $this->distLeastBusy($users, $emailIds);
1669 } elseif($distributionMethod == 'direct') {
1670 if(count($users) > 1) {
1671 // only 1 user allowed in direct assignment
1675 $this->distDirect($user, $emailIds);
1682 * distributes emails to users on Round Robin basis
1683 * @param $userIds array of users to dist to
1684 * @param $mailIds array of email ids to push on those users
1685 * @return boolean true on success
1687 function distRoundRobin($userIds, $mailIds) {
1688 // check if we have a 'lastRobin'
1689 $lastRobin = $userIds[0];
1690 foreach($mailIds as $k => $mailId) {
1691 $userIdsKeys = array_flip($userIds); // now keys are values
1692 $thisRobinKey = $userIdsKeys[$lastRobin] + 1;
1693 if(!empty($userIds[$thisRobinKey])) {
1694 $thisRobin = $userIds[$thisRobinKey];
1695 $lastRobin = $userIds[$thisRobinKey];
1697 $thisRobin = $userIds[0];
1698 $lastRobin = $userIds[0];
1701 $email = new Email();
1702 $email->retrieve($mailId);
1703 $email->assigned_user_id = $thisRobin;
1704 $email->status = 'unread';
1712 * distributes emails to users on Least Busy basis
1713 * @param $userIds array of users to dist to
1714 * @param $mailIds array of email ids to push on those users
1715 * @return boolean true on success
1717 function distLeastBusy($userIds, $mailIds) {
1718 foreach($mailIds as $k => $mailId) {
1719 $email = new Email();
1720 $email->retrieve($mailId);
1721 foreach($userIds as $k => $id) {
1722 $r = $this->db->query("SELECT count(*) AS c FROM emails WHERE assigned_user_id = '.$id.' AND status = 'unread'");
1723 $a = $this->db->fetchByAssoc($r);
1724 $counts[$id] = $a['c'];
1726 asort($counts); // lowest to highest
1727 $countsKeys = array_flip($counts); // keys now the 'count of items'
1728 $leastBusy = array_shift($countsKeys); // user id of lowest item count
1729 $email->assigned_user_id = $leastBusy;
1730 $email->status = 'unread';
1737 * distributes emails to 1 user
1738 * @param $user users to dist to
1739 * @param $mailIds array of email ids to push
1740 * @return boolean true on success
1742 function distDirect($user, $mailIds) {
1743 foreach($mailIds as $k => $mailId) {
1744 $email = new Email();
1745 $email->retrieve($mailId);
1746 $email->assigned_user_id = $user;
1747 $email->status = 'unread';
1754 function getAssignedEmailsCountForUsers($userIds) {
1756 foreach($userIds as $id) {
1757 $r = $this->db->query("SELECT count(*) AS c FROM emails WHERE assigned_user_id = '$id' AND status = 'unread'");
1758 $a = $this->db->fetchByAssoc($r);
1759 $counts[$id] = $a['c'];
1764 function getLastRobin($ie) {
1766 if($this->validCacheFileExists($ie->id, 'folders', "robin.cache.php")) {
1767 $lastRobin = $this->getCacheValue($ie->id, 'folders', "robin.cache.php", 'robin');
1772 function setLastRobin($ie, $lastRobin) {
1773 global $sugar_config;
1774 $cacheFolderPath = sugar_cached("modules/Emails/{$ie->id}/folders");
1775 if (!file_exists($cacheFolderPath)) {
1776 mkdir_recursive($cacheFolderPath);
1778 $this->writeCacheFile('robin', $lastRobin, $ie->id, 'folders', "robin.cache.php");
1782 * returns the metadata defining a single email message for display. Uses cache file if it exists
1785 function getSingleMessage($ie) {
1788 global $app_strings,$mod_strings;
1789 $ie->retrieve($_REQUEST['ieId']);
1792 $ie->mailbox = $_REQUEST['mbox'];
1793 $filename = $_REQUEST['mbox'].$_REQUEST['uid'].".php";
1795 if ($ie->isPop3Protocol()) {
1796 $md5uidl = md5($_REQUEST['uid']);
1797 $filename = $_REQUEST['mbox'].$md5uidl.".php";
1800 if($this->validCacheFileExists($_REQUEST['ieId'], 'messages', $filename)) {
1801 $out = $this->getCacheValue($_REQUEST['ieId'], 'messages', $filename, 'out');
1804 // something fubar'd the cache?
1805 if(empty($out['meta']['email']['name']) && empty($out['meta']['email']['description'])) {
1808 // When sending data from cache, convert date into users preffered format
1809 $dateTimeInGMTFormat = $out['meta']['email']['date_start'];
1810 $out['meta']['email']['date_start'] = $timedate->to_display_date_time($dateTimeInGMTFormat);
1815 $writeToCacheFile = true;
1816 if ($ie->isPop3Protocol()) {
1817 $status = $ie->setEmailForDisplay($_REQUEST['uid'], true, true, true);
1819 $status = $ie->setEmailForDisplay($_REQUEST['uid'], false, true, true);
1821 $out = $ie->displayOneEmail($_REQUEST['uid'], $_REQUEST['mbox']);
1822 // modify the out object to store date in GMT format on the local cache file
1823 $dateTimeInUserFormat = $out['meta']['email']['date_start'];
1824 $out['meta']['email']['date_start'] = $timedate->to_db($dateTimeInUserFormat);
1825 if ($status == 'error') {
1826 $writeToCacheFile = false;
1828 if ($writeToCacheFile) {
1829 if ($ie->isPop3Protocol()) {
1830 $this->writeCacheFile('out', $out, $_REQUEST['ieId'], 'messages', "{$_REQUEST['mbox']}{$md5uidl}.php");
1832 $this->writeCacheFile('out', $out, $_REQUEST['ieId'], 'messages', "{$_REQUEST['mbox']}{$_REQUEST['uid']}.php");
1834 // restore date in the users preferred format to be send on to UI for diaply
1835 $out['meta']['email']['date_start'] = $dateTimeInUserFormat;
1838 $out['meta']['email']['toaddrs'] = $this->generateExpandableAddrs($out['meta']['email']['toaddrs']);
1839 if(!empty($out['meta']['email']['cc_addrs'])) {
1840 $ccs = $this->generateExpandableAddrs($out['meta']['email']['cc_addrs']);
1841 $out['meta']['cc'] = <<<eoq
1843 <td NOWRAP valign="top" class="displayEmailLabel">
1844 {$app_strings['LBL_EMAIL_CC']}:
1846 <td class="displayEmailValue">
1853 if(empty($out['meta']['email']['description']))
1854 $out['meta']['email']['description'] = $mod_strings['LBL_EMPTY_EMAIL_BODY'];
1857 $GLOBALS['log']->debug("EMAILUI: getSingleMessage() NOT using cache file");
1859 $GLOBALS['log']->debug("EMAILUI: getSingleMessage() using cache file [ ".$_REQUEST['mbox'].$_REQUEST['uid'].".php ]");
1862 $this->setReadFlag($_REQUEST['ieId'], $_REQUEST['mbox'], $_REQUEST['uid']);
1868 * Returns the HTML for a list of emails in a given folder
1869 * @param GUID $ieId GUID to InboundEmail instance
1870 * @param string $mbox Mailbox path name in dot notation
1871 * @param int $folderListCacheOffset Seconds for valid cache file
1872 * @return string HTML render of list.
1874 function getListEmails($ieId, $mbox, $folderListCacheOffset, $forceRefresh='false') {
1875 global $sugar_config;
1878 $ie = new InboundEmail();
1879 $ie->retrieve($ieId);
1880 $list = $ie->displayFolderContents($mbox, $forceRefresh);
1886 * Returns the templatized compose screen. Used by reply, forwards and draft status messages.
1887 * @param object email Email bean in focus
1889 function displayComposeEmail($email) {
1891 global $current_user;
1894 $ea = new SugarEmailAddress();
1896 if(!empty($email)) {
1897 $email->cids2Links();
1898 $description = (empty($email->description_html)) ? $email->description : $email->description_html;
1901 //Get the most complete address list availible for this email
1902 $addresses = array('toAddresses' => 'to', 'ccAddresses' => 'cc', 'bccAddresses' => 'bcc');
1903 foreach($addresses as $var => $type)
1906 foreach (array("{$type}_addrs_names", "{$type}addrs", "{$type}_addrs") as $emailVar)
1908 if (!empty($email->$emailVar)) {
1909 $$var = $email->$emailVar;
1916 $ret['type'] = $email->type;
1917 $ret['name'] = $email->name;
1918 $ret['description'] = $description;
1919 $ret['from'] = (isset($_REQUEST['composeType']) && $_REQUEST['composeType'] == 'forward') ? "" : $email->from_addr;
1920 $ret['to'] = from_html($toAddresses);
1921 $ret['uid'] = $email->id;
1922 $ret['parent_name'] = $email->parent_name;
1923 $ret['parent_type'] = $email->parent_type;
1924 $ret['parent_id'] = $email->parent_id;
1927 if(isset($_REQUEST['composeType']) && $_REQUEST['composeType'] == 'replyAll') {
1928 $ret['cc'] = from_html($ccAddresses);
1929 $ret['bcc'] = $bccAddresses;
1931 $userEmails = array();
1932 $userEmailsMeta = $ea->getAddressesByGUID($current_user->id, 'Users');
1933 foreach($userEmailsMeta as $emailMeta) {
1934 $userEmails[] = from_html(strtolower(trim($emailMeta['email_address'])));
1936 $userEmails[] = from_html(strtolower(trim($email->from_addr)));
1938 $ret['cc'] = from_html($email->cc_addrs);
1939 $toAddresses = from_html($toAddresses);
1940 $to = str_replace($this->addressSeparators, "::", $toAddresses);
1941 $exTo = explode("::", $to);
1943 if(is_array($exTo)) {
1944 foreach($exTo as $addr) {
1945 $addr = strtolower(trim($addr));
1946 if(!in_array($addr, $userEmails)) {
1947 if(!empty($ret['cc'])) {
1948 $ret['cc'] = $ret['cc'].", ";
1950 $ret['cc'] = $ret['cc'].trim($addr);
1953 } elseif(!empty($exTo)) {
1954 $exTo = trim($exTo);
1955 if(!in_array($exTo, $userEmails)) {
1956 $ret['cc'] = $ret['cc'].", ".$exTo;
1963 * Formats email body on reply/forward
1964 * @param object email Email object in focus
1965 * @param string type
1966 * @return object email
1968 function handleReplyType($email, $type) {
1969 global $mod_strings;
1970 $GLOBALS['log']->debug("****At Handle Reply Type: $type");
1974 $header = $email->getReplyHeader();
1975 if(!preg_match('/^(re:)+/i', $email->name)) {
1976 $email->name = "{$mod_strings['LBL_RE']} {$email->name}";
1978 if ($type == "reply") {
1979 $email->cc_addrs = "";
1980 if (!empty($email->reply_to_addr)) {
1981 $email->from_addr = $email->reply_to_addr;
1984 if (!empty($email->reply_to_addr)) {
1985 $email->to_addrs = $email->to_addrs . "," . $email->reply_to_addr;
1991 $header = $email->getForwardHeader();
1992 if(!preg_match('/^(fw:)+/i', $email->name)) {
1993 $email->name = "{$mod_strings['LBL_FW']} {$email->name}";
1995 $email->cc_addrs = "";
1999 $GLOBALS['log']->debug("EMAILUI: At reply case");
2000 $header = $email->getReplyHeader();
2002 $myCase = new aCase();
2003 $myCase->retrieve($email->parent_id);
2004 $myCaseMacro = $myCase->getEmailSubjectMacro();
2005 $email->parent_name = $myCase->name;
2006 $GLOBALS['log']->debug("****Case # : {$myCase->case_number} macro: $myCaseMacro");
2007 if(!strpos($email->name, str_replace('%1',$myCase->case_number,$myCaseMacro))) {
2008 $GLOBALS['log']->debug("Replacing");
2009 $email->name = str_replace('%1',$myCase->case_number,$myCaseMacro) . ' '. $email->name;
2011 $email->name = "{$mod_strings['LBL_RE']} {$email->name}";
2015 $html = trim($email->description_html);
2016 $plain = trim($email->description);
2018 $desc = (!empty($html)) ? $html : $plain;
2020 $email->description = $header.$email->quoteHtmlEmailForNewEmailUI($desc);
2025 ///////////////////////////////////////////////////////////////////////////
2026 //// PRIVATE HELPERS
2028 * Generates a UNION query to get one list of users, contacts, leads, and
2029 * prospects; used specifically for the addressBook
2031 function _getPeopleUnionQuery($whereArr , $person) {
2032 global $current_user , $app_strings;
2034 if(!isset($person) || $person === 'LBL_DROPDOWN_LIST_ALL'){
2035 $peopleTables = array("users",
2042 $peopleTables = array($person);
2048 foreach($whereArr as $column => $clause) {
2049 if(!empty($whereAdd)) {
2050 $whereAdd .= " AND ";
2052 $clause = $current_user->db->quote($clause);
2053 $whereAdd .= "{$column} LIKE '{$clause}%'";
2057 foreach($peopleTables as $table) {
2058 $module = ucfirst($table);
2059 $class = substr($module, 0, strlen($module) - 1);
2060 require_once("modules/{$module}/{$class}.php");
2061 $person = new $class();
2062 if (!$person->ACLAccess('list')) {
2065 $where = "({$table}.deleted = 0 AND eabr.primary_address = 1 AND {$table}.id <> '{$current_user->id}')";
2067 if (ACLController::requireOwner($module, 'list')) {
2068 $where = $where . " AND ({$table}.assigned_user_id = '{$current_user->id}')";
2070 if(!empty($whereAdd)) {
2071 $where .= " AND ({$whereAdd})";
2074 if ($person === 'accounts') {
2075 $t = "SELECT {$table}.id, '' first_name, {$table}.name, eabr.primary_address, ea.email_address, '{$module}' module ";
2077 $t = "SELECT {$table}.id, {$table}.first_name, {$table}.last_name, eabr.primary_address, ea.email_address, '{$module}' module ";
2079 $t .= "FROM {$table} ";
2080 $t .= "JOIN email_addr_bean_rel eabr ON ({$table}.id = eabr.bean_id and eabr.deleted=0) ";
2081 $t .= "JOIN email_addresses ea ON (eabr.email_address_id = ea.id) ";
2082 $t .= " WHERE {$where}";
2085 $q .= "\n UNION ALL \n";
2090 $countq = "SELECT count(people.id) c from ($q) people";
2091 $q .= "ORDER BY last_name";
2093 return array('query' => $q, 'countQuery' => $countq);
2097 * get emails of related bean for a given bean id
2099 * @param $condition array of conditions inclued bean id
2100 * @return array('query' => $q, 'countQuery' => $countq);
2102 function getRelatedEmail($beanType, $whereArr, $relatedBeanInfoArr = ''){
2103 global $beanList, $current_user, $app_strings, $db;
2105 $searchBeans = null;
2106 if($beanType === 'LBL_DROPDOWN_LIST_ALL')
2107 $searchBeans = array("users",
2114 if ($relatedBeanInfoArr == '' || empty($relatedBeanInfoArr['related_bean_type']) )
2116 if ($searchBeans != null)
2119 foreach ($searchBeans as $searchBean)
2121 $searchq = $this->findEmailFromBeanIds('', $searchBean, $whereArr);
2122 if(!empty($searchq)) {
2123 $q[] = "($searchq)";
2127 $finalQuery .= implode("\n UNION ALL \n", $q);
2130 $finalQuery = $this->findEmailFromBeanIds('', $beanType, $whereArr);
2134 $class = $beanList[$relatedBeanInfoArr['related_bean_type']];
2135 $focus = new $class();
2136 $focus->retrieve($relatedBeanInfoArr['related_bean_id']);
2137 if ($searchBeans != null)
2140 foreach ($searchBeans as $searchBean)
2142 if ($focus->load_relationship($searchBean))
2144 $data = $focus->$searchBean->get();
2145 if (count($data) != 0)
2146 $q[] = '('.$this->findEmailFromBeanIds($data, $searchBean, $whereArr).')';
2150 $finalQuery .= implode("\n UNION ALL \n", $q);
2154 if ($focus->load_relationship($beanType))
2156 $data = $focus->$beanType->get();
2157 if (count($data) != 0)
2158 $finalQuery = $this->findEmailFromBeanIds($data, $beanType, $whereArr);
2162 $countq = "SELECT count(people.id) c from ($finalQuery) people";
2163 return array('query' => $finalQuery, 'countQuery' => $countq);
2166 function findEmailFromBeanIds($beanIds, $beanType, $whereArr) {
2167 global $current_user;
2171 if ($beanIds != '') {
2172 foreach ($beanIds as $key => $value) {
2173 $beanIds[$key] = '\''.$value.'\'';
2175 $relatedIDs = implode(',', $beanIds);
2178 if ($beanType == 'accounts') {
2179 if (isset($whereArr['first_name'])) {
2180 $whereArr['name'] = $whereArr['first_name'];
2182 unset($whereArr['last_name']);
2183 unset($whereArr['first_name']);
2186 foreach($whereArr as $column => $clause) {
2187 if(!empty($whereAdd)) {
2188 $whereAdd .= " OR ";
2190 $clause = $current_user->db->quote($clause);
2191 $whereAdd .= "{$column} LIKE '{$clause}%'";
2194 $module = ucfirst($table);
2195 $class = substr($module, 0, strlen($module) - 1);
2196 require_once("modules/{$module}/{$class}.php");
2197 $person = new $class();
2198 if ($person->ACLAccess('list')) {
2199 if ($relatedIDs != '') {
2200 $where = "({$table}.deleted = 0 AND eabr.primary_address = 1 AND {$table}.id in ($relatedIDs))";
2202 $where = "({$table}.deleted = 0 AND eabr.primary_address = 1)";
2205 if (ACLController::requireOwner($module, 'list')) {
2206 $where = $where . " AND ({$table}.assigned_user_id = '{$current_user->id}')";
2208 if(!empty($whereAdd)) {
2209 $where .= " AND ({$whereAdd})";
2212 if ($beanType === 'accounts') {
2213 $t = "SELECT {$table}.id, '' first_name, {$table}.name last_name, eabr.primary_address, ea.email_address, '{$module}' module ";
2215 $t = "SELECT {$table}.id, {$table}.first_name, {$table}.last_name, eabr.primary_address, ea.email_address, '{$module}' module ";
2218 $t .= "FROM {$table} ";
2219 $t .= "JOIN email_addr_bean_rel eabr ON ({$table}.id = eabr.bean_id and eabr.deleted=0) ";
2220 $t .= "JOIN email_addresses ea ON (eabr.email_address_id = ea.id) ";
2221 $t .= " WHERE {$where}";
2228 * @param mixed $uids
2229 * @param bool $returnString False will return an array
2232 function _cleanUIDList($uids, $returnString=false) {
2233 global $app_strings;
2234 $GLOBALS['log']->debug("_cleanUIDList: before - [ {$uids} ]");
2236 if(!is_array($uids)) {
2237 $returnString = true;
2239 $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
2243 $cleanUids = array();
2244 foreach($uids as $uid) {
2245 $cleanUids[$uid] = $uid;
2251 $cleanImplode = implode($app_strings['LBL_EMAIL_DELIMITER'], $cleanUids);
2252 $GLOBALS['log']->debug("_cleanUIDList: after - [ {$cleanImplode} ]");
2253 return $cleanImplode;
2260 * Creates defaults for the User
2261 * @param object $user User in focus
2263 function preflightUser(&$user) {
2264 global $mod_strings;
2266 $goodToGo = $user->getPreference("email2Preflight", "Emails");
2267 $q = "SELECT count(*) count FROM folders f where f.created_by = '{$user->id}' AND f.folder_type = 'inbound' AND f.deleted = 0";
2268 $r = $user->db->query($q);
2269 $a = $user->db->fetchByAssoc($r);
2271 if($a['count'] < 1) {
2272 require_once("include/SugarFolders/SugarFolders.php");
2274 $folder = new SugarFolder();
2275 $folder->new_with_id = true;
2276 $folder->id = create_guid();
2277 $folder->name = $mod_strings['LNK_MY_INBOX'];
2278 $folder->has_child = 1;
2279 $folder->created_by = $user->id;
2280 $folder->modified_by = $user->id;
2281 $folder->is_dynamic = 1;
2282 $folder->folder_type = "inbound";
2283 $folder->dynamic_query = $this->generateDynamicFolderQuery('inbound', $user->id);
2287 $drafts = new SugarFolder();
2288 $drafts->name = $mod_strings['LNK_MY_DRAFTS'];
2289 $drafts->has_child = 0;
2290 $drafts->parent_folder = $folder->id;
2291 $drafts->created_by = $user->id;
2292 $drafts->modified_by = $user->id;
2293 $drafts->is_dynamic = 1;
2294 $drafts->folder_type = "draft";
2295 $drafts->dynamic_query = $this->generateDynamicFolderQuery('draft', $user->id);
2300 $archived = new SugarFolder();
2301 $archived->name = $mod_strings['LNK_SENT_EMAIL_LIST'];
2302 $archived->has_child = 0;
2303 $archived->parent_folder = $folder->id;
2304 $archived->created_by = $user->id;
2305 $archived->modified_by = $user->id;
2306 $archived->is_dynamic = 1;
2307 $archived->folder_type = "sent";
2308 $archived->dynamic_query = $this->generateDynamicFolderQuery('sent', $user->id);
2311 // set flag to show that this was run
2312 $user->setPreference("email2Preflight", true, 1, "Emails");
2317 * Parses the core dynamic folder query
2318 * @param string $type 'inbound', 'draft', etc.
2319 * @param string $userId
2322 function generateDynamicFolderQuery($type, $userId) {
2323 $q = $this->coreDynamicFolderQuery;
2327 if($type == "sent") {
2331 $replacee = array("::TYPE::", "::STATUS::", "::USER_ID::");
2332 $replacer = array($type, $status, $userId);
2334 $ret = str_replace($replacee, $replacer, $q);
2336 if($type == 'inbound') {
2337 $ret .= " AND status NOT IN ('sent', 'archived', 'draft') AND type NOT IN ('out', 'archived', 'draft')";
2339 $ret .= " AND status NOT IN ('archived') AND type NOT IN ('archived')";
2346 * Preps the User's cache dir
2348 function preflightUserCache() {
2349 $path = clean_path($this->userCacheDir);
2350 if(!file_exists($this->userCacheDir))
2351 mkdir_recursive($path);
2353 $files = findAllFiles($path, array());
2355 foreach($files as $file) {
2360 function clearInboundAccountCache($ieId) {
2361 global $sugar_config;
2362 $cacheRoot = sugar_cached("modules/Emails/{$ieId}");
2363 $files = findAllFiles($cacheRoot."/messages/", array());
2364 foreach($files as $file) {
2367 $files = findAllFiles($cacheRoot."/attachments/", array());
2368 foreach($files as $file) {
2374 * returns an array of EmailTemplates that the user has access to for the compose email screen
2377 function getEmailTemplatesArray() {
2379 global $app_strings;
2381 if(ACLController::checkAccess('EmailTemplates', 'list', true) && ACLController::checkAccess('EmailTemplates', 'view', true)) {
2382 $et = new EmailTemplate();
2383 $etResult = $et->db->query($et->create_new_list_query('','',array(),array(),''));
2384 $email_templates_arr = array('' => $app_strings['LBL_NONE']);
2385 while($etA = $et->db->fetchByAssoc($etResult)) {
2386 $email_templates_arr[$etA['id']] = $etA['name'];
2389 $email_templates_arr = array('' => $app_strings['LBL_NONE']);
2392 return $email_templates_arr;
2395 function getFromAccountsArray($ie) {
2396 global $current_user;
2397 global $app_strings;
2399 $ieAccountsFull = $ie->retrieveAllByGroupIdWithGroupAccounts($current_user->id);
2400 $ieAccountsFrom= array();
2402 $oe = new OutboundEmail();
2403 $system = $oe->getSystemMailerSettings();
2404 $ret = $current_user->getUsersNameAndEmail();
2405 $ret['name'] = from_html($ret['name']);
2406 $useMyAccountString = true;
2408 if(empty($ret['email'])) {
2409 $systemReturn = $current_user->getSystemDefaultNameAndEmail();
2410 $ret['email'] = $systemReturn['email'];
2411 $ret['name'] = from_html($systemReturn['name']);
2412 $useMyAccountString = false;
2415 $myAccountString = '';
2416 if ($useMyAccountString) {
2417 $myAccountString = " - {$app_strings['LBL_MY_ACCOUNT']}";
2420 //Check to make sure that the user has set the associated inbound email acount -> outbound acount is active.
2421 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
2422 $sf = new SugarFolder();
2423 $groupSubs = $sf->getSubscriptions($current_user);
2425 foreach($ieAccountsFull as $k => $v)
2427 $personalSelected = (!empty($showFolders) && in_array($v->id, $showFolders));
2429 $allowOutboundGroupUsage = $v->get_stored_options('allow_outbound_group_usage',FALSE);
2430 $groupSelected = ( in_array($v->groupfolder_id, $groupSubs) && $allowOutboundGroupUsage);
2431 $selected = ( $personalSelected || $groupSelected );
2435 $GLOBALS['log']->debug("Inbound Email {$v->name}, not selected and will not be available for selection within compose UI.");
2439 $name = $v->get_stored_options('from_name');
2440 $addr = $v->get_stored_options('from_addr');
2441 if ($name != null && $addr != null) {
2442 $name = from_html($name);
2443 if (!$v->is_personal) {
2444 $ieAccountsFrom[] = array("value" => $v->id, "text" => "{$name} ({$addr}) - {$app_strings['LBL_EMAIL_UPPER_CASE_GROUP']}");
2446 $ieAccountsFrom[] = array("value" => $v->id, "text" => "{$name} ({$addr})");
2452 $userSystemOverride = $oe->getUsersMailerForSystemOverride($current_user->id);
2453 //Substitute in the users system override if its available.
2454 if($userSystemOverride != null)
2455 $system = $userSystemOverride;
2457 if( !empty($system->mail_smtpserver) )
2459 $admin = new Administration();
2460 $admin->retrieveSettings(); //retrieve all admin settings.
2461 $ieAccountsFrom[] = array("value" => $system->id, "text" =>
2462 "{$ret['name']} ({$ret['email']}){$myAccountString}");
2465 return $ieAccountsFrom;
2469 * This function will return all the accounts this user has access to based on the
2470 * match of the emailId passed in as a parameter
2472 * @param unknown_type $ie
2475 function getFromAllAccountsArray($ie, $ret) {
2476 global $current_user;
2477 global $app_strings;
2479 $ret['fromAccounts'] = array();
2480 if (!isset($ret['to']) && !empty($ret['from'])) {
2481 $ret['fromAccounts']['status'] = false;
2484 $ieAccountsFull = $ie->retrieveAllByGroupIdWithGroupAccounts($current_user->id);
2485 $foundInPersonalAccounts = false;
2486 $foundInGroupAccounts = false;
2487 $foundInSystemAccounts = false;
2489 //$toArray = array();
2490 if ($ret['type'] == "draft") {
2491 $toArray = explode(",", $ret['from']);
2493 $toArray = $ie->email->email2ParseAddressesForAddressesOnly($ret['to']);
2495 foreach($ieAccountsFull as $k => $v) {
2496 $storedOptions = unserialize(base64_decode($v->stored_options));
2497 if ( array_search_insensitive($storedOptions['from_addr'], $toArray)) {
2498 if ($v->is_personal) {
2499 $foundInPersonalAccounts = true;
2502 $foundInGroupAccounts = true;
2507 $oe = new OutboundEmail();
2508 $system = $oe->getSystemMailerSettings();
2510 $return = $current_user->getUsersNameAndEmail();
2511 $return['name'] = from_html($return['name']);
2512 $useMyAccountString = true;
2514 if(empty($return['email'])) {
2515 $systemReturn = $current_user->getSystemDefaultNameAndEmail();
2516 $return['email'] = $systemReturn['email'];
2517 $return['name'] = from_html($systemReturn['name']);
2518 $useMyAccountString = false;
2521 $myAccountString = '';
2522 if ($useMyAccountString) {
2523 $myAccountString = " - {$app_strings['LBL_MY_ACCOUNT']}";
2526 if(!empty($system->id)) {
2528 $admin = new Administration();
2529 $admin->retrieveSettings(); //retrieve all admin settings.
2530 if (in_array(trim($return['email']), $toArray)) {
2531 $foundInSystemAccounts = true;
2535 if (!$foundInPersonalAccounts && !$foundInGroupAccounts && !$foundInSystemAccounts) {
2536 $ret['fromAccounts']['status'] = false;
2540 $ieAccountsFrom= array();
2541 foreach($ieAccountsFull as $k => $v) {
2542 $storedOptions = unserialize(base64_decode($v->stored_options));
2543 $storedOptionsName = from_html($storedOptions['from_name']);
2546 if (array_search_insensitive($storedOptions['from_addr'], $toArray)) {
2547 //if ($ret['to'] == $storedOptions['from_addr']) {
2550 if ($foundInPersonalAccounts) {
2551 if ($v->is_personal) {
2552 $ieAccountsFrom[] = array("value" => $v->id, "selected" => $selected, "text" => "{$storedOptionsName} ({$storedOptions['from_addr']})");
2555 $ieAccountsFrom[] = array("value" => $v->id, "selected" => $selected, "text" => "{$storedOptionsName} ({$storedOptions['from_addr']}) - {$app_strings['LBL_EMAIL_UPPER_CASE_GROUP']}");
2559 if(!empty($system->id)) {
2560 if (!$foundInPersonalAccounts && !$foundInGroupAccounts && $foundInSystemAccounts) {
2561 $ieAccountsFrom[] = array("value" => $system->id, "selected" => true, "text" =>
2562 "{$return['name']} ({$return['email']}){$myAccountString}");
2564 $ieAccountsFrom[] = array("value" => $system->id, "text" =>
2565 "{$return['name']} ({$return['email']}){$myAccountString}");
2569 $ret['fromAccounts']['status'] = ($foundInPersonalAccounts || $foundInGroupAccounts || $foundInSystemAccounts) ? true : false;
2570 $ret['fromAccounts']['data'] = $ieAccountsFrom;
2576 * takes an array and creates XML
2577 * @param array Array to convert
2578 * @param string Name to wrap highest level items in array
2579 * @return string XML
2581 function arrayToXML($a, $paramName) {
2585 $bad = array("<",">","'",'"',"&");
2586 $good = array("<", ">", "'", ""","&");
2590 for($i=0; $i<count($a); $i++) {
2592 $ret .= "\n<{$paramName}>";
2594 foreach($email as $k => $v) {
2595 $ret .= "\n\t<{$k}>".str_replace($bad, $good, $v)."</{$k}>";
2597 $ret .= "\n</{$paramName}>";
2603 * Re-used option getter for Show Accounts multiselect pane
2605 function getShowAccountsOptions(&$ie) {
2606 global $current_user;
2607 global $app_strings;
2608 global $mod_strings;
2610 $ieAccountsFull = $ie->retrieveAllByGroupId($current_user->id);
2611 $ieAccountsShowOptionsMeta = array();
2612 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
2614 $defaultIEAccount = $ie->getUsersDefaultOutboundServerId($current_user);
2616 foreach($ieAccountsFull as $k => $v) {
2617 $selected = (!empty($showFolders) && in_array($v->id, $showFolders)) ? true : false;
2618 $default = ($defaultIEAccount == $v->id) ? TRUE : FALSE;
2619 $has_groupfolder = !empty($v->groupfolder_id) ? TRUE : FALSE;
2620 $type = ($v->is_personal) ? $mod_strings['LBL_MAILBOX_TYPE_PERSONAL'] : $mod_strings['LBL_MAILBOX_TYPE_GROUP'];
2622 $ieAccountsShowOptionsMeta[] = array("id" => $v->id, "name" => $v->name, 'is_active' => $selected,
2623 'server_url' => $v->server_url, 'is_group' => !$v->is_personal,'group_id' => $v->group_id,
2624 'is_default' => $default, 'has_groupfolder' => $has_groupfolder,'type' => $type );
2627 //Retrieve the grou folders
2628 $f = new SugarFolder();
2629 $groupFolders = $f->getGroupFoldersForSettings($current_user);
2631 foreach ($groupFolders as $singleGroup)
2633 //Retrieve the related IE accounts.
2634 $relatedIEAccounts = $ie->retrieveByGroupFolderId($singleGroup['id']);
2636 if(count($relatedIEAccounts) == 0)
2637 $server_url = $app_strings['LBL_EMAIL_MULT_GROUP_FOLDER_ACCOUNTS_EMPTY'];
2638 else if(count($relatedIEAccounts) == 1)
2640 if($relatedIEAccounts[0]->status != 'Active' || $relatedIEAccounts[0]->mailbox_type == 'bounce')
2643 $server_url = $relatedIEAccounts[0]->server_url;
2646 $server_url = $app_strings['LBL_EMAIL_MULT_GROUP_FOLDER_ACCOUNTS'];
2648 $type = $mod_strings['LBL_MAILBOX_TYPE_GROUP_FOLDER'];
2649 $ieAccountsShowOptionsMeta[] = array("id" => $singleGroup['id'], "name" => $singleGroup['origName'], 'is_active' => $singleGroup['selected'],
2650 'server_url' => $server_url, 'is_group' => true,'group_id' => $singleGroup['id'],
2651 'is_default' => FALSE, 'has_groupfolder' => true,'type' => $type);
2655 return $ieAccountsShowOptionsMeta;
2658 function getShowAccountsOptionsForSearch(&$ie) {
2659 global $current_user;
2660 global $app_strings;
2662 $ieAccountsFull = $ie->retrieveAllByGroupId($current_user->id);
2663 //$ieAccountsShowOptions = "<option value=''>{$app_strings['LBL_NONE']}</option>\n";
2664 $ieAccountsShowOptionsMeta = array();
2665 $ieAccountsShowOptionsMeta[] = array("value" => "", "text" => $app_strings['LBL_NONE'], 'selected' => '');
2666 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
2668 foreach($ieAccountsFull as $k => $v) {
2669 if(!in_array($v->id, $showFolders)) {
2672 $group = (!$v->is_personal) ? $app_strings['LBL_EMAIL_GROUP']."." : "";
2673 $ieAccountsShowOptionsMeta[] = array("value" => $v->id, "text" => $group.$v->name, 'protocol' => $v->protocol);
2676 return $ieAccountsShowOptionsMeta;
2679 * Formats a display message on successful async call
2680 * @param string $type Type of message to display
2682 function displaySuccessMessage($type) {
2683 global $app_strings;
2687 $message = $app_strings['LBL_EMAIL_DELETE_SUCCESS'];
2691 $message = "NOOP: invalid type";
2695 $this->smarty->assign('app_strings', $app_strings);
2696 $this->smarty->assign('message', $message);
2697 echo $this->smarty->fetch("modules/Emails/templates/successMessage.tpl");
2701 * Validates existence and expiration of a cache file
2702 * @param string $ieId
2703 * @param string $type Type of cache file: folders, messages, etc.
2704 * @param string $file The cachefile name
2705 * @param int refreshOffset Refresh time in secs.
2708 function validCacheFileExists($ieId, $type, $file, $refreshOffset=-1) {
2709 global $sugar_config;
2711 if($refreshOffset == -1) {
2712 $refreshOffset = $this->cacheTimeouts[$type]; // use defaults
2715 $cacheFilePath = sugar_cached("modules/Emails/{$ieId}/{$type}/{$file}");
2716 if(file_exists($cacheFilePath)) {
2724 * retrieves the cached value
2725 * @param string $ieId
2726 * @param string $type Type of cache file: folders, messages, etc.
2727 * @param string $file The cachefile name
2728 * @param string $key name of cache value
2731 function getCacheValue($ieId, $type, $file, $key) {
2732 global $sugar_config;
2734 $cacheFilePath = sugar_cached("modules/Emails/{$ieId}/{$type}/{$file}");
2735 $cacheFile = array();
2737 if(file_exists($cacheFilePath)) {
2738 include($cacheFilePath); // provides $cacheFile
2740 if(isset($cacheFile[$key])) {
2741 $ret = unserialize($cacheFile[$key]);
2745 $GLOBALS['log']->debug("EMAILUI: cache file not found [ {$cacheFilePath} ] - creating blank cache file");
2746 $this->writeCacheFile('retArr', array(), $ieId, $type, $file);
2753 * retrieves the cache file last touched time
2754 * @param string $ieId
2755 * @param string $type Type of cache file: folders, messages, etc.
2756 * @param string $file The cachefile name
2759 function getCacheTimestamp($ieId, $type, $file) {
2760 global $sugar_config;
2762 $cacheFilePath = sugar_cached("modules/Emails/{$ieId}/{$type}/{$file}");
2763 $cacheFile = array();
2765 if(file_exists($cacheFilePath)) {
2766 include($cacheFilePath); // provides $cacheFile['timestamp']
2768 if(isset($cacheFile['timestamp'])) {
2769 $GLOBALS['log']->debug("EMAILUI: found timestamp [ {$cacheFile['timestamp']} ]");
2770 return $cacheFile['timestamp'];
2778 * Updates the timestamp for a cache file - usually to mark a "check email"
2780 * @param string $ieId
2781 * @param string $type Type of cache file: folders, messages, etc.
2782 * @param string $file The cachefile name
2784 function setCacheTimestamp($ieId, $type, $file) {
2785 global $sugar_config;
2787 $cacheFilePath = sugar_cached("modules/Emails/{$ieId}/{$type}/{$file}");
2788 $cacheFile = array();
2790 if(file_exists($cacheFilePath)) {
2791 include($cacheFilePath); // provides $cacheFile['timestamp']
2793 if(isset($cacheFile['timestamp'])) {
2794 $cacheFile['timestamp'] = strtotime('now');
2795 $GLOBALS['log']->debug("EMAILUI: setting updated timestamp [ {$cacheFile['timestamp']} ]");
2796 return $this->_writeCacheFile($cacheFile, $cacheFilePath);
2803 * Writes caches to flat file in cache dir.
2804 * @param string $key Key to the main cache entry (not timestamp)
2805 * @param mixed $var Variable to be cached
2806 * @param string $ieId I-E focus ID
2807 * @param string $type Folder in cache
2808 * @param string $file Cache file name
2810 function writeCacheFile($key, $var, $ieId, $type, $file) {
2811 global $sugar_config;
2813 $the_file = sugar_cached("/modules/Emails/{$ieId}/{$type}/{$file}");
2814 $timestamp = strtotime('now');
2816 $array['timestamp'] = $timestamp;
2817 $array[$key] = serialize($var); // serialized since varexport_helper() can't handle PHP objects
2819 return $this->_writeCacheFile($array, $the_file);
2823 * Performs the actual file write. Abstracted from writeCacheFile() for
2825 * @param array $array The array to write to the cache
2826 * @param string $file Full path (relative) with cache file name
2829 function _writeCacheFile($array, $file) {
2830 global $sugar_config;
2832 $arrayString = var_export_helper($array);
2836 <?php // created: {$date}
2837 \$cacheFile = {$arrayString};
2840 if($fh = @sugar_fopen($file, "w")) {
2841 fputs($fh, $the_string);
2845 $GLOBALS['log']->debug("EMAILUI: Could not write cache file [ {$file} ]");
2851 * Generate JSON encoded data to be consumed by yui datatable.
2853 * @param array $data
2854 * @param string $resultsParam The resultsList name
2857 function jsonOuput($data, $resultsParam, $count=0, $fromCache=true, $unread=-1) {
2858 global $app_strings;
2860 $count = ($count > 0) ? $count : 0;
2862 if(isset($a['fromCache']))
2863 $cached = ($a['fromCache'] == 1) ? 1 : 0;
2865 $cached = ($fromCache) ? 1 : 0;
2867 if($data['mbox'] == 'undefined' || empty($data['mbox']))
2868 $data['mbox'] = $app_strings['LBL_NONE'];
2870 $jsonOut = array('TotalCount' => $count, 'FromCache' => $cached, 'UnreadCount' => $unread, $resultsParam => $data['out']);
2872 return json_encode($jsonOut);
2875 * generates XML output from an array
2877 * @param string master list Item
2880 function xmlOutput($a, $paramName, $count=0, $fromCache=true, $unread=-1) {
2881 global $app_strings;
2882 $count = ($count > 0) ? $count : 0;
2884 if(isset($a['fromCache'])) {
2885 $cached = ($a['fromCache'] == 1) ? 1 : 0;
2887 $cached = ($fromCache) ? 1 : 0;
2890 if($a['mbox'] == 'undefined' || empty($a['mbox'])) {
2891 $a['mbox'] = $app_strings['LBL_NONE'];
2894 $xml = $this->arrayToXML($a['out'], $paramName);
2897 <?xml version="1.0" encoding="UTF-8"?>
2899 <TotalCount>{$count}</TotalCount>
2900 <UnreadCount>{$unread}</UnreadCount>
2901 <FromCache> {$cached} </FromCache>
2911 * Generate to/cc addresses string in email detailview.
2913 * @param string $str
2914 * @param string $target values: to, cc
2915 * @param int $defaultNum
2916 * @return string $str
2918 function generateExpandableAddrs($str) {
2919 global $mod_strings;
2920 $tempStr = $str.',';
2921 $tempStr = html_entity_decode($tempStr);
2922 $tempStr = $this->unifyEmailString($tempStr);
2924 $pattern = '/@.*,/U';
2925 preg_match_all($pattern, $tempStr, $matchs);
2926 $totalCount = count($matchs[0]);
2928 if(!empty($matchs[0]) && $totalCount > $defaultNum) {
2929 $position = strpos($tempStr, $matchs[0][$defaultNum]);
2930 $hiddenCount = $totalCount - $defaultNum;
2931 $frontStr = substr($tempStr, 0, $position);
2932 $backStr = substr($tempStr, $position, -1);
2933 $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>';
2940 * Unify the seperator as ,
2942 * @param String $str email address string
2943 * @return String converted string
2945 function unifyEmailString($str) {
2946 preg_match_all('/@.*;/U', $str, $matches);
2947 if(!empty($matches[0])) {
2948 foreach($matches[0] as $key => $value) {
2949 $new[] = str_replace(";",",",$value);
2951 return str_replace($matches[0], $new, $str);