]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/Emails/EmailUIAjax.php
Release 6.5.1
[Github/sugarcrm.git] / modules / Emails / EmailUIAjax.php
1 <?php
2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4  * SugarCRM Community Edition is a customer relationship management program developed by
5  * SugarCRM, Inc. Copyright (C) 2004-2012 SugarCRM Inc.
6  * 
7  * This program is free software; you can redistribute it and/or modify it under
8  * the terms of the GNU Affero General Public License version 3 as published by the
9  * Free Software Foundation with the addition of the following permission added
10  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
13  * 
14  * This program is distributed in the hope that it will be useful, but WITHOUT
15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
17  * details.
18  * 
19  * You should have received a copy of the GNU Affero General Public License along with
20  * this program; if not, see http://www.gnu.org/licenses or write to the Free
21  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22  * 02110-1301 USA.
23  * 
24  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
26  * 
27  * The interactive user interfaces in modified source and object code versions
28  * of this program must display Appropriate Legal Notices, as required under
29  * Section 5 of the GNU Affero General Public License version 3.
30  * 
31  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32  * these Appropriate Legal Notices must retain the display of the "Powered by
33  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34  * technical reasons, the Appropriate Legal Notices must display the words
35  * "Powered by SugarCRM".
36  ********************************************************************************/
37
38  /*********************************************************************************
39
40   * Description:
41   * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. All Rights
42   * Reserved. Contributor(s): ______________________________________..
43   *********************************************************************************/
44   //increate timeout for phpo script execution
45   ini_set('max_execution_time',300);
46   //ajaxInit();
47
48
49   require_once("include/OutboundEmail/OutboundEmail.php");
50   require_once("include/ytree/Tree.php");
51   require_once("include/ytree/ExtNode.php");
52
53   $email = new Email();
54   $email->email2init();
55   $ie = new InboundEmail();
56   $ie->email = $email;
57   $json = getJSONobj();
58
59
60   $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
61
62  if (isset($_REQUEST['emailUIAction'])) {
63   switch($_REQUEST['emailUIAction']) {
64
65
66         ///////////////////////////////////////////////////////////////////////////
67         ////    COMPOSE REPLY FORWARD
68         // this is used in forward/reply
69     case "composeEmail":
70         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: composeEmail");
71         if(isset($_REQUEST['sugarEmail']) && $_REQUEST['sugarEmail'] == 'true' && isset($_REQUEST['uid']) && !empty($_REQUEST['uid'])) {
72             $ie->email->retrieve($_REQUEST['uid']);
73             $ie->email->from_addr = $ie->email->from_addr_name;
74             $ie->email->to_addrs = to_html($ie->email->to_addrs_names);
75             $ie->email->cc_addrs = to_html($ie->email->cc_addrs_names);
76             $ie->email->bcc_addrs = $ie->email->bcc_addrs_names;
77             $ie->email->from_name = $ie->email->from_addr;
78             $email = $ie->email->et->handleReplyType($ie->email, $_REQUEST['composeType']);
79             $ret = $ie->email->et->displayComposeEmail($email);
80             $ret['description'] = empty($email->description_html) ?  str_replace("\n", "\n<BR/>", $email->description) : $email->description_html;
81                         //get the forward header and add to description
82             $forward_header = $email->getForwardHeader();
83
84             $ret['description'] = $forward_header . $ret['description'];
85             if ($_REQUEST['composeType'] == 'forward') {
86                 $ret = $ie->email->et->getDraftAttachments($ret);
87             }
88             $ret = $ie->email->et->getFromAllAccountsArray($ie, $ret);
89             $ret['from'] = from_html($ret['from']);
90             $ret['name'] = from_html($ret['name']);
91             $out = $json->encode($ret, true);
92             echo $out;
93         } elseif(isset($_REQUEST['uid']) && !empty($_REQUEST['uid']) && isset($_REQUEST['ieId']) && !empty($_REQUEST['ieId'])) {
94             $ie->retrieve($_REQUEST['ieId']);
95             $ie->mailbox = $_REQUEST['mbox'];
96                         global $timedate;
97             $ie->setEmailForDisplay($_REQUEST['uid']);
98                         $ie->email->date_start = $timedate->to_display_date($ie->email->date_sent);
99                         $ie->email->time_start = $timedate->to_display_time($ie->email->date_sent);
100             $ie->email->date_sent = $timedate->to_display_date_time($ie->email->date_sent);
101             $email = $ie->email->et->handleReplyType($ie->email, $_REQUEST['composeType']);
102             $ret = $ie->email->et->displayComposeEmail($email);
103             if ($_REQUEST['composeType'] == 'forward') {
104                 $ret = $ie->email->et->createCopyOfInboundAttachment($ie, $ret, $_REQUEST['uid']);
105             }
106             $ret = $ie->email->et->getFromAllAccountsArray($ie, $ret);
107             $ret['from'] = from_html($ret['from']);
108             $ret['name'] = from_html($ret['name']);
109             $ret['ieId'] = $_REQUEST['ieId'];
110             $ret['mbox'] = $_REQUEST['mbox'];
111             $out = $json->encode($ret, true);
112             echo $out;
113         }
114         break;
115
116         /**
117          * sendEmail handles both send and save draft duties
118          */
119     case "sendEmail":
120         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: sendEmail");
121
122
123         $sea = new SugarEmailAddress();
124
125         $email->type = 'out';
126         $email->status = 'sent';
127
128         if(isset($_REQUEST['email_id']) && !empty($_REQUEST['email_id'])) {// && isset($_REQUEST['saveDraft']) && !empty($_REQUEST['saveDraft'])) {
129             $email->retrieve($_REQUEST['email_id']); // uid is GUID in draft cases
130         }
131         if (isset($_REQUEST['uid']) && !empty($_REQUEST['uid'])) {
132                 $email->uid = $_REQUEST['uid'];
133         }
134
135         if ($email->email2Send($_REQUEST)) {
136             $ret = array(
137                 'composeLayoutId'  => $_REQUEST['composeLayoutId'],
138             );
139                 $out = $json->encode($ret, true);
140             echo $out; // async call to close the proper compose tab
141         }
142     break;
143
144     case "uploadAttachment":
145         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: uploadAttachment");
146         $metadata = $email->email2saveAttachment();
147
148         if(!empty($metadata)) {
149             $out = $json->encode($metadata);
150             echo $out;
151         }
152         break;
153
154     case "removeUploadedAttachment":
155         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: removeUploadedAttachment");
156         $fileFromRequest = from_html($_REQUEST['file']);
157         $fileGUID = substr($fileFromRequest, 0, 36);
158         // Bug52727: sanitize fileGUID to remove path components: /\.
159         $fileGUID = cleanDirName($fileGUID);
160         $fileName = $email->et->userCacheDir . "/" . $fileGUID;
161         $filePath = clean_path($fileName);
162         unlink($filePath);
163         break;
164
165     case "fillComposeCache": // fills client-side compose email cache with signatures and email templates
166         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: fillComposeCache");
167         $out = array();
168         $email_templates_arr = $email->et->getEmailTemplatesArray();
169         natcasesort($email_templates_arr);
170         $out['emailTemplates'] = $email_templates_arr;
171         $sigs = $current_user->getSignaturesArray();
172         // clean "none"
173         foreach($sigs as $k => $v) {
174             if($k == "") {
175                  $sigs[$k] = $app_strings['LBL_NONE'];
176                         } else if (is_array($v) && isset($v['name'])){
177                                 $sigs[$k] = $v['name'];
178                         } else{
179                             $sigs[$k] = $v;
180                         }
181         }
182         $out['signatures'] = $sigs;
183         $out['fromAccounts'] = $email->et->getFromAccountsArray($ie);
184         $out['errorArray'] = array();
185
186         $oe = new OutboundEmail();
187         if( $oe->doesUserOverrideAccountRequireCredentials($current_user->id) )
188         {
189             $overideAccount = $oe->getUsersMailerForSystemOverride($current_user->id);
190             //If the user override account has not been created yet, create it for the user.
191             if($overideAccount == null)
192                 $overideAccount = $oe->createUserSystemOverrideAccount($current_user->id);
193
194                     $out['errorArray'] = array($overideAccount->id => $app_strings['LBL_EMAIL_WARNING_MISSING_USER_CREDS']);
195         }
196
197         $ret = $json->encode($out);
198         echo $ret;
199         break;
200
201     case "getSignature":
202         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: getSignature");
203         if(isset($_REQUEST['id'])) {
204             $signature = $current_user->getSignature($_REQUEST['id']);
205             $signature['signature_html'] = from_html($signature['signature_html']);
206             $out = $json->encode($signature);
207             echo $out;
208         } else {
209             die();
210         }
211         break;
212
213     case "deleteSignature":
214         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: deleteSignature");
215         if(isset($_REQUEST['id'])) {
216                         require_once("modules/Users/UserSignature.php");
217                 $us = new UserSignature();
218                 $us->mark_deleted($_REQUEST['id']);
219             $signatureArray = $current_user->getSignaturesArray();
220                 // clean "none"
221                 foreach($signatureArray as $k => $v) {
222                     if($k == "") {
223                  $sigs[$k] = $app_strings['LBL_NONE'];
224                     } else if (is_array($v) && isset($v['name'])){
225                         $sigs[$k] = $v['name'];
226                     } else{
227                         $sigs[$k] = $v;
228                     }
229                 }
230                 $out['signatures'] = $signatureArray;
231             $ret = $json->encode($out);
232             echo $ret;
233         } else {
234             die();
235         }
236         break;
237     case "getTemplateAttachments":
238         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: getTemplateAttachments");
239         if(isset($_REQUEST['parent_id']) && !empty($_REQUEST['parent_id'])) {
240
241
242             $where = "parent_id='{$_REQUEST['parent_id']}'";
243             $order = "";
244             $seed = new Note();
245             $fullList = $seed->get_full_list($order, $where, '');
246             $all_fields = array_merge($seed->column_fields, $seed->additional_column_fields);
247
248             $js_fields_arr = array();
249
250             $i=1; // js doesn't like 0 index?
251             if (!empty($fullList)) {
252                 foreach($fullList as $note) {
253                     $js_fields_arr[$i] = array();
254
255                     foreach($all_fields as $field) {
256                         if(isset($note->$field)) {
257                             $note->$field = from_html($note->$field);
258                             $note->$field = preg_replace('/\r\n/','<BR>',$note->$field);
259                             $note->$field = preg_replace('/\n/','<BR>',$note->$field);
260                             $js_fields_arr[$i][$field] = addslashes($note->$field);
261                         }
262                     }
263                     $i++;
264                 }
265             }
266
267             $out = $json->encode($js_fields_arr);
268             echo $out;
269         }
270         break;
271         ////    END COMPOSE REPLY FORWARD
272         ///////////////////////////////////////////////////////////////////////////
273
274
275
276         ///////////////////////////////////////////////////////////////////////////
277         ////    MESSAGE HANDLING
278     case "displayView":
279         $ret = array();
280         $ie->retrieve($_REQUEST['ieId']);
281         $ie->mailbox = $_REQUEST['mailbox'];
282         $ie->connectMailserver();
283
284         switch($_REQUEST['type']) {
285             case "headers":
286                 $title = "{$app_strings['LBL_EMAIL_VIEW_HEADERS']}";
287                 $text = $ie->getFormattedHeaders($_REQUEST['uid']);
288                 break;
289
290             case "raw":
291                 $title = "{$app_strings['LBL_EMAIL_VIEW_RAW']}";
292                 $text = $ie->getFormattedRawSource($_REQUEST['uid']);
293                 break;
294
295             case "printable":
296
297                 break;
298         }
299
300         $ret['html'] = $text;
301         $ret['title'] = $title;
302
303         $out = $json->encode($ret, true);
304         echo $out;
305         break;
306
307     case "getQuickCreateForm":
308         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: getQuickCreateForm");
309         if(isset($_REQUEST['qc_module']) && !empty($_REQUEST['qc_module'])) {
310                 if (!ACLController::checkAccess($_REQUEST['qc_module'],'edit', true)) {
311                         echo trim($json->encode(array('html' => translate('LBL_NO_ACCESS', 'ACL')), true));
312                         break;
313                 }
314             $people = array("Users", "Contacts", "Leads", "Prospects");
315             $showSaveToAddressBookButton = false;//(in_array($_REQUEST['qc_module'], $people)) ? true : false;
316
317             if(isset($_REQUEST['sugarEmail']) && !empty($_REQUEST['sugarEmail'])) {
318                 $ie->email->retrieve($_REQUEST['uid']); // uid is a sugar GUID in this case
319             } else {
320                 $ie->retrieve($_REQUEST['ieId']);
321                 $ie->mailbox = $_REQUEST['mailbox'];
322                 $ie->setEmailForDisplay($_REQUEST['uid']);
323             }
324             $ret = $email->et->getQuickCreateForm($_REQUEST, $ie->email, $showSaveToAddressBookButton);
325             $ret['ieId'] = $_REQUEST['ieId'];
326             $ret['mbox'] = $_REQUEST['mailbox'];
327             $ret['uid'] = $_REQUEST['uid'];
328             $ret['module'] = $_REQUEST['qc_module'];
329             if (!isset($_REQUEST['iframe'])) {
330                 $out = trim($json->encode($ret, false));
331             } else {
332                 $out = $ret['html'];
333             }
334             echo $out;
335         }
336         break;
337
338     case 'saveQuickCreate':
339         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: saveQuickCreate");
340         require_once('include/MVC/Controller/ControllerFactory.php');
341         if (isset($_REQUEST['qcmodule'])) {
342             $GLOBALS['log']->debug("********** QCmodule was set: {$_REQUEST['qcmodule']}");
343         }
344         $controller = ControllerFactory::getController($_REQUEST['qcmodule']);
345         $controller->loadBean();
346         $controller->pre_save();
347         $GLOBALS['log']->debug("********** saving new {$controller->module}");
348         $controller->action_save();
349         //Relate the email to the new bean
350         if(isset($_REQUEST['sugarEmail']) && $_REQUEST['sugarEmail'] == 'true' && isset($_REQUEST['uid']) && !empty($_REQUEST['uid'])) {
351             $ie->email->retrieve($_REQUEST['uid']);
352         } elseif(isset($_REQUEST['uid']) && !empty($_REQUEST['uid']) && isset($_REQUEST['ieId']) && !empty($_REQUEST['ieId'])) {
353             $GLOBALS['log']->debug("********** Quick Create from non-imported message");
354             $ie->retrieve($_REQUEST['ieId']);
355             $ie->mailbox = $_REQUEST['mbox'];
356             $ie->connectMailserver();
357             $uid = $_REQUEST['uid'];
358             if($ie->protocol == 'imap') {
359                 $_REQUEST['uid'] = imap_msgno($ie->conn, $_REQUEST['uid']);
360             } else {
361                 $_REQUEST['uid'] = $ie->getCorrectMessageNoForPop3($_REQUEST['uid']);
362             }
363
364             if (!$ie->importOneEmail($_REQUEST['uid'], $uid)) {
365                 $ie->getDuplicateEmailId($_REQUEST['uid'], $uid);
366             } // id
367             $ie->email->retrieve($ie->email->id);
368             $GLOBALS['log']->debug("**********Imported Email");
369             $ie->email->assigned_user_id = $controller->bean->assigned_user_id;
370             $ie->email->assigned_user_name = $controller->bean->assigned_user_name;
371         }
372         if (isset($ie->email->id)) {
373                 if (empty($ie->email->parent_id)) {
374                     $ie->email->parent_id = $controller->bean->id;
375                     $ie->email->parent_type = $controller->module;
376                 } // if
377             $ie->email->status = 'read';
378             $ie->email->save();
379             $mod = strtolower($controller->module);
380             $ie->email->load_relationship($mod);
381             $ie->email->$mod->add($controller->bean->id);
382             if($controller->bean->load_relationship('emails')) {
383                 $controller->bean->emails->add($ie->email->id);
384             }
385             if ($controller->bean->module_dir == 'Cases') {
386                     if($controller->bean->load_relationship('contacts')) {
387                         $emailAddressWithName = $ie->email->from_addr;
388                         if (!empty($ie->email->reply_to_addr)) {
389                                 $emailAddressWithName = $ie->email->reply_to_addr;
390                         } // if
391
392                         $emailAddress = SugarEmailAddress::_cleanAddress($emailAddressWithName);
393                         $contactIds = $ie->email->emailAddress->getRelatedId($emailAddress, 'contacts');
394                         if (!empty($contactIds)) {
395                                 $controller->bean->contacts->add($contactIds);
396                         } // if
397                     } // if
398             } // if
399             echo $json->encode(array('id' => $ie->email->id));
400         }
401         break;
402
403     case "getImportForm":
404         $ie->retrieve($_REQUEST['ieId']);
405         //            $ie->mailbox = $_REQUEST['mailbox'];
406         $ie->setEmailForDisplay($_REQUEST['uid']);
407         $ret = $email->et->getImportForm($_REQUEST, $ie->email);
408         $out = trim($json->encode($ret, false));
409         echo $out;
410         break;
411
412     case "getRelateForm":
413         if (isset($_REQUEST['uid']) && !empty($_REQUEST['uid'])) {
414                 $uids = $json->decode(from_html($_REQUEST['uid']));
415                 $email->retrieve($uids[0]);
416             $ret = $email->et->getImportForm(array('showTeam' => false, 'showAssignTo' => false, 'showDelete' => false), $email,'RelateEditView');
417             $out = trim($json->encode($ret, false));
418         echo $out;
419         }
420     break;
421
422     case "getEmail2DetailView":
423         if (isset($_REQUEST['uid']) && !empty($_REQUEST['uid'])) {
424             $ret = $email->et->getDetailViewForEmail2($_REQUEST['uid']);
425             if( !isset($_REQUEST['print']) ||  $_REQUEST['print'] === FALSE)
426             {
427                 $out = trim($json->encode($ret, false));
428                 echo $out;
429             }
430             else
431                 echo $ret['html'];
432
433         }
434     break;
435
436     case "relateEmails":
437         if (isset($_REQUEST['uid']) && !empty($_REQUEST['uid']) &&
438                isset($_REQUEST['parent_id']) && !empty($_REQUEST['parent_id']) &&
439                isset($_REQUEST['parent_type']) && !empty($_REQUEST['parent_type'])) {
440             $uids = explode($app_strings['LBL_EMAIL_DELIMITER'], $_REQUEST['uid']);
441             $mod = strtolower($_REQUEST['parent_type']);
442             $modId = $_REQUEST['parent_id'];
443             foreach($uids as $id) {
444                 $email = new Email();
445                 $email->retrieve($id);
446                 $email->parent_id = $modId;
447                 $email->parent_type = $_REQUEST['parent_type'];
448                 $email->status = 'read';
449
450                 // BUG FIX BEGIN
451                 // Bug 50979 - relating a message in group inbox removes message
452                 if (empty($email->assigned_user_id))
453                 {
454                     $email->setFieldNullable('assigned_user_id');
455                 }
456                 $email->save();
457                 // Bug 50979 - reset assigned_user_id field defs
458                 if (empty($email->assigned_user_id))
459                 {
460                     $email->revertFieldNullable('assigned_user_id');
461                 }
462                 // BUG FIX END
463
464                 $email->load_relationship($mod);
465                 $email->$mod->add($modId);
466             }
467         }
468     break;
469
470
471     case "getAssignmentDialogContent":
472         $out = $email->distributionForm("");
473         $out = trim($json->encode($out, false));
474         echo $out;
475         break;
476     case "doAssignmentAssign":
477         $out = $email->et->doAssignment($_REQUEST['distribute_method'], $_REQUEST['ieId'], $_REQUEST['folder'], $_REQUEST['uids'], $_REQUEST['users']);
478         echo $out;
479         break;
480     case "doAssignmentDelete";
481     $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: doAssignmentDelete");
482     if(isset($_REQUEST['uids']) && !empty($_REQUEST['uids']) &&
483     isset($_REQUEST['ieId']) && !empty($_REQUEST['ieId']) &&
484     isset($_REQUEST['folder']) && !empty($_REQUEST['folder'])) {
485         $email->et->markEmails("deleted", $_REQUEST['ieId'], $_REQUEST['folder'], $_REQUEST['uids']);
486     } else {
487     }
488     break;
489     case "markEmail":
490         global $app_strings;
491         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: markEmail");
492         if(isset($_REQUEST['uids']) && !empty($_REQUEST['uids']) &&
493         isset($_REQUEST['type']) && !empty($_REQUEST['type']) &&
494         isset($_REQUEST['folder']) && !empty($_REQUEST['folder']) &&
495                 isset($_REQUEST['ieId']) && (!empty($_REQUEST['ieId']) || (empty($_REQUEST['ieId']) && strpos($_REQUEST['folder'], 'sugar::') !== false))
496         ) {
497                 $uid = $json->decode(from_html($_REQUEST['uids']));
498                 $uids = array();
499                 if(is_array($uid)) {
500                         $uids = $uid;
501                 } else {
502                                 if(strpos($uid, $app_strings['LBL_EMAIL_DELIMITER']) !== false) {
503                                         $uids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uid);
504                                 } else {
505                                         $uids[] = $uid;
506                                 }
507                 }   // else
508                 $uids = implode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
509                 $GLOBALS['log']->debug("********** EMAIL 2.0 - Marking emails $uids as {$_REQUEST['type']}");
510
511                 $ret = array();
512                 if(strpos($_REQUEST['folder'], 'sugar::') !== false && ($_REQUEST['type'] == 'deleted') && !ACLController::checkAccess('Emails', 'delete')) {
513                         $ret['status'] = false;
514                         $ret['message'] = $app_strings['LBL_EMAIL_DELETE_ERROR_DESC'];
515                 } else {
516                 $email->et->markEmails($_REQUEST['type'], $_REQUEST['ieId'], $_REQUEST['folder'], $uids);
517                         $ret['status'] = true;
518                 }
519                 $out = trim($json->encode($ret, false));
520                 echo $out;
521         } else {
522         }
523         break;
524
525     case "checkEmail2":
526         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: checkEmail2");
527
528         $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
529
530         $ret = array();
531         $ret['numberAccounts'] = count($showFolders);
532
533         $GLOBALS['log']->info("EMAIL2.0: async checkEmail - found [ ".$ret['numberAccounts']." ] accounts to check");
534
535         if(!empty($showFolders) && is_array($showFolders)) {
536             foreach($showFolders as $ieId) {
537                 $ieId = trim($ieId);
538
539                 if(!empty($ieId)) {
540                     $GLOBALS['log']->info("INBOUNDEMAIL: trying to check email for GUID [ {$ieId} ]");
541                     $ie->disconnectMailserver();
542                     $ie->retrieve($ieId);
543
544                     $ret[$ieId] = $ie->checkEmail2_meta();
545                 }
546             }
547         } else {
548             $GLOBALS['log']->info("EMAIL2.0: at checkEmail() async call - not subscribed accounts to check.");
549         }
550
551
552
553         $out = $json->encode($ret, true);
554         echo $out;
555         break;
556
557     case "checkEmail":
558         $GLOBALS['log']->info("[EMAIL] - Start checkEmail action for user [{$current_user->user_name}]");
559         if(isset($_REQUEST['ieId']) && !empty($_REQUEST['ieId'])) {
560             $ie->retrieve($_REQUEST['ieId']);
561             $ie->mailbox = (isset($_REQUEST['mbox']) && !empty($_REQUEST['mbox'])) ? $_REQUEST['mbox'] : "INBOX";
562             $ie->checkEmail(false);
563         } elseif(isset($_REQUEST['all']) && !empty($_REQUEST['all'])) {
564             $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
565
566             $GLOBALS['log']->info("[EMAIL] - checkEmail found ".count($showFolders)." accounts to check for user [{$current_user->user_name}]");
567
568             if(!empty($showFolders) && is_array($showFolders)) {
569                 foreach($showFolders as $ieId) {
570                     $ieId = trim($ieId);
571                     if(!empty($ieId)) {
572                         $GLOBALS['log']->info("[EMAIL] - Start checking email for GUID [{$ieId}] for user [{$current_user->user_name}]");
573                         $ie->disconnectMailserver();
574                         // If I-E not exist - skip check
575                         if (is_null($ie->retrieve($ieId))) {
576                             $GLOBALS['log']->info("[EMAIL] - Inbound with GUID [{$ieId}] not exist");
577                             continue;
578                         }
579                         $ie->checkEmail(false);
580                         $GLOBALS['log']->info("[EMAIL] - Done checking email for GUID [{$ieId}] for user [{$current_user->user_name}]");
581                     }
582                 }
583             } else {
584                 $GLOBALS['log']->info("EMAIL2.0: at checkEmail() async call - not subscribed accounts to check.");
585             }
586         }
587
588         $tree = $email->et->getMailboxNodes(true); // preserve cache files
589         $return = $tree->generateNodesRaw();
590         $out = $json->encode($return);
591         echo $out;
592         $GLOBALS['log']->info("[EMAIL] - Done checkEmail action for user [{$current_user->user_name}]");
593         break;
594
595     case "checkEmailProgress":
596         $GLOBALS['log']->info("[EMAIL] - Start checkEmail action for user [{$current_user->user_name}]");
597         if(isset($_REQUEST['ieId']) && !empty($_REQUEST['ieId'])) {
598             $ie->retrieve($_REQUEST['ieId']);
599             $ie->mailbox = (isset($_REQUEST['mbox']) && !empty($_REQUEST['mbox'])) ? $_REQUEST['mbox'] : "INBOX";
600             $synch = (isset($_REQUEST['synch']) && ($_REQUEST['synch'] == "true"));
601             if (!$ie->is_personal) {
602                 $return = array('status' => "done");
603             } else {
604                     if ($ie->protocol == "pop3") {
605                         $return = $ie->pop3_checkPartialEmail($synch);
606                     } else {
607                         $return = $ie->checkEmailIMAPPartial(false, $synch);
608                     } // else
609             } // if
610             $return['ieid'] = $ie->id;
611             $return['synch'] = $synch;
612                         if(isset($_REQUEST['totalcount']) && !empty($_REQUEST['totalcount']) && $_REQUEST['totalcount'] >= 0) {
613                                 if ($ie->protocol == "pop3") {
614                                         $return['totalcount'] = $_REQUEST['totalcount'];
615                                 } // else
616                         }
617             echo $json->encode($return);
618         } // if
619         break;
620
621     case "getAllFoldersTree":
622         $tree = $email->et->getMailboxNodes(true); // preserve cache files
623         $return = $tree->generateNodesRaw();
624         $out = $json->encode($return);
625         echo $out;
626         $GLOBALS['log']->info("[EMAIL] - Done checkEmail action for user [{$current_user->user_name}]");
627         break;
628
629     case "synchronizeEmail":
630         $GLOBALS['log']->info("[EMAIL] Start action synchronizeEmail for user [{$current_user->user_name}]");
631         $ie->syncEmail(true);
632         $tree = $email->et->getMailboxNodes(true);
633         $return = $tree->generateNodesRaw();
634         $out = $json->encode($return);
635         echo $out;
636         $GLOBALS['log']->info("[EMAIL] Done action synchronizeEmail for user [{$current_user->user_name}]");
637         break;
638
639     case "importEmail":
640         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: importEmail");
641         $ie->retrieve($_REQUEST['ieId']);
642         $ie->mailbox = $_REQUEST['mbox'];
643         $ie->connectMailserver();
644         $return = array();
645         $status = true;
646                 $count = 1;
647         if(strpos($_REQUEST['uid'], $app_strings['LBL_EMAIL_DELIMITER']) !== false) {
648             $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $_REQUEST['uid']);
649             foreach($exUids as $msgNo) {
650                 $uid = $msgNo;
651                 if($ie->protocol == 'imap') {
652                     $msgNo = imap_msgno($ie->conn, $msgNo);
653                     $status = $ie->importOneEmail($msgNo, $uid);
654                 } else {
655                         $status = $ie->importOneEmail($ie->getCorrectMessageNoForPop3($msgNo), $uid);
656                 } // else
657                 $return[] = $app_strings['LBL_EMAIL_MESSAGE_NO'] . " " . $count . ", " . $app_strings['LBL_STATUS'] . " " . ($status ? $app_strings['LBL_EMAIL_IMPORT_SUCCESS'] : $app_strings['LBL_EMAIL_IMPORT_FAIL']);
658                 $count++;
659                     if(($_REQUEST['delete'] == 'true') && $status && ($current_user->is_admin == 1 || $ie->group_id == $current_user->id)) {
660                         $ie->deleteMessageOnMailServer($uid);
661                         $ie->deleteMessageFromCache($uid);
662                         } // if
663             } // for
664         } else {
665             $msgNo = $_REQUEST['uid'];
666             if($ie->protocol == 'imap') {
667                 $msgNo = imap_msgno($ie->conn, $_REQUEST['uid']);
668                 $status = $ie->importOneEmail($msgNo, $_REQUEST['uid']);
669             } else {
670                 $status = $ie->importOneEmail($ie->getCorrectMessageNoForPop3($msgNo), $_REQUEST['uid']);
671             } // else
672             $return[] = $app_strings['LBL_EMAIL_MESSAGE_NO'] . " " . $count . ", " . $app_strings['LBL_STATUS'] . " " . ($status ? $app_strings['LBL_EMAIL_IMPORT_SUCCESS'] : $app_strings['LBL_EMAIL_IMPORT_FAIL']);
673
674             if(($_REQUEST['delete'] == 'true') && $status && ($current_user->is_admin == 1 || $ie->group_id == $current_user->id)) {
675                 $ie->deleteMessageOnMailServer($_REQUEST['uid']);
676                 $ie->deleteMessageFromCache($_REQUEST['uid']);
677             } // if
678         } // else
679         echo $json->encode($return);
680         break;
681
682     case "setReadFlag":
683         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: setReadFlag");
684         $ie->retrieve($_REQUEST['ieId']);
685         $ie->setReadFlagOnFolderCache($_REQUEST['mbox'], $_REQUEST['uid']);
686         $email->et->getListEmails($_REQUEST['ieId'], $_REQUEST['mbox'], 0, 'true');
687         //unlink("{$cacheRoot}/{$_REQUEST['ieId']}/folders/{$_REQUEST['mbox']}.php");
688         break;
689
690     case "deleteMessage":
691         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: deleteMessage");
692         if(isset($_REQUEST['uid']) && !empty($_REQUEST['uid']) && isset($_REQUEST['ieId']) && !empty($_REQUEST['ieId'])) {
693             $ie->retrieve($_REQUEST['ieId']);
694             $ie->mailbox = $_REQUEST['mbox'];
695
696             if($current_user->is_admin == 1 || $ie->group_id == $current_user->id) {
697                 $ie->deleteMessageOnMailServer($_REQUEST['uid']);
698                 $ie->deleteMessageFromCache($_REQUEST['uid']);
699             } else {
700                 $GLOBALS['log']->debug("*** ERROR: tried to delete an email for an account for which {$current_user->full_name} is not the owner!");
701                 echo "NOOP: error see log";
702             }
703         } else {
704             echo "error: missing credentials";
705         }
706         break;
707
708     case "getSingleMessage":
709         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: getSingleMessage");
710         if(isset($_REQUEST['uid']) && !empty($_REQUEST['uid']) && isset($_REQUEST['ieId']) && !empty($_REQUEST['ieId'])) {
711             // this method needs to guarantee UTF-8 charset - encoding detection
712             // and conversion is unreliable, and can break valid UTF-8 text
713             $out = $email->et->getSingleMessage($ie);
714
715             echo $json->encode($out);
716         } else {
717             echo "error: no UID";
718         }
719         break;
720
721     case "getSingleMessageFromSugar":
722         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: getSingleMessageFromSugar");
723         if(isset($_REQUEST['uid']) && !empty($_REQUEST['uid'])) {
724             $email->retrieve($_REQUEST['uid']);
725             //$email->description_html = from_html($email->description_html);
726             $ie->email = $email;
727
728             if($email->status == 'draft' || $email->type == 'draft') {
729                 // forcing an editview since we are looking at a draft message
730                 global $current_user;
731                 $ret = $ie->email->et->displayComposeEmail($email);
732
733                 $ret = $ie->email->et->getDraftAttachments($ret, $ie);
734                 $ret = $ie->email->et->getFromAllAccountsArray($ie, $ret);
735
736
737                 $out = $json->encode($ret, true);
738                 echo $out;
739             } else {
740                 $out = $ie->displayOneEmail($_REQUEST['uid'], $_REQUEST['mbox']);
741                 $out['meta']['email']['description'] =
742                         empty($email->description_html) ? str_replace("\n", "\n<BR/>", $email->description) : $email->description_html;
743                 $out['meta']['email']['date_start'] = $email->date_start;
744                 $out['meta']['email']['time_start'] = $email->time_start;
745                 $out['meta']['ieId'] = $_REQUEST['ieId'];
746                 $out['meta']['mbox'] = $_REQUEST['mbox'];
747                 $out['meta']['email']['toaddrs'] = $email->et->generateExpandableAddrs($out['meta']['email']['toaddrs']);
748                         if(!empty($out['meta']['email']['cc_addrs'])) {
749                     $ccs = $email->et->generateExpandableAddrs($out['meta']['email']['cc_addrs']);
750                             $out['meta']['email']['cc'] = <<<eoq
751                                         <tr>
752                                                 <td NOWRAP valign="top" class="displayEmailLabel">
753                                                         {$app_strings['LBL_EMAIL_CC']}:
754                                                 </td>
755                                                 <td class="displayEmailValue">
756                                                         {$ccs}
757                                                 </td>
758                                         </tr>
759 eoq;
760                         }
761                 echo $json->encode($out);
762             }
763         } else {
764             echo "error: no UID";
765         }
766         break;
767
768     case "getMultipleMessages":
769         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: getMultipleMessages");
770         if(isset($_REQUEST['uid']) && !empty($_REQUEST['uid']) && isset($_REQUEST['ieId']) && !empty($_REQUEST['ieId'])) {
771             $exUids = explode(",", $_REQUEST['uid']);
772
773             $out = array();
774             foreach($exUids as $k => $uid) {
775                 if($email->et->validCacheFileExists($_REQUEST['ieId'], 'messages', $_REQUEST['mbox'].$uid.".php")) {
776                     $msg = $email->et->getCacheValue($_REQUEST['ieId'], 'messages', $_REQUEST['mbox'].$uid.".php", 'out');
777                 } else {
778                     $ie->retrieve($_REQUEST['ieId']);
779                     $ie->mailbox = $_REQUEST['mbox'];
780                     $ie->setEmailForDisplay($uid, false, true);
781                     $msg = $ie->displayOneEmail($uid, $_REQUEST['mbox']);
782                     $email->et->writeCacheFile('out', $msg, $_REQUEST['ieId'], 'messages', "{$_REQUEST['mbox']}{$uid}.php");
783                 }
784
785                 $out[] = $msg;
786             }
787             echo $json->encode($out);
788         } else {
789             echo "error: no UID";
790         }
791         break;
792
793     case "getMultipleMessagesFromSugar":
794         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: getMultipleMessagesFromSugar");
795         if(isset($_REQUEST['uid']) && !empty($_REQUEST['uid'])) {
796             $exIds = explode(",", $_REQUEST['uid']);
797             $out = array();
798
799             foreach($exIds as $id) {
800                 $e = new Email();
801                 $e->retrieve($id);
802                 $e->description_html = from_html($e->description_html);
803                 $ie->email = $e;
804                 $out[] = $ie->displayOneEmail($id, $_REQUEST['mbox']);
805             }
806
807             echo $json->encode($out);
808         }
809
810         break;
811         ////    END MESSAGE HANDLING
812         ///////////////////////////////////////////////////////////////////////////
813
814
815
816         ///////////////////////////////////////////////////////////////////////////
817         ////    LIST VIEW
818     case "getMessageCount":
819         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: getMessageCount");
820
821         $out = $ie->getCacheCount($_REQUEST['mbox']);
822         echo $json->encode($out);
823         break;
824
825     case "getMessageList":
826         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: getMessageListJSON");
827         if(isset($_REQUEST['ieId']) && !empty($_REQUEST['ieId'])) {
828             // user view preferences
829             $email->et->saveListView($_REQUEST['ieId'], $_REQUEST['mbox']);
830             // list output
831             $ie->retrieve($_REQUEST['ieId']);
832             if(isset($_REQUEST['start']) && isset($_REQUEST['limit'])) {
833                     $page = ceil($_REQUEST['start'] / $_REQUEST['limit']) + 1;
834                 } else {
835                         $page = 1;
836                 }
837             $list = $ie->displayFolderContents($_REQUEST['mbox'], $_REQUEST['forceRefresh'], $page);
838             $count = $ie->getCacheCount($_REQUEST['mbox']);
839             $unread = $ie->getCacheUnread($_REQUEST['mbox']);
840             $out = $email->et->jsonOuput($list, 'Email', $count, true, $unread);
841
842             @ob_end_clean();
843             ob_start();
844             echo $out;
845             ob_end_flush();
846             //die();
847         } else {
848             echo "error: no ieID";
849         }
850         break;
851
852     case "getMessageListSugarFolders":
853         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: getMessageListSugarFoldersJSON");
854         if(isset($_REQUEST['ieId']) && !empty($_REQUEST['ieId'])) {
855             // user view preferences
856             $email->et->saveListView($_REQUEST['ieId'], "SUGAR.{$_REQUEST['mbox']}");
857             if(isset($_REQUEST['start']) && isset($_REQUEST['limit'])) {
858                     $page = ceil($_REQUEST['start'] / $_REQUEST['limit']) + 1;
859                 } else {
860                         $page = 1;
861                 }
862             if(!isset($_REQUEST['sort']) || !isset($_REQUEST['dir'])) {
863                 $_REQUEST['sort'] = '';
864                 $_REQUEST['dir']  = '';
865             }
866             $emailSettings = $current_user->getPreference('emailSettings', 'Emails');
867             // cn: default to a low number until user specifies otherwise
868             if(empty($emailSettings['showNumInList'])) {
869                 $emailSettings['showNumInList'] = 20;
870             }
871
872                         // jchi #9424, get sort and direction from user preference
873                         $sort = 'date';
874                         $direction = 'desc';
875                         $sortSerial = $current_user->getPreference('folderSortOrder', 'Emails');
876                         if(!empty($sortSerial) && !empty($_REQUEST['ieId']) && !empty($_REQUEST['mbox'])) {
877                                 $sortArray = unserialize($sortSerial);
878                                 $GLOBALS['log']->debug("********** EMAIL 2.0********** ary=".print_r($sortArray,true).' id='.$_REQUEST['ieId'].'; box='.$_REQUEST['mbox']);
879                                 $sort = $sortArray[$_REQUEST['ieId']][$_REQUEST['mbox']]['current']['sort'];
880                                 $direction = $sortArray[$_REQUEST['ieId']][$_REQUEST['mbox']]['current']['direction'];
881                         }
882                         //set sort and direction to user predference
883                         if(!empty($_REQUEST['sort']) && !empty($_REQUEST['dir'])) {
884                                 $email->et->saveListViewSortOrder($_REQUEST['ieId'], $_REQUEST['mbox'], $_REQUEST['sort'], $_REQUEST['dir']);
885                                 $sort = $_REQUEST['sort'];
886                                 $direction = $_REQUEST['dir'];
887                         } else {
888                                 $_REQUEST['sort'] = '';
889                                 $_REQUEST['dir'] = '';
890                         }
891                         //end
892
893             $metalist = $email->et->folder->getListItemsForEmailXML($_REQUEST['ieId'], $page,
894             $emailSettings['showNumInList'], $sort, $direction);
895             $count = $email->et->folder->getCountItems($_REQUEST['ieId']);
896             $unread = $email->et->folder->getCountUnread($_REQUEST['ieId']);
897             $out = $email->et->jsonOuput($metalist, 'Email', $count, false, $unread);
898
899             @ob_end_clean();
900             ob_start();
901             echo $out;
902             ob_end_flush();
903         } else {
904             echo "error: no ieID";
905         }
906         break;
907         ////    END LIST VIEW
908         ///////////////////////////////////////////////////////////////////////////
909
910
911
912         ///////////////////////////////////////////////////////////////////////////
913         ////    FOLDER ACTIONS
914     case "emptyTrash":
915         $email->et->emptyTrash($ie);
916         break;
917
918     case "clearInboundAccountCache":
919         $email->et->clearInboundAccountCache($_REQUEST['ieId']);
920         break;
921
922     case "updateSubscriptions":
923         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: updateSubscriptions");
924         if(isset($_REQUEST['subscriptions']) && !empty($_REQUEST['subscriptions']))
925         {
926             $subs = explode("::", $_REQUEST['subscriptions']);
927             $childrenSubs = array();
928             //Find all children of the group folder subscribed to and add
929             //them to the list of folders to show.
930             foreach ($subs as $singleSub)
931                 $email->et->folder->findAllChildren($singleSub, $childrenSubs);
932
933             $subs = array_merge($subs, $childrenSubs);
934             $email->et->folder->setSubscriptions($subs);
935         }
936         elseif(empty($_REQUEST['subscriptions'])) {
937             $email->et->folder->clearSubscriptions();
938         }
939         break;
940
941     case "refreshSugarFolders":
942         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: refreshSugarFolders");
943         $rootNode = new ExtNode('','');
944         $folderOpenState = $current_user->getPreference('folderOpenState', 'Emails');
945         $folderOpenState = (empty($folderOpenState)) ? "" : $folderOpenState;
946         $ret = $email->et->folder->getUserFolders($rootNode, unserialize($folderOpenState), $current_user, true);
947         $out = $json->encode($ret);
948         echo $out;
949         break;
950
951
952
953     case "getFoldersForSettings":
954         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: getFoldersForSettings");
955         $ret = $email->et->folder->getFoldersForSettings($current_user);
956         $out = $json->encode($ret);
957         echo $out;
958         break;
959
960     case "moveEmails":
961         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: moveEmails");
962         $ie->moveEmails($_REQUEST['sourceIeId'], $_REQUEST['sourceFolder'], $_REQUEST['destinationIeId'], $_REQUEST['destinationFolder'], $_REQUEST['emailUids']);
963         break;
964
965     case "saveNewFolder":
966         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: saveNewFolder");
967         if(isset($_REQUEST['folderType']) && !empty($_REQUEST['folderType'])) {
968             switch($_REQUEST['folderType']) {
969                 case "sugar":
970                     $ret = $email->et->saveNewFolder($_REQUEST['nodeLabel'], $_REQUEST['parentId']);
971                     $out = $json->encode($ret);
972                     echo $out;
973                     break;
974
975                 case "imap":
976                     $ie->retrieve($_REQUEST['ieId']);
977                     $ie->connectMailserver();
978                     $ie->saveNewFolder($_REQUEST['newFolderName'], $_REQUEST['mbox']);
979                     break;
980             }
981         } else {
982             echo "NOOP: no folderType defined";
983         }
984         break;
985
986     case "setFolderViewSelection": // flows into next case statement
987         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: setFolderViewSelection");
988         $viewFolders = $_REQUEST['ieIdShow'];
989         $current_user->setPreference('showFolders', base64_encode(serialize($viewFolders)), '', 'Emails');
990         $tree = $email->et->getMailboxNodes(false);
991         $return = $tree->generateNodesRaw();
992         $out = $json->encode($return);
993         echo $out;
994         break;
995
996     case "deleteFolder":
997         $v = $app_strings['LBL_NONE'];
998         $return = array();
999         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: deleteFolder");
1000         if(isset($_REQUEST['folderType']) && !empty($_REQUEST['folderType'])) {
1001             switch($_REQUEST['folderType']) {
1002                 case "sugar":
1003                     $status = $email->et->folder->deleteChildrenCascade($_REQUEST['folder_id']);
1004                     if ($status == true) {
1005                         $return['status'] = true;
1006                         $return['folder_id'] = $_REQUEST['folder_id'];
1007                     } else {
1008                         $return['status'] = false;
1009                         $return['errorMessage'] = $app_strings['LBL_EMAIL_ERROR_DELETE_GROUP_FOLDER'];
1010                     }
1011                     break;
1012
1013                 case "imap":
1014                     $ie->retrieve($_REQUEST['ieId']);
1015                     $ie->connectMailserver();
1016                     $returnArray = $ie->deleteFolder($_REQUEST['mbox']);
1017                     $status = $returnArray['status'];
1018                     $errorMessage = $returnArray['errorMessage'];
1019                     if ($status == true) {
1020                         $return['status'] = true;
1021                         $return['mbox'] = $_REQUEST['mbox'];
1022                         $return['ieId'] = $_REQUEST['ieId'];
1023                     } else {
1024                         $return['status'] = false;
1025                         $return['errorMessage'] = $errorMessage;
1026                     }
1027                     break;
1028             }
1029         } else {
1030                 $return['status'] = false;
1031                 $return['errorMessage'] =  "NOOP: no folderType defined";
1032         }
1033         $out = $json->encode($return);
1034         echo $out;
1035         break;
1036     case "renameFolder":
1037         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: renameFolder");
1038
1039         if(isset($_REQUEST['ieId']) && isset($_REQUEST['oldFolderName']) && !empty($_REQUEST['oldFolderName'])
1040         && isset($_REQUEST['newFolderName']) && !empty($_REQUEST['newFolderName'])) {
1041             $ie->retrieve($_REQUEST['ieId']);
1042             $ie->renameFolder($_REQUEST['oldFolderName'], $_REQUEST['newFolderName']);
1043         } elseif(isset($_REQUEST['folderId']) && !empty($_REQUEST['folderId']) && isset($_REQUEST['newFolderName']) && !empty($_REQUEST['newFolderName'])) {
1044             if(is_guid($_REQUEST['folderId'])) {
1045                 $email->et->folder->retrieve($_REQUEST['folderId']);
1046                 $email->et->folder->name = $_REQUEST['newFolderName'];
1047                 $email->et->folder->save();
1048             } else {
1049                 echo "NOOP - not a Sugar Folder";
1050             }
1051         }
1052     case "moveFolder":
1053         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: moveFolder");
1054         if(isset($_REQUEST['folderId']) && !empty($_REQUEST['folderId']) && isset($_REQUEST['newParentId']) && !empty($_REQUEST['newParentId']) && $_REQUEST['newParentId'] != $_REQUEST['folderId']) {
1055             if(is_guid($_REQUEST['folderId']) && is_guid($_REQUEST['newParentId'])) {
1056                 $email->et->folder->retrieve($_REQUEST['folderId']);
1057                 $email->et->folder->updateFolder(array(
1058                     "record"        => $_REQUEST['folderId'],
1059                     "name"          => $email->et->folder->name,
1060                     "parent_folder" => $_REQUEST['newParentId'],
1061                     "team_id"       => $email->et->folder->team_id,
1062                     "team_set_id"       => $email->et->folder->team_set_id,
1063                 ));
1064             } else {
1065                 echo "NOOP - not a Sugar Folder";
1066             }
1067         }
1068         break;
1069     case "getGroupFolder":
1070             $email->et->folder->retrieve($_REQUEST['folderId']);
1071             $_REQUEST['record'] = $_REQUEST['folderId'];
1072             $ret = array();
1073             $ret['folderId'] = $email->et->folder->id;
1074             $ret['folderName'] = $email->et->folder->name;
1075             $ret['parentFolderId'] = $email->et->folder->parent_folder;
1076             $out = $json->encode($ret);
1077             echo $out;
1078         break;
1079
1080
1081     case "rebuildFolders":
1082         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: rebuildFolders");
1083         $tree = $email->et->getMailboxNodes(false);
1084         $return = $tree->generateNodesRaw();
1085         $out = $json->encode($return);
1086         echo $out;
1087         break;
1088
1089     case "setFolderOpenState":
1090         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: setFolderOpenState");
1091         $email->et->saveFolderOpenState($_REQUEST['focusFolder'], $_REQUEST['focusFolderOpen']);
1092         break;
1093
1094     case "saveListViewSortOrder":
1095         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: saveListViewSortOrder");
1096         $email->et->saveListViewSortOrder($_REQUEST['ieId'], $_REQUEST['focusFolder'], $_REQUEST['sortBy'], $_REQUEST['reverse']);
1097         break;
1098         ////    END FOLDER ACTIONS
1099         ///////////////////////////////////////////////////////////////////////////
1100
1101         ///////////////////////////////////////////////////////////////////////////
1102         ////    INBOUND EMAIL ACCOUNTS
1103
1104     case "retrieveAllOutbound":
1105         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: retrieveAllOutbound");
1106         global $current_user;
1107         $oe = new OutboundEmail();
1108                 $outbounds = $oe->getUserMailers($current_user);
1109                 $results = array('outbound_account_list' => $outbounds, 'count' => count($outbounds));
1110                 $out = $json->encode($results, false);
1111                 echo $out;
1112
1113         break;
1114
1115     case "editOutbound":
1116         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: editOutbound");
1117         if(isset($_REQUEST['outbound_email']) && !empty($_REQUEST['outbound_email'])) {
1118             $oe = new OutboundEmail();
1119             $oe->retrieve($_REQUEST['outbound_email']);
1120
1121             $ret = array();
1122
1123             foreach($oe->field_defs as $def) {
1124                 $ret[$def] = $oe->$def;
1125             }
1126             $ret['mail_smtppass']=''; // don't send back the password
1127             $ret['has_password'] =  isset($oe->mail_smtppass);
1128
1129             $out = $json->encode($ret, true);
1130             echo $out;
1131
1132         } else {
1133             echo "NOOP";
1134         }
1135         break;
1136
1137     case "deleteOutbound":
1138         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: deleteOutbound");
1139         if(isset($_REQUEST['outbound_email']) && !empty($_REQUEST['outbound_email']))
1140         {
1141             $oe = new OutboundEmail();
1142             global $current_user;
1143             $oe->retrieve($_REQUEST['outbound_email']);
1144             $affectedInboundAccounts = $oe->getAssociatedInboundAccounts($current_user);
1145
1146             //Check if the user has confirmed he wants to delete the email account even if associated to an inbound accnt.
1147             $confirmedDelete = ( isset($_REQUEST['confirm']) && $_REQUEST['confirm'] ) ? TRUE : FALSE;
1148
1149             if( count($affectedInboundAccounts) > 0 && !$confirmedDelete)
1150             {
1151                 $results = array('is_error' => true, 'error_message' => $app_strings['LBL_EMAIL_REMOVE_SMTP_WARNING'] , 'outbound_email' => $_REQUEST['outbound_email']);
1152             }
1153             else
1154             {
1155                 $oe->delete();
1156                 $results = array('is_error' => false, 'error_message' => '');
1157             }
1158
1159             $out = $json->encode($results);
1160             @ob_end_clean();
1161             ob_start();
1162             echo $out;
1163             ob_end_flush();
1164             die();
1165         }
1166         else
1167         {
1168             echo "NOOP";
1169         }
1170         break;
1171
1172     case "saveOutbound":
1173         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: saveOutbound");
1174
1175         $oe = new OutboundEmail();
1176         $oe->id = $_REQUEST['mail_id'];
1177         $oe->retrieve($oe->id);
1178         $oe->name = $_REQUEST['mail_name'];
1179         $type = empty($_REQUEST['type']) ? 'user' : $_REQUEST['type'];
1180         $oe->type = $type;
1181         $oe->user_id = $current_user->id;
1182         $oe->mail_sendtype = "SMTP";
1183         $oe->mail_smtptype = $_REQUEST['mail_smtptype'];
1184         $oe->mail_smtpserver = $_REQUEST['mail_smtpserver'];
1185         $oe->mail_smtpport = $_REQUEST['mail_smtpport'];
1186         $oe->mail_smtpssl = $_REQUEST['mail_smtpssl'];
1187         $oe->mail_smtpauth_req = isset($_REQUEST['mail_smtpauth_req']) ? 1 : 0;
1188         $oe->mail_smtpuser = $_REQUEST['mail_smtpuser'];
1189         if(!empty($_REQUEST['mail_smtppass'])) {
1190             $oe->mail_smtppass = $_REQUEST['mail_smtppass'];
1191         }
1192         $oe = $oe->save();
1193                 echo $oe->id;
1194         break;
1195
1196     case "saveDefaultOutbound":
1197                 global $current_user;
1198         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: saveDefaultOutbound");
1199         $outbound_id = empty($_REQUEST['id']) ? "" : $_REQUEST['id'];
1200         $ie = new InboundEmail();
1201                 $ie->setUsersDefaultOutboundServerId($current_user, $outbound_id);
1202         break;
1203     case "testOutbound":
1204         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: testOutbound");
1205
1206         $pass = '';
1207         if(!empty($_REQUEST['mail_smtppass'])) {
1208             $pass = $_REQUEST['mail_smtppass'];
1209         } elseif(isset($_REQUEST['mail_name'])) {
1210             $oe = new OutboundEmail();
1211             $oe = $oe->getMailerByName($current_user, $_REQUEST['mail_name']);
1212             if(!empty($oe)) {
1213                 $pass = $oe->mail_smtppass;
1214             }
1215         }
1216         $out = $email->sendEmailTest($_REQUEST['mail_smtpserver'], $_REQUEST['mail_smtpport'], $_REQUEST['mail_smtpssl'],
1217                                                                 (isset($_REQUEST['mail_smtpauth_req']) ? 1 : 0), $_REQUEST['mail_smtpuser'],
1218                                                                 $pass, $_REQUEST['outboundtest_from_address'], $_REQUEST['outboundtest_from_address']);
1219
1220         $out = $json->encode($out);
1221         echo $out;
1222         break;
1223
1224     case "rebuildShowAccount":
1225         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: rebuildShowAccount");
1226         $ret = $email->et->getShowAccountsOptions($ie);
1227         $results = array('account_list' => $ret, 'count' => count($ret));
1228         $out = $json->encode($results);
1229         echo $out;
1230         break;
1231
1232     case "rebuildShowAccountForSearch":
1233         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: rebuildShowAccount");
1234         $ret = $email->et->getShowAccountsOptionsForSearch($ie);
1235         $out = $json->encode($ret);
1236         echo $out;
1237         break;
1238
1239     case "deleteIeAccount":
1240         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: deleteIeAccount");
1241         if(isset($_REQUEST['group_id']) && $_REQUEST['group_id'] == $current_user->id) {
1242             $ret = array();
1243             $updateFolders = array();
1244                 $ret['id'] = $_REQUEST['ie_id'];
1245             $out = $json->encode($ret);
1246             $ie->hardDelete($_REQUEST['ie_id']);
1247             $out = $json->encode(array('id' => $_REQUEST['ie_id']));
1248             echo $out;
1249
1250             foreach ($showFolders as $id) {
1251                 if ($id != $_REQUEST['ie_id']) {
1252                     $updateFolders[] = $id;
1253                 }
1254             }
1255
1256             $showStore = base64_encode(serialize($updateFolders));
1257             $current_user->setPreference('showFolders', $showStore, 0, 'Emails');
1258         }
1259         break;
1260
1261     case "saveIeAccount":
1262         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: saveIeAccount");
1263         if(isset($_REQUEST['server_url']) && !empty($_REQUEST['server_url'])) {
1264             if(false === $ie->savePersonalEmailAccount($current_user->id, $current_user->user_name, false)) {
1265                 $ret = array('error' => 'error');
1266                 $out = $json->encode($ret);
1267                 echo $out;
1268             } else {
1269                 $ie->retrieve($_REQUEST['ie_id']);
1270                                 if (!isset($ie->created_by_link)) {
1271                                         $ie->created_by_link = null;
1272                                 }
1273                                 if (!isset($ie->modified_user_id_link)) {
1274                                         $ie->modified_user_id_link = null;
1275                                 }
1276                                 if (!is_array($showFolders)) {
1277                                         $showFolders = array();
1278                                 }
1279                 if(!in_array($ie->id, $showFolders)) {
1280                     $showFolders[] = $ie->id;
1281                     $showStore = base64_encode(serialize($showFolders));
1282                     $current_user->setPreference('showFolders', $showStore, 0, 'Emails');
1283                 }
1284
1285                 foreach($ie->field_defs as $k => $v) {
1286                         if (isset($v['type']) && ($v['type'] == 'link')) {
1287                                 continue;
1288                         }
1289                     if($k == 'stored_options') {
1290                         $ie->$k = unserialize(base64_decode($ie->$k));
1291                             if (isset($ie->stored_options['from_name'])) {
1292                                 $ie->stored_options['from_name'] = from_html($ie->stored_options['from_name']);
1293                             }
1294                     } elseif($k == 'service') {
1295                         $service = explode("::", $ie->$k);
1296                         $retService = array();
1297
1298                         foreach($service as $serviceK => $serviceV) {
1299                             if(!empty($serviceV)) {
1300                                 $retService[$serviceK] = $serviceV;
1301                             }
1302                         }
1303
1304                         $ie->$k = $retService;
1305                     }
1306
1307                     if (isset($ie->$k))
1308                     $ret[$k] = $ie->$k;
1309                 }
1310
1311                 $out = $json->encode($ret);
1312                 echo $out;
1313             }
1314
1315             //If the user is saving the username/password then we need to update the outbound account.
1316             $outboundMailUser = (isset($_REQUEST['mail_smtpuser'])) ? $_REQUEST['mail_smtpuser'] : "";
1317             $outboundMailPass = (isset($_REQUEST['mail_smtppass'])) ? $_REQUEST['mail_smtppass'] : "";
1318             $outboundMailId = (isset($_REQUEST['outbound_email'])) ? $_REQUEST['outbound_email'] : "";
1319
1320             if( !empty($outboundMailUser) && !empty($outboundMailPass) && !empty($outboundMailId) )
1321             {
1322                 $oe = new OutboundEmail();
1323                 $oe->retrieve($outboundMailId);
1324                 $oe->mail_smtpuser = $outboundMailUser;
1325                 $oe->mail_smtppass = $outboundMailPass;
1326                 $oe->save();
1327             }
1328
1329         } else {
1330             echo "NOOP";
1331         }
1332         break;
1333
1334     case "getIeAccount":
1335         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: getIeAccount");
1336         $ie->retrieve($_REQUEST['ieId']);
1337         if($ie->group_id == $current_user->id) {
1338             $ret = array();
1339
1340             foreach($ie->field_defs as $k => $v) {
1341                 if($k == 'stored_options') {
1342                     $ie->$k = unserialize(base64_decode($ie->$k));
1343                     if (isset($ie->stored_options['from_name'])) {
1344                         $ie->stored_options['from_name'] = from_html($ie->stored_options['from_name']);
1345                     }
1346                 } elseif($k == 'service') {
1347                     $service = explode("::", $ie->$k);
1348                     $retService = array();
1349                     foreach($service as $serviceK => $serviceV) {
1350                         if(!empty($serviceV)) {
1351                             $retService[$serviceK] = $serviceV;
1352                         }
1353                     }
1354
1355                     $ie->$k = $retService;
1356                 }
1357
1358                 $ret[$k] = $ie->$k;
1359             }
1360             unset($ret['email_password']); // no need to send the password out
1361
1362             $out = $json->encode($ret);
1363         } else {
1364             $out = "NOOP: ID mismatch";
1365         }
1366         echo $out;
1367         break;
1368         ////    END INBOUND EMAIL ACCOUNTS
1369         ///////////////////////////////////////////////////////////////////////////
1370
1371
1372
1373         ///////////////////////////////////////////////////////////////////////////
1374         ////    SEARCH
1375     case "search":
1376         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: search");
1377         if(isset($_REQUEST['subject']) && !empty($_REQUEST['subject']) && isset($_REQUEST['ieId']) && !empty($_REQUEST['ieId'])) {
1378             $metalist = $ie->search($_REQUEST['ieId'], $_REQUEST['subject']);
1379             if (!isset($_REQUEST['page'])) {
1380                 $_REQUEST['page'] = 1;
1381             }
1382             $_REQUEST['pageSize'] = count($metalist['out']);
1383             $out = $email->et->xmlOutput($metalist, 'Email', false);
1384             @ob_end_clean();
1385             ob_start();
1386             header("Content-type: text/xml");
1387             echo $out;
1388             ob_end_flush();
1389             die();
1390         } else {
1391             echo "NOOP: no search criteria found";
1392         }
1393         break;
1394
1395     case "searchAdvanced":
1396         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: searchAdvanced");
1397
1398         $metalist = $email->searchImportedEmails();
1399         $out = $email->et->jsonOuput($metalist, 'Email', $metalist['totalCount']);
1400
1401         @ob_end_clean();
1402         ob_start();
1403         echo $out;
1404         ob_end_flush();
1405         die();
1406
1407         break;
1408         ////    END SEARCH
1409         ///////////////////////////////////////////////////////////////////////////
1410
1411
1412
1413         ///////////////////////////////////////////////////////////////////////////
1414         ////    SETTINGS
1415     case "loadPreferences":
1416         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: loadPreferences");
1417         $prefs = $email->et->getUserPrefsJS();
1418         $out = $json->encode($prefs);
1419         echo $out;
1420         break;
1421
1422     case "saveSettingsGeneral":
1423         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: saveSettingsGeneral");
1424         $emailSettings = array();
1425         $emailSettings['emailCheckInterval'] = $_REQUEST['emailCheckInterval'];
1426         //$emailSettings['autoImport'] = isset($_REQUEST['autoImport']) ? '1' : '0';
1427         $emailSettings['alwaysSaveOutbound'] = '1';
1428         $emailSettings['sendPlainText'] = isset($_REQUEST['sendPlainText']) ? '1' : '0';
1429         $emailSettings['showNumInList'] = $_REQUEST['showNumInList'];
1430         $emailSettings['defaultOutboundCharset'] = $_REQUEST['default_charset'];
1431         $current_user->setPreference('emailSettings', $emailSettings, '', 'Emails');
1432
1433         // signature
1434         $current_user->setPreference('signature_default', $_REQUEST['signature_id']);
1435         $current_user->setPreference('signature_prepend', (isset($_REQUEST['signature_prepend'])) ? true : false);
1436
1437         $out = $json->encode($email->et->getUserPrefsJS());
1438         echo $out;
1439         break;
1440
1441     case "setPreference":
1442         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: setPreference");
1443         if(isset($_REQUEST['prefName']) && isset($_REQUEST['prefValue'])) {
1444             // handle potential JSON encoding
1445             if(isset($_REQUEST['decode'])) {
1446                 $_REQUEST['prefValue'] = $json->decode(from_html($_REQUEST['prefValue']));
1447             }
1448
1449             $current_user->setPreference($_REQUEST['prefName'], $_REQUEST['prefValue'], '', 'Emails');
1450         }
1451         break;
1452         ////    END SETTINGS
1453         ///////////////////////////////////////////////////////////////////////////
1454
1455
1456
1457
1458         ///////////////////////////////////////////////////////////////////////////
1459         ////    ADDRESS BOOK
1460
1461     case "editContact":
1462         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: editContact");
1463         if(isset($_REQUEST['id']) && !empty($_REQUEST['id'])) {
1464             $module = "Contacts";
1465             $ret = $email->et->getEditContact($_REQUEST['id'], $module);
1466         }
1467         $out = $json->encode($ret);
1468         echo $out;
1469         break;
1470
1471
1472         /* The four calls below all have the same return signature */
1473     case "removeContact":
1474         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: removeContacts");
1475         if(strpos($_REQUEST['ids'], "::") !== false) {
1476             $removeIds = explode("::", $_REQUEST['ids']);
1477         } else {
1478             $removeIds[] = $_REQUEST['ids'];
1479         }
1480         $email->et->removeContacts($removeIds);
1481
1482     case "saveContactEdit":
1483         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: saveContactEdit");
1484         if(isset($_REQUEST['args']) && !empty($_REQUEST['args'])) {
1485             $email->et->saveContactEdit($_REQUEST['args']);
1486         }
1487         // flow into getUserContacts();
1488     case "addContact":
1489         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: addContacts");
1490         $contacts = array();
1491
1492         if(isset($_REQUEST['bean_module']) && !empty($_REQUEST['bean_module']) && isset($_REQUEST['bean_id']) && !empty($_REQUEST['bean_id'])) {
1493             $contacts[$_REQUEST['bean_id']] = array(
1494             'id' => $_REQUEST['bean_id'],
1495             'module' => $_REQUEST['bean_module']
1496             );
1497             $email->et->setContacts($contacts);
1498         }
1499
1500     case "addContactsMultiple":
1501         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: addContacts");
1502         if (isset($_REQUEST['contactData'])) {
1503             $contacts = $json->decode(from_HTML($_REQUEST['contactData']));
1504             if ($contacts) {
1505                 //_ppd($contacts);
1506                 $email->et->setContacts($contacts);
1507             }
1508         }
1509
1510     case "getUserContacts":
1511         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: getUserContacts");
1512         $contacts = $email->et->getContacts();
1513
1514         if(is_array($contacts) && !empty($contacts)) {
1515             $ret = $email->et->getUserContacts($contacts, $current_user);
1516             $out = $json->encode($ret);
1517             echo $out;
1518         } else {
1519             echo "{}";
1520         }
1521    break;
1522
1523
1524         // address book search
1525     case "getUnionData":
1526         $wheres = array();
1527         $person;
1528         if(isset($_REQUEST['first_name']) && !empty($_REQUEST['first_name'])) {
1529             $wheres['first_name'] = $_REQUEST['first_name'];
1530         }
1531         if(isset($_REQUEST['last_name']) && !empty($_REQUEST['last_name'])) {
1532             $wheres['last_name'] = $_REQUEST['last_name'];
1533         }
1534         if(isset($_REQUEST['email_address']) && !empty($_REQUEST['email_address'])) {
1535             $wheres['email_address'] = $_REQUEST['email_address'];
1536         }
1537                 if(isset($_REQUEST['person']) && !empty($_REQUEST['person'])) {
1538             $person = $_REQUEST['person'];
1539         }
1540         $q = $email->et->_getPeopleUnionQuery($wheres , $person);
1541         $r = $ie->db->limitQuery($q, 0, 25, true);
1542
1543         $out = array();
1544         while($a = $ie->db->fetchByAssoc($r)) {
1545             $person = array();
1546             $person['id'] = $a['id'];
1547             $person['module'] = $a['module'];
1548             $person['full_name'] = $locale->getLocaleFormattedName($a['first_name'], $a['last_name'],'');
1549             $person['email_address'] = $a['email_address'];
1550             $out[] = $person;
1551         }
1552
1553         $ret = $json->encode($out, true);
1554         echo $ret;
1555         break;
1556
1557     case "getAddressSearchResults":
1558         $wheres = array();
1559         $person = 'contacts';
1560         $relatedBeanInfo = '';
1561                 if(isset($_REQUEST['related_bean_id']) && !empty($_REQUEST['related_bean_id'])) {
1562             $isRelatedSearch = true;
1563             $relatedBeanInfo['related_bean_id'] = $_REQUEST['related_bean_id'];
1564             $relatedBeanInfo['related_bean_type'] = ucfirst($_REQUEST['related_bean_type']);
1565         }
1566
1567         if (isset($_REQUEST['search_field'])) {
1568                 $wheres['first_name'] = $_REQUEST['search_field'];
1569                 $wheres['last_name'] = $_REQUEST['search_field'];
1570                 $wheres['email_address'] = $_REQUEST['search_field'];
1571         }
1572
1573         if(isset($_REQUEST['person']) && !empty($_REQUEST['person'])) {
1574             $person = $_REQUEST['person'];
1575         }
1576         if(!empty($_REQUEST['start'])) {
1577             $start = intval($_REQUEST['start']);
1578         } else {
1579                 $start = 0;
1580         }
1581
1582         $qArray = $email->et->getRelatedEmail($person, $wheres, $relatedBeanInfo);
1583         $out = array();
1584         $count = 0;
1585         if (!empty($qArray['query'])) {
1586                 $countq = $qArray['countQuery'];
1587                 $time = microtime(true);
1588                 $r = $ie->db->query($countq);
1589                 $GLOBALS['log']->debug("***QUERY counted in " . (microtime(true) - $time) . " milisec\n");
1590                 if($row = $GLOBALS['db']->fetchByAssoc($r)){
1591                     $count = $row['c'];
1592                 }
1593                 $time = microtime(true);
1594
1595                 //Handle sort and order requests
1596                 $sort = !empty($_REQUEST['sort']) ? $ie->db->getValidDBName($_REQUEST['sort']) : "id";
1597                 $sort = ($sort == 'bean_id') ? 'id' : $sort;
1598                 $sort = ($sort == 'email') ? 'email_address' : $sort;
1599                 $sort = ($sort == 'name') ? 'last_name' : $sort;
1600                 $direction = !empty($_REQUEST['dir']) && in_array(strtolower($_REQUEST['dir']), array("asc", "desc")) ? $_REQUEST['dir'] : "asc";
1601                 $order = ( !empty($sort) && !empty($direction) ) ? " ORDER BY {$sort} {$direction}" : "";
1602
1603                 $r = $ie->db->limitQuery($qArray['query'] . " $order ", $start, 25, true);
1604                 $GLOBALS['log']->debug("***QUERY Got results in " . (microtime(true) - $time) . " milisec\n");
1605
1606
1607                 while($a = $ie->db->fetchByAssoc($r)) {
1608                     $person = array();
1609                     $person['bean_id'] = $a['id'];
1610                     $person['bean_module'] = $a['module'];
1611                     $person['name'] = $locale->getLocaleFormattedName($a['first_name'], $a['last_name'],'');
1612                     $person['email'] = $a['email_address'];
1613                     $out[] = $person;
1614                 }
1615         }
1616         $ret = $email->et->jsonOuput(array('out' => $out), 'Person', $count);
1617
1618         @ob_end_clean();
1619         ob_start();
1620         echo $ret;
1621         ob_end_flush();
1622     break;
1623
1624         ////    END ADDRESS BOOK
1625         ///////////////////////////////////////////////////////////////////////////
1626
1627
1628
1629         ///////////////////////////////////////////////////////////////////////////
1630         ////    MISC
1631
1632     default:
1633         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: default");
1634         echo "NOOP";
1635         break;
1636   } // switch
1637  } // if