PageRenderTime 56ms CodeModel.GetById 10ms RepoModel.GetById 1ms app.codeStats 0ms

/modules/Emails/EmailUI.php

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