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