]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/Emails/EmailUIAjax.php
Release 6.5.16
[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-2013 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
897             if (!empty($_REQUEST['getUnread'])) {
898                 $out = $email->et->jsonOuput($metalist, 'Email', $count, false);
899             } else {
900                 $unread = $email->et->folder->getCountUnread($_REQUEST['ieId']);
901                 $out = $email->et->jsonOuput($metalist, 'Email', $count, false, $unread);
902             }
903
904             @ob_end_clean();
905             ob_start();
906             echo $out;
907             ob_end_flush();
908         } else {
909             echo "error: no ieID";
910         }
911         break;
912         ////    END LIST VIEW
913         ///////////////////////////////////////////////////////////////////////////
914
915
916
917         ///////////////////////////////////////////////////////////////////////////
918         ////    FOLDER ACTIONS
919     case "emptyTrash":
920         $email->et->emptyTrash($ie);
921         break;
922
923     case "clearInboundAccountCache":
924         $email->et->clearInboundAccountCache($_REQUEST['ieId']);
925         break;
926
927     case "updateSubscriptions":
928         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: updateSubscriptions");
929         if(isset($_REQUEST['subscriptions']) && !empty($_REQUEST['subscriptions']))
930         {
931             $subs = explode("::", $_REQUEST['subscriptions']);
932             $childrenSubs = array();
933             //Find all children of the group folder subscribed to and add
934             //them to the list of folders to show.
935             foreach ($subs as $singleSub)
936                 $email->et->folder->findAllChildren($singleSub, $childrenSubs);
937
938             $subs = array_merge($subs, $childrenSubs);
939             $email->et->folder->setSubscriptions($subs);
940         }
941         elseif(empty($_REQUEST['subscriptions'])) {
942             $email->et->folder->clearSubscriptions();
943         }
944         break;
945
946     case "refreshSugarFolders":
947         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: refreshSugarFolders");
948         $rootNode = new ExtNode('','');
949         $folderOpenState = $current_user->getPreference('folderOpenState', 'Emails');
950         $folderOpenState = (empty($folderOpenState)) ? "" : $folderOpenState;
951         $ret = $email->et->folder->getUserFolders($rootNode, unserialize($folderOpenState), $current_user, true);
952         $out = $json->encode($ret);
953         echo $out;
954         break;
955
956
957
958     case "getFoldersForSettings":
959         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: getFoldersForSettings");
960         $ret = $email->et->folder->getFoldersForSettings($current_user);
961         $out = $json->encode($ret);
962         echo $out;
963         break;
964
965     case "moveEmails":
966         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: moveEmails");
967         $ie->moveEmails($_REQUEST['sourceIeId'], $_REQUEST['sourceFolder'], $_REQUEST['destinationIeId'], $_REQUEST['destinationFolder'], $_REQUEST['emailUids']);
968         break;
969
970     case "saveNewFolder":
971         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: saveNewFolder");
972         if(isset($_REQUEST['folderType']) && !empty($_REQUEST['folderType'])) {
973             switch($_REQUEST['folderType']) {
974                 case "sugar":
975                     $ret = $email->et->saveNewFolder($_REQUEST['nodeLabel'], $_REQUEST['parentId']);
976                     $out = $json->encode($ret);
977                     echo $out;
978                     break;
979
980                 case "imap":
981                     $ie->retrieve($_REQUEST['ieId']);
982                     $ie->connectMailserver();
983                     $ie->saveNewFolder($_REQUEST['newFolderName'], $_REQUEST['mbox']);
984                     break;
985             }
986         } else {
987             echo "NOOP: no folderType defined";
988         }
989         break;
990
991     case "setFolderViewSelection": // flows into next case statement
992         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: setFolderViewSelection");
993         $viewFolders = $_REQUEST['ieIdShow'];
994         $current_user->setPreference('showFolders', base64_encode(serialize($viewFolders)), '', 'Emails');
995         $tree = $email->et->getMailboxNodes(false);
996         $return = $tree->generateNodesRaw();
997         $out = $json->encode($return);
998         echo $out;
999         break;
1000
1001     case "deleteFolder":
1002         $v = $app_strings['LBL_NONE'];
1003         $return = array();
1004         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: deleteFolder");
1005         if(isset($_REQUEST['folderType']) && !empty($_REQUEST['folderType'])) {
1006             switch($_REQUEST['folderType']) {
1007                 case "sugar":
1008                     $status = $email->et->folder->deleteChildrenCascade($_REQUEST['folder_id']);
1009                     if ($status == true) {
1010                         $return['status'] = true;
1011                         $return['folder_id'] = $_REQUEST['folder_id'];
1012                     } else {
1013                         $return['status'] = false;
1014                         $return['errorMessage'] = $app_strings['LBL_EMAIL_ERROR_DELETE_GROUP_FOLDER'];
1015                     }
1016                     break;
1017
1018                 case "imap":
1019                     $ie->retrieve($_REQUEST['ieId']);
1020                     $ie->connectMailserver();
1021                     $returnArray = $ie->deleteFolder($_REQUEST['mbox']);
1022                     $status = $returnArray['status'];
1023                     $errorMessage = $returnArray['errorMessage'];
1024                     if ($status == true) {
1025                         $return['status'] = true;
1026                         $return['mbox'] = $_REQUEST['mbox'];
1027                         $return['ieId'] = $_REQUEST['ieId'];
1028                     } else {
1029                         $return['status'] = false;
1030                         $return['errorMessage'] = $errorMessage;
1031                     }
1032                     break;
1033             }
1034         } else {
1035                 $return['status'] = false;
1036                 $return['errorMessage'] =  "NOOP: no folderType defined";
1037         }
1038         $out = $json->encode($return);
1039         echo $out;
1040         break;
1041     case "renameFolder":
1042         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: renameFolder");
1043
1044         if(isset($_REQUEST['ieId']) && isset($_REQUEST['oldFolderName']) && !empty($_REQUEST['oldFolderName'])
1045         && isset($_REQUEST['newFolderName']) && !empty($_REQUEST['newFolderName'])) {
1046             $ie->retrieve($_REQUEST['ieId']);
1047             $ie->renameFolder($_REQUEST['oldFolderName'], $_REQUEST['newFolderName']);
1048         } elseif(isset($_REQUEST['folderId']) && !empty($_REQUEST['folderId']) && isset($_REQUEST['newFolderName']) && !empty($_REQUEST['newFolderName'])) {
1049             if(is_guid($_REQUEST['folderId'])) {
1050                 $email->et->folder->retrieve($_REQUEST['folderId']);
1051                 $email->et->folder->name = $_REQUEST['newFolderName'];
1052                 $email->et->folder->save();
1053             } else {
1054                 echo "NOOP - not a Sugar Folder";
1055             }
1056         }
1057     case "moveFolder":
1058         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: moveFolder");
1059         if(isset($_REQUEST['folderId']) && !empty($_REQUEST['folderId']) && isset($_REQUEST['newParentId']) && !empty($_REQUEST['newParentId']) && $_REQUEST['newParentId'] != $_REQUEST['folderId']) {
1060             if(is_guid($_REQUEST['folderId']) && is_guid($_REQUEST['newParentId'])) {
1061                 $email->et->folder->retrieve($_REQUEST['folderId']);
1062                 $email->et->folder->updateFolder(array(
1063                     "record"        => $_REQUEST['folderId'],
1064                     "name"          => $email->et->folder->name,
1065                     "parent_folder" => $_REQUEST['newParentId'],
1066                     "team_id"       => $email->et->folder->team_id,
1067                     "team_set_id"       => $email->et->folder->team_set_id,
1068                 ));
1069             } else {
1070                 echo "NOOP - not a Sugar Folder";
1071             }
1072         }
1073         break;
1074     case "getGroupFolder":
1075             $email->et->folder->retrieve($_REQUEST['folderId']);
1076             $_REQUEST['record'] = $_REQUEST['folderId'];
1077             $ret = array();
1078             $ret['folderId'] = $email->et->folder->id;
1079             $ret['folderName'] = $email->et->folder->name;
1080             $ret['parentFolderId'] = $email->et->folder->parent_folder;
1081             $out = $json->encode($ret);
1082             echo $out;
1083         break;
1084
1085
1086     case "rebuildFolders":
1087         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: rebuildFolders");
1088         $tree = $email->et->getMailboxNodes(false);
1089         $return = $tree->generateNodesRaw();
1090         $out = $json->encode($return);
1091         echo $out;
1092         break;
1093
1094     case "setFolderOpenState":
1095         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: setFolderOpenState");
1096         $email->et->saveFolderOpenState($_REQUEST['focusFolder'], $_REQUEST['focusFolderOpen']);
1097         break;
1098
1099     case "saveListViewSortOrder":
1100         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: saveListViewSortOrder");
1101         $email->et->saveListViewSortOrder($_REQUEST['ieId'], $_REQUEST['focusFolder'], $_REQUEST['sortBy'], $_REQUEST['reverse']);
1102         break;
1103         ////    END FOLDER ACTIONS
1104         ///////////////////////////////////////////////////////////////////////////
1105
1106         ///////////////////////////////////////////////////////////////////////////
1107         ////    INBOUND EMAIL ACCOUNTS
1108
1109     case "retrieveAllOutbound":
1110         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: retrieveAllOutbound");
1111         global $current_user;
1112         $oe = new OutboundEmail();
1113                 $outbounds = $oe->getUserMailers($current_user);
1114                 $results = array('outbound_account_list' => $outbounds, 'count' => count($outbounds));
1115                 $out = $json->encode($results, false);
1116                 echo $out;
1117
1118         break;
1119
1120     case "editOutbound":
1121         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: editOutbound");
1122         if(isset($_REQUEST['outbound_email']) && !empty($_REQUEST['outbound_email'])) {
1123             $oe = new OutboundEmail();
1124             $oe->retrieve($_REQUEST['outbound_email']);
1125
1126             $ret = array();
1127
1128             foreach($oe->field_defs as $def) {
1129                 $ret[$def] = $oe->$def;
1130             }
1131             $ret['mail_smtppass']=''; // don't send back the password
1132             $ret['has_password'] =  isset($oe->mail_smtppass);
1133
1134             $out = $json->encode($ret, true);
1135             echo $out;
1136
1137         } else {
1138             echo "NOOP";
1139         }
1140         break;
1141
1142     case "deleteOutbound":
1143         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: deleteOutbound");
1144         if(isset($_REQUEST['outbound_email']) && !empty($_REQUEST['outbound_email']))
1145         {
1146             $oe = new OutboundEmail();
1147             global $current_user;
1148             $oe->retrieve($_REQUEST['outbound_email']);
1149             $affectedInboundAccounts = $oe->getAssociatedInboundAccounts($current_user);
1150
1151             //Check if the user has confirmed he wants to delete the email account even if associated to an inbound accnt.
1152             $confirmedDelete = ( isset($_REQUEST['confirm']) && $_REQUEST['confirm'] ) ? TRUE : FALSE;
1153
1154             if( count($affectedInboundAccounts) > 0 && !$confirmedDelete)
1155             {
1156                 $results = array('is_error' => true, 'error_message' => $app_strings['LBL_EMAIL_REMOVE_SMTP_WARNING'] , 'outbound_email' => $_REQUEST['outbound_email']);
1157             }
1158             else
1159             {
1160                 $oe->delete();
1161                 $results = array('is_error' => false, 'error_message' => '');
1162             }
1163
1164             $out = $json->encode($results);
1165             @ob_end_clean();
1166             ob_start();
1167             echo $out;
1168             ob_end_flush();
1169             die();
1170         }
1171         else
1172         {
1173             echo "NOOP";
1174         }
1175         break;
1176
1177     case "saveOutbound":
1178         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: saveOutbound");
1179
1180         $oe = new OutboundEmail();
1181         $oe->id = $_REQUEST['mail_id'];
1182         $oe->retrieve($oe->id);
1183         $oe->name = $_REQUEST['mail_name'];
1184         $type = empty($_REQUEST['type']) ? 'user' : $_REQUEST['type'];
1185         $oe->type = $type;
1186         $oe->user_id = $current_user->id;
1187         $oe->mail_sendtype = "SMTP";
1188         $oe->mail_smtptype = $_REQUEST['mail_smtptype'];
1189         $oe->mail_smtpserver = $_REQUEST['mail_smtpserver'];
1190         $oe->mail_smtpport = $_REQUEST['mail_smtpport'];
1191         $oe->mail_smtpssl = $_REQUEST['mail_smtpssl'];
1192         $oe->mail_smtpauth_req = isset($_REQUEST['mail_smtpauth_req']) ? 1 : 0;
1193         $oe->mail_smtpuser = $_REQUEST['mail_smtpuser'];
1194         if(!empty($_REQUEST['mail_smtppass'])) {
1195             $oe->mail_smtppass = $_REQUEST['mail_smtppass'];
1196         }
1197         $oe = $oe->save();
1198                 echo $oe->id;
1199         break;
1200
1201     case "saveDefaultOutbound":
1202                 global $current_user;
1203         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: saveDefaultOutbound");
1204         $outbound_id = empty($_REQUEST['id']) ? "" : $_REQUEST['id'];
1205         $ie = new InboundEmail();
1206                 $ie->setUsersDefaultOutboundServerId($current_user, $outbound_id);
1207         break;
1208     case "testOutbound":
1209         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: testOutbound");
1210
1211         $pass = '';
1212         if(!empty($_REQUEST['mail_smtppass'])) {
1213             $pass = $_REQUEST['mail_smtppass'];
1214         } elseif(isset($_REQUEST['mail_name'])) {
1215             $oe = new OutboundEmail();
1216             $oe = $oe->getMailerByName($current_user, $_REQUEST['mail_name']);
1217             if(!empty($oe)) {
1218                 $pass = $oe->mail_smtppass;
1219             }
1220         }
1221         $out = $email->sendEmailTest($_REQUEST['mail_smtpserver'], $_REQUEST['mail_smtpport'], $_REQUEST['mail_smtpssl'],
1222                                                                 (isset($_REQUEST['mail_smtpauth_req']) ? 1 : 0), $_REQUEST['mail_smtpuser'],
1223                                                                 $pass, $_REQUEST['outboundtest_from_address'], $_REQUEST['outboundtest_from_address']);
1224
1225         $out = $json->encode($out);
1226         echo $out;
1227         break;
1228
1229     case "rebuildShowAccount":
1230         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: rebuildShowAccount");
1231         $ret = $email->et->getShowAccountsOptions($ie);
1232         $results = array('account_list' => $ret, 'count' => count($ret));
1233         $out = $json->encode($results);
1234         echo $out;
1235         break;
1236
1237     case "rebuildShowAccountForSearch":
1238         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: rebuildShowAccount");
1239         $ret = $email->et->getShowAccountsOptionsForSearch($ie);
1240         $out = $json->encode($ret);
1241         echo $out;
1242         break;
1243
1244     case "deleteIeAccount":
1245         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: deleteIeAccount");
1246         if(isset($_REQUEST['group_id']) && $_REQUEST['group_id'] == $current_user->id) {
1247             $ret = array();
1248             $updateFolders = array();
1249                 $ret['id'] = $_REQUEST['ie_id'];
1250             $out = $json->encode($ret);
1251             $ie->hardDelete($_REQUEST['ie_id']);
1252             $out = $json->encode(array('id' => $_REQUEST['ie_id']));
1253             echo $out;
1254
1255             foreach ($showFolders as $id) {
1256                 if ($id != $_REQUEST['ie_id']) {
1257                     $updateFolders[] = $id;
1258                 }
1259             }
1260
1261             $showStore = base64_encode(serialize($updateFolders));
1262             $current_user->setPreference('showFolders', $showStore, 0, 'Emails');
1263         }
1264         break;
1265
1266     case "saveIeAccount":
1267         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: saveIeAccount");
1268         if(isset($_REQUEST['server_url']) && !empty($_REQUEST['server_url'])) {
1269             if(false === $ie->savePersonalEmailAccount($current_user->id, $current_user->user_name, false)) {
1270                 $ret = array('error' => 'error');
1271                 $out = $json->encode($ret);
1272                 echo $out;
1273             } else {
1274                 $ie->retrieve($_REQUEST['ie_id']);
1275                                 if (!isset($ie->created_by_link)) {
1276                                         $ie->created_by_link = null;
1277                                 }
1278                                 if (!isset($ie->modified_user_id_link)) {
1279                                         $ie->modified_user_id_link = null;
1280                                 }
1281                                 if (!is_array($showFolders)) {
1282                                         $showFolders = array();
1283                                 }
1284                 if(!in_array($ie->id, $showFolders)) {
1285                     $showFolders[] = $ie->id;
1286                     $showStore = base64_encode(serialize($showFolders));
1287                     $current_user->setPreference('showFolders', $showStore, 0, 'Emails');
1288                 }
1289
1290                 foreach($ie->field_defs as $k => $v) {
1291                         if (isset($v['type']) && ($v['type'] == 'link')) {
1292                                 continue;
1293                         }
1294                     if($k == 'stored_options') {
1295                         $ie->$k = unserialize(base64_decode($ie->$k));
1296                             if (isset($ie->stored_options['from_name'])) {
1297                                 $ie->stored_options['from_name'] = from_html($ie->stored_options['from_name']);
1298                             }
1299                     } elseif($k == 'service') {
1300                         $service = explode("::", $ie->$k);
1301                         $retService = array();
1302
1303                         foreach($service as $serviceK => $serviceV) {
1304                             if(!empty($serviceV)) {
1305                                 $retService[$serviceK] = $serviceV;
1306                             }
1307                         }
1308
1309                         $ie->$k = $retService;
1310                     }
1311
1312                     if (isset($ie->$k))
1313                     $ret[$k] = $ie->$k;
1314                 }
1315
1316                 $out = $json->encode($ret);
1317                 echo $out;
1318             }
1319
1320             //If the user is saving the username/password then we need to update the outbound account.
1321             $outboundMailUser = (isset($_REQUEST['mail_smtpuser'])) ? $_REQUEST['mail_smtpuser'] : "";
1322             $outboundMailPass = (isset($_REQUEST['mail_smtppass'])) ? $_REQUEST['mail_smtppass'] : "";
1323             $outboundMailId = (isset($_REQUEST['outbound_email'])) ? $_REQUEST['outbound_email'] : "";
1324
1325             if( !empty($outboundMailUser) && !empty($outboundMailPass) && !empty($outboundMailId) )
1326             {
1327                 $oe = new OutboundEmail();
1328                 $oe->retrieve($outboundMailId);
1329                 $oe->mail_smtpuser = $outboundMailUser;
1330                 $oe->mail_smtppass = $outboundMailPass;
1331                 $oe->save();
1332             }
1333
1334         } else {
1335             echo "NOOP";
1336         }
1337         break;
1338
1339     case "getIeAccount":
1340         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: getIeAccount");
1341         $ie->retrieve($_REQUEST['ieId']);
1342         if($ie->group_id == $current_user->id) {
1343             $ret = array();
1344
1345             foreach($ie->field_defs as $k => $v) {
1346                 if($k == 'stored_options') {
1347                     $ie->$k = unserialize(base64_decode($ie->$k));
1348                     if (isset($ie->stored_options['from_name'])) {
1349                         $ie->stored_options['from_name'] = from_html($ie->stored_options['from_name']);
1350                     }
1351                 } elseif($k == 'service') {
1352                     $service = explode("::", $ie->$k);
1353                     $retService = array();
1354                     foreach($service as $serviceK => $serviceV) {
1355                         if(!empty($serviceV)) {
1356                             $retService[$serviceK] = $serviceV;
1357                         }
1358                     }
1359
1360                     $ie->$k = $retService;
1361                 }
1362
1363                 $ret[$k] = $ie->$k;
1364             }
1365             unset($ret['email_password']); // no need to send the password out
1366
1367             $out = $json->encode($ret);
1368         } else {
1369             $out = "NOOP: ID mismatch";
1370         }
1371         echo $out;
1372         break;
1373         ////    END INBOUND EMAIL ACCOUNTS
1374         ///////////////////////////////////////////////////////////////////////////
1375
1376
1377
1378         ///////////////////////////////////////////////////////////////////////////
1379         ////    SEARCH
1380     case "search":
1381         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: search");
1382         if(isset($_REQUEST['subject']) && !empty($_REQUEST['subject']) && isset($_REQUEST['ieId']) && !empty($_REQUEST['ieId'])) {
1383             $metalist = $ie->search($_REQUEST['ieId'], $_REQUEST['subject']);
1384             if (!isset($_REQUEST['page'])) {
1385                 $_REQUEST['page'] = 1;
1386             }
1387             $_REQUEST['pageSize'] = count($metalist['out']);
1388             $out = $email->et->xmlOutput($metalist, 'Email', false);
1389             @ob_end_clean();
1390             ob_start();
1391             header("Content-type: text/xml");
1392             echo $out;
1393             ob_end_flush();
1394             die();
1395         } else {
1396             echo "NOOP: no search criteria found";
1397         }
1398         break;
1399
1400     case "searchAdvanced":
1401         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: searchAdvanced");
1402
1403         $metalist = $email->searchImportedEmails();
1404         $out = $email->et->jsonOuput($metalist, 'Email', $metalist['totalCount']);
1405
1406         @ob_end_clean();
1407         ob_start();
1408         echo $out;
1409         ob_end_flush();
1410         die();
1411
1412         break;
1413         ////    END SEARCH
1414         ///////////////////////////////////////////////////////////////////////////
1415
1416
1417
1418         ///////////////////////////////////////////////////////////////////////////
1419         ////    SETTINGS
1420     case "loadPreferences":
1421         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: loadPreferences");
1422         $prefs = $email->et->getUserPrefsJS();
1423         $out = $json->encode($prefs);
1424         echo $out;
1425         break;
1426
1427     case "saveSettingsGeneral":
1428         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: saveSettingsGeneral");
1429         $emailSettings = array();
1430         $emailSettings['emailCheckInterval'] = $_REQUEST['emailCheckInterval'];
1431         //$emailSettings['autoImport'] = isset($_REQUEST['autoImport']) ? '1' : '0';
1432         $emailSettings['alwaysSaveOutbound'] = '1';
1433         $emailSettings['sendPlainText'] = isset($_REQUEST['sendPlainText']) ? '1' : '0';
1434         $emailSettings['showNumInList'] = $_REQUEST['showNumInList'];
1435         $emailSettings['defaultOutboundCharset'] = $_REQUEST['default_charset'];
1436         $current_user->setPreference('emailSettings', $emailSettings, '', 'Emails');
1437
1438         // signature
1439         $current_user->setPreference('signature_default', $_REQUEST['signature_id']);
1440         $current_user->setPreference('signature_prepend', (isset($_REQUEST['signature_prepend'])) ? true : false);
1441
1442         $out = $json->encode($email->et->getUserPrefsJS());
1443         echo $out;
1444         break;
1445
1446     case "setPreference":
1447         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: setPreference");
1448         if(isset($_REQUEST['prefName']) && isset($_REQUEST['prefValue'])) {
1449             // handle potential JSON encoding
1450             if(isset($_REQUEST['decode'])) {
1451                 $_REQUEST['prefValue'] = $json->decode(from_html($_REQUEST['prefValue']));
1452             }
1453
1454             $current_user->setPreference($_REQUEST['prefName'], $_REQUEST['prefValue'], '', 'Emails');
1455         }
1456         break;
1457         ////    END SETTINGS
1458         ///////////////////////////////////////////////////////////////////////////
1459
1460
1461
1462
1463         ///////////////////////////////////////////////////////////////////////////
1464         ////    ADDRESS BOOK
1465
1466     case "editContact":
1467         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: editContact");
1468         if(isset($_REQUEST['id']) && !empty($_REQUEST['id'])) {
1469             $module = "Contacts";
1470             $ret = $email->et->getEditContact($_REQUEST['id'], $module);
1471         }
1472         $out = $json->encode($ret);
1473         echo $out;
1474         break;
1475
1476
1477         /* The four calls below all have the same return signature */
1478     case "removeContact":
1479         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: removeContacts");
1480         if(strpos($_REQUEST['ids'], "::") !== false) {
1481             $removeIds = explode("::", $_REQUEST['ids']);
1482         } else {
1483             $removeIds[] = $_REQUEST['ids'];
1484         }
1485         $email->et->removeContacts($removeIds);
1486
1487     case "saveContactEdit":
1488         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: saveContactEdit");
1489         if(isset($_REQUEST['args']) && !empty($_REQUEST['args'])) {
1490             $email->et->saveContactEdit($_REQUEST['args']);
1491         }
1492         // flow into getUserContacts();
1493     case "addContact":
1494         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: addContacts");
1495         $contacts = array();
1496
1497         if(isset($_REQUEST['bean_module']) && !empty($_REQUEST['bean_module']) && isset($_REQUEST['bean_id']) && !empty($_REQUEST['bean_id'])) {
1498             $contacts[$_REQUEST['bean_id']] = array(
1499             'id' => $_REQUEST['bean_id'],
1500             'module' => $_REQUEST['bean_module']
1501             );
1502             $email->et->setContacts($contacts);
1503         }
1504
1505     case "addContactsMultiple":
1506         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: addContacts");
1507         if (isset($_REQUEST['contactData'])) {
1508             $contacts = $json->decode(from_HTML($_REQUEST['contactData']));
1509             if ($contacts) {
1510                 //_ppd($contacts);
1511                 $email->et->setContacts($contacts);
1512             }
1513         }
1514
1515     case "getUserContacts":
1516         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: getUserContacts");
1517         $contacts = $email->et->getContacts();
1518
1519         if(is_array($contacts) && !empty($contacts)) {
1520             $ret = $email->et->getUserContacts($contacts, $current_user);
1521             $out = $json->encode($ret);
1522             echo $out;
1523         } else {
1524             echo "{}";
1525         }
1526    break;
1527
1528
1529         // address book search
1530     case "getUnionData":
1531         $wheres = array();
1532         $person;
1533         if(isset($_REQUEST['first_name']) && !empty($_REQUEST['first_name'])) {
1534             $wheres['first_name'] = $_REQUEST['first_name'];
1535         }
1536         if(isset($_REQUEST['last_name']) && !empty($_REQUEST['last_name'])) {
1537             $wheres['last_name'] = $_REQUEST['last_name'];
1538         }
1539         if(isset($_REQUEST['email_address']) && !empty($_REQUEST['email_address'])) {
1540             $wheres['email_address'] = $_REQUEST['email_address'];
1541         }
1542                 if(isset($_REQUEST['person']) && !empty($_REQUEST['person'])) {
1543             $person = $_REQUEST['person'];
1544         }
1545         $q = $email->et->_getPeopleUnionQuery($wheres , $person);
1546         $r = $ie->db->limitQuery($q, 0, 25, true);
1547
1548         $out = array();
1549         while($a = $ie->db->fetchByAssoc($r)) {
1550             $person = array();
1551             $person['id'] = $a['id'];
1552             $person['module'] = $a['module'];
1553             $person['full_name'] = $locale->getLocaleFormattedName($a['first_name'], $a['last_name'],'');
1554             $person['email_address'] = $a['email_address'];
1555             $out[] = $person;
1556         }
1557
1558         $ret = $json->encode($out, true);
1559         echo $ret;
1560         break;
1561
1562     case "getAddressSearchResults":
1563         $wheres = array();
1564         $person = 'contacts';
1565         $relatedBeanInfo = '';
1566                 if(isset($_REQUEST['related_bean_id']) && !empty($_REQUEST['related_bean_id'])) {
1567             $isRelatedSearch = true;
1568             $relatedBeanInfo['related_bean_id'] = $_REQUEST['related_bean_id'];
1569             $relatedBeanInfo['related_bean_type'] = ucfirst($_REQUEST['related_bean_type']);
1570         }
1571
1572         if (isset($_REQUEST['search_field'])) {
1573                 $wheres['first_name'] = $_REQUEST['search_field'];
1574                 $wheres['last_name'] = $_REQUEST['search_field'];
1575                 $wheres['email_address'] = $_REQUEST['search_field'];
1576         }
1577
1578         if(isset($_REQUEST['person']) && !empty($_REQUEST['person'])) {
1579             $person = $_REQUEST['person'];
1580         }
1581         if(!empty($_REQUEST['start'])) {
1582             $start = intval($_REQUEST['start']);
1583         } else {
1584                 $start = 0;
1585         }
1586
1587         $qArray = $email->et->getRelatedEmail($person, $wheres, $relatedBeanInfo);
1588         $out = array();
1589         $count = 0;
1590         if (!empty($qArray['query'])) {
1591                 $countq = $qArray['countQuery'];
1592                 $time = microtime(true);
1593                 $r = $ie->db->query($countq);
1594                 $GLOBALS['log']->debug("***QUERY counted in " . (microtime(true) - $time) . " milisec\n");
1595                 if($row = $GLOBALS['db']->fetchByAssoc($r)){
1596                     $count = $row['c'];
1597                 }
1598                 $time = microtime(true);
1599
1600                 //Handle sort and order requests
1601                 $sort = !empty($_REQUEST['sort']) ? $ie->db->getValidDBName($_REQUEST['sort']) : "id";
1602                 $sort = ($sort == 'bean_id') ? 'id' : $sort;
1603                 $sort = ($sort == 'email') ? 'email_address' : $sort;
1604                 $sort = ($sort == 'name') ? 'last_name' : $sort;
1605                 $direction = !empty($_REQUEST['dir']) && in_array(strtolower($_REQUEST['dir']), array("asc", "desc")) ? $_REQUEST['dir'] : "asc";
1606                 $order = ( !empty($sort) && !empty($direction) ) ? " ORDER BY {$sort} {$direction}" : "";
1607
1608                 $r = $ie->db->limitQuery($qArray['query'] . " $order ", $start, 25, true);
1609                 $GLOBALS['log']->debug("***QUERY Got results in " . (microtime(true) - $time) . " milisec\n");
1610
1611
1612                 while($a = $ie->db->fetchByAssoc($r)) {
1613                     $person = array();
1614                     $person['bean_id'] = $a['id'];
1615                     $person['bean_module'] = $a['module'];
1616                     $person['name'] = $locale->getLocaleFormattedName($a['first_name'], $a['last_name'],'');
1617                     $person['email'] = $a['email_address'];
1618                     $out[] = $person;
1619                 }
1620         }
1621         $ret = $email->et->jsonOuput(array('out' => $out), 'Person', $count);
1622
1623         @ob_end_clean();
1624         ob_start();
1625         echo $ret;
1626         ob_end_flush();
1627     break;
1628
1629         ////    END ADDRESS BOOK
1630         ///////////////////////////////////////////////////////////////////////////
1631
1632
1633
1634         ///////////////////////////////////////////////////////////////////////////
1635         ////    MISC
1636
1637     default:
1638         $GLOBALS['log']->debug("********** EMAIL 2.0 - Asynchronous - at: default");
1639         echo "NOOP";
1640         break;
1641   } // switch
1642  } // if