/**
  * Process the request for displaying UI
  * @global String $currentModule
  * @param MailManager_Request $request
  * @return MailManager_Response
  */
 function process(MailManager_Request $request)
 {
     global $currentModule;
     $response = new Vtiger_Response(true);
     $viewer = $this->getViewer();
     if ($request->getOperationArg() == "_quicklinks") {
         $content = $viewer->fetch($this->getModuleTpl('MainuiQuickLinks.tpl'));
         $response->setResult(array('ui' => $content));
         return $response;
     } else {
         if ($this->hasMailboxModel()) {
             $connector = $this->getConnector();
             if ($connector->hasError()) {
                 $viewer->assign('ERROR', $connector->lastError());
             } else {
                 $folders = $connector->folders();
                 $connector->updateFolders();
                 $viewer->assign('FOLDERS', $folders);
             }
             $this->closeConnector();
         }
         $viewer->assign('MODULE', $currentModule);
         $content = $viewer->fetch($this->getModuleTpl('Mainui.tpl'));
         $response->setResult(array('mailbox' => $this->hasMailboxModel(), 'ui' => $content));
         return $response;
     }
 }
Example #2
0
 public function process(Vtiger_Request $request)
 {
     $request = MailManager_Request::getInstance($request);
     if (!$request->has('_operation')) {
         return $this->processRoot($request);
     }
     $operation = $request->getOperation();
     $controllerInfo = self::$controllers[$operation];
     // TODO Handle case when controller information is not available
     //$controllerFile = dirname(__FILE__) . '/' . $controllerInfo['file'];
     //checkFileAccessForInclusion($controllerFile);
     //include_once $controllerFile;
     $controller = new $controllerInfo['class']();
     // Making sure to close the open connection
     if ($controller) {
         $controller->closeConnector();
     }
     if ($controller->validateRequest($request)) {
         $response = $controller->process($request);
         if ($response) {
             $response->emit();
         }
     }
     unset($request);
     unset($response);
 }
 /**
  * Processes the request for search Operation
  * @global <type> $current_user
  * @param MailManager_Request $request
  * @return boolean
  */
 function process(MailManager_Request $request)
 {
     $response = new Vtiger_Response();
     $viewer = $this->getViewer();
     if ('popupui' == $request->getOperationArg()) {
         $viewer->display($this->getModuleTpl('Search.Popupui.tpl'));
         $response = false;
     } else {
         if ('email' == $request->getOperationArg()) {
             global $current_user;
             $searchTerm = $request->get('q');
             if (empty($searchTerm)) {
                 $searchTerm = '%@';
             } else {
                 $searchTerm = "%{$searchTerm}%";
             }
             $filteredResult = MailManager::lookupMailInVtiger($searchTerm, $current_user);
             $response->emitJSON($filteredResult);
         }
     }
     return $response;
 }
 /**
  * Process the request for Settings Operations
  * @param MailManager_Request $request
  * @return MailManager_Response
  */
 function process(MailManager_Request $request)
 {
     $response = new MailManager_Response();
     if ('edit' == $request->getOperationArg()) {
         $model = $this->getMailBoxModel();
         $serverName = $model->serverName();
         $viewer = $this->getViewer();
         $viewer->assign('SERVERNAME', $serverName);
         $response->setResult($viewer->fetch($this->getModuleTpl('Settings.tpl')));
     } else {
         if ('save' == $request->getOperationArg()) {
             $model = $this->getMailBoxModel();
             $model->setServer($request->get('_mbox_server'));
             $model->setUsername($request->get('_mbox_user'));
             $model->setPassword($request->get('_mbox_pwd'));
             $model->setProtocol($request->get('_mbox_protocol', 'imap2'));
             $model->setSSLType($request->get('_mbox_ssltype', 'tls'));
             $model->setCertValidate($request->get('_mbox_certvalidate', 'novalidate-cert'));
             $model->setRefreshTimeOut($request->get('_mbox_refresh_timeout'));
             $connector = $this->getConnector();
             if ($connector->isConnected()) {
                 $model->save();
                 $request->set('_operation', 'mainui');
                 return parent::process($request);
             } else {
                 if ($connector->hasError()) {
                     $response->isJSON(true);
                     $response->setError(101, $connector->lastError());
                 }
             }
         } else {
             if ('remove' == $request->getOperationArg()) {
                 $model = $this->getMailBoxModel();
                 $model->delete();
                 $response->isJSON(true);
                 $response->setResult(array('status' => true));
             }
         }
     }
     return $response;
 }
 /**
  * Process the request to perform relationship operations
  * @global Users Instance $current_user
  * @global PearDataBase Instance $adb
  * @global String $currentModule
  * @param MailManager_Request $request
  * @return boolean
  */
 function process(MailManager_Request $request)
 {
     global $current_user, $adb;
     $response = new MailManager_Response(true);
     $viewer = $this->getViewer();
     if ('find' == $request->getOperationArg()) {
         $this->skipConnection = true;
         // No need to connect to mailbox here, improves performance
         // Check if the message is already linked.
         //$linkedto = MailManager_RelationControllerAction::associatedLink($request->get('_msguid'));
         // If the message was not linked, lookup for matching records, using FROM address
         //if (empty($linkedto)) {
         $msguid = $request->get('_msguid');
         $results = array();
         $modules = array();
         $allowedModules = $this->getCurrentUserMailManagerAllowedModules();
         foreach (self::$MODULES as $MODULE) {
             if (!in_array($MODULE, $allowedModules)) {
                 continue;
             }
             $from = $request->get('_mfrom');
             if (empty($from)) {
                 continue;
             }
             $results[$MODULE] = $this->lookupModuleRecordsWithEmail($MODULE, $from, $msguid);
             $describe = $this->ws_describe($MODULE);
             $modules[$MODULE] = array('label' => $describe['label'], 'name' => textlength_check($describe['name']), 'id' => $describe['idPrefix']);
             // If look is found in a module, skip rest. - for performance
             //if (!empty($results[$MODULE])) break;
         }
         $viewer->assign('LOOKUPS', $results);
         $viewer->assign('MODULES', $modules);
         //} else {
         //	$viewer->assign('LINKEDTO', $linkedto);
         //}
         $viewer->assign('LinkToAvailableActions', $this->linkToAvailableActions());
         $viewer->assign('AllowedModules', $allowedModules);
         $viewer->assign('MSGNO', $request->get('_msgno'));
         $viewer->assign('FOLDER', $request->get('_folder'));
         $response->setResult(array('ui' => $viewer->fetch($this->getModuleTpl('Relationship.tpl'))));
     } else {
         if ('link' == $request->getOperationArg()) {
             $linkto = $request->get('_mlinkto');
             $foldername = $request->get('_folder');
             $connector = $this->getConnector($foldername);
             // This is to handle larger uploads
             $memory_limit = ConfigPrefs::get('MEMORY_LIMIT');
             ini_set('memory_limit', $memory_limit);
             $mail = $connector->openMail($request->get('_msgno'));
             $mail->attachments();
             // Initialize attachments
             $linkedto = MailManager_RelationControllerAction::associate($mail, $linkto);
             $viewer->assign('LinkToAvailableActions', $this->linkToAvailableActions());
             $viewer->assign('AllowedModules', $this->getCurrentUserMailManagerAllowedModules());
             $viewer->assign('LINKEDTO', $linkedto);
             $viewer->assign('MSGNO', $request->get('_msgno'));
             $viewer->assign('FOLDER', $foldername);
             $response->setResult(array('ui' => $viewer->fetch($this->getModuleTpl('Relationship.tpl'))));
         } else {
             if ('create_wizard' == $request->getOperationArg()) {
                 global $currentModule;
                 $moduleName = $request->get('_mlinktotype');
                 $parent = $request->get('_mlinkto');
                 $foldername = $request->get('_folder');
                 $connector = $this->getConnector($foldername);
                 $mail = $connector->openMail($request->get('_msgno'));
                 $qcreate_array = QuickCreate($moduleName);
                 $validationData = $qcreate_array['data'];
                 $data = split_validationdataArray($validationData);
                 $qcreate_array['form'] = $this->processFormData($qcreate_array['form'], $mail);
                 $viewer->assign("QUICKCREATE", $qcreate_array['form']);
                 if ($moduleName == 'Calendar') {
                     $viewer->assign("QCMODULE", getTranslatedString('Todo', 'Calendar'));
                 } elseif ($moduleName == "HelpDesk") {
                     $viewer->assign("QCMODULE", getTranslatedString('Ticket', 'HelpDesk'));
                 } else {
                     $viewer->assign("QCMODULE", getTranslatedString("SINGLE_" . $moduleName, $moduleName));
                 }
                 $viewer->assign("PARENT", $parent);
                 $viewer->assign("MODULE", $moduleName);
                 $viewer->assign('MSGNO', $request->get('_msgno'));
                 $viewer->assign('FOLDER', $foldername);
                 $viewer->assign("VALIDATION_DATA_FIELDNAME", $data['fieldname']);
                 $viewer->assign("VALIDATION_DATA_FIELDDATATYPE", $data['datatype']);
                 $viewer->assign("VALIDATION_DATA_FIELDLABEL", $data['fieldlabel']);
                 $viewer->display($this->getModuleTpl('Relationship.CreateWizard.tpl'));
                 $response = false;
             } else {
                 if ('create' == $request->getOperationArg()) {
                     $linkModule = $request->get('_mlinktotype');
                     $parent = $request->get('_mlinkto');
                     $focus = CRMEntity::getInstance($linkModule);
                     // This is added as ModComments module has a bug that will not initialize column_fields
                     // Basically $currentModule is set to MailManager, so the fields are not set properly.
                     if (empty($focus->column_fields)) {
                         $focus->column_fields = getColumnFields($linkModule);
                     }
                     setObjectValuesFromRequest($focus);
                     if ($request->get('assigntype') == 'U') {
                         $focus->column_fields['assigned_user_id'] = $request->get('assigned_user_id');
                     } elseif ($request->get('assigntype') == 'T') {
                         $focus->column_fields['assigned_user_id'] = $request->get('assigned_group_id');
                     }
                     $foldername = $request->get('_folder');
                     if (!empty($foldername)) {
                         // This is to handle larger uploads
                         $memory_limit = ConfigPrefs::get('MEMORY_LIMIT');
                         ini_set('memory_limit', $memory_limit);
                         $connector = $this->getConnector($foldername);
                         $mail = $connector->openMail($request->get('_msgno'));
                         $attachments = $mail->attachments();
                         // Initialize attachments
                     }
                     $linkedto = MailManager_RelationControllerAction::getSalesEntityInfo($parent);
                     switch ($linkModule) {
                         case 'Calendar':
                             if (empty($focus->column_fields['activitytype'])) {
                                 $focus->column_fields['activitytype'] = 'Task';
                             }
                             if (empty($focus->column_fields['due_date'])) {
                                 if (!empty($focus->column_fields['date_start'])) {
                                     $dateStart = getValidDBInsertDateValue($focus->column_fields['date_start']);
                                     $focus->column_fields['due_date'] = date("Y-m-d", strtotime(date("Y-m-d", strtotime($dateStart)) . " +1 day"));
                                 } else {
                                     $focus->column_fields['due_date'] = date('Y-m-d', strtotime("+1 day"));
                                 }
                             }
                             if (!empty($parent)) {
                                 if ($linkedto['module'] == 'Contacts') {
                                     $focus->column_fields['contact_id'] = $parent;
                                 } else {
                                     $focus->column_fields['parent_id'] = $parent;
                                 }
                             }
                             break;
                         case 'HelpDesk':
                             $from = $mail->from();
                             $focus->column_fields['parent_id'] = $this->setParentForHelpDesk($parent, $from);
                             break;
                         case 'ModComments':
                             $focus->column_fields['assigned_user_id'] = $current_user->id;
                             $focus->column_fields['creator'] = $current_user->id;
                             $focus->column_fields['related_to'] = $parent;
                             break;
                     }
                     try {
                         $focus->save($linkModule);
                         // This condition is added so that emails are not created for Todo without Parent,
                         // as there is no way to relate them
                         if (empty($parent) && $linkModule != 'Calendar') {
                             $linkedto = MailManager_RelationControllerAction::associate($mail, $focus->id);
                         }
                         // add attachments to the tickets as Documents
                         if (in_array($linkModule, array('HelpDesk', 'Potentials', 'Project', 'ProjectTask')) && !empty($attachments)) {
                             $relationController = new MailManager_RelationControllerAction();
                             $relationController->__SaveAttachements($mail, $linkModule, $focus);
                         }
                         $viewer->assign('MSGNO', $request->get('_msgno'));
                         $viewer->assign('LINKEDTO', $linkedto);
                         $viewer->assign('AllowedModules', $this->getCurrentUserMailManagerAllowedModules());
                         $viewer->assign('LinkToAvailableActions', $this->linkToAvailableActions());
                         $viewer->assign('FOLDER', $foldername);
                         $response->setResult(array('ui' => $viewer->fetch($this->getModuleTpl('Relationship.tpl'))));
                     } catch (Exception $e) {
                         $response->setResult(array('ui' => '', 'error' => $e));
                     }
                 } else {
                     if ('savedraft' == $request->getOperationArg()) {
                         $connector = $this->getConnector('__vt_drafts');
                         $draftResponse = $connector->saveDraft($request);
                         $response->setResult($draftResponse);
                     } else {
                         if ('saveattachment' == $request->getOperationArg()) {
                             $connector = $this->getConnector('__vt_drafts');
                             $uploadResponse = $connector->saveAttachment($request);
                             $response->setResult($uploadResponse);
                         } else {
                             if ('commentwidget' == $request->getOperationArg()) {
                                 $viewer->assign('LINKMODULE', $request->get('_mlinktotype'));
                                 $viewer->assign('PARENT', $request->get('_mlinkto'));
                                 $viewer->assign('MSGNO', $request->get('_msgno'));
                                 $viewer->assign('FOLDER', $request->get('_folder'));
                                 $viewer->display($this->getModuleTpl('MailManager.CommentWidget.tpl'));
                                 $response = false;
                             }
                         }
                     }
                 }
             }
         }
     }
     return $response;
 }
 /**
  * Function which processes request for Mail Operations
  * @global Integer $list_max_entries_per_page - Number of entries per page
  * @global PearDataBase Instance $adb
  * @global Users Instance $current_user
  * @global String $root_directory
  * @param MailManager_Request $request
  * @return MailManager_Response
  */
 function process(MailManager_Request $request)
 {
     global $list_max_entries_per_page, $adb, $current_user;
     $response = new Vtiger_Response();
     if ('open' == $request->getOperationArg()) {
         $foldername = $request->get('_folder');
         $connector = $this->getConnector($foldername);
         $folder = $connector->folderInstance($foldername);
         $connector->markMailRead($request->get('_msgno'));
         $mail = $connector->openMail($request->get('_msgno'));
         // Get updated count after opening the email
         $connector->updateFolder($folder, SA_MESSAGES | SA_UNSEEN);
         $viewer = $this->getViewer();
         $viewer->assign('FOLDER', $folder);
         $viewer->assign('MAIL', $mail);
         $viewer->assign('ATTACHMENTS', $mail->attachments(false));
         $body = $mail->body();
         $inlineAttachments = $mail->inlineAttachments();
         if (is_array($inlineAttachments)) {
             foreach ($inlineAttachments as $index => $att) {
                 $cid = $att['cid'];
                 $attch_name = imap_utf8($att['filename']);
                 $id = $mail->muid();
                 $src = "index.php?module=MailManager&action=MailManagerAjax&file=index&_operation=mail&_operationarg=attachment_dld&_muid={$id}&_atname={$attch_name}";
                 $body = preg_replace('/cid:' . $cid . '/', $src, $body);
                 $inline_cid[$attch_name] = $cid;
             }
         }
         $viewer->assign('INLINE_ATT', $inline_cid);
         // Every link should open in a new tab
         $body = str_replace('<a', '<a target="_blank"', $body);
         $viewer->assign('BODY', $body);
         $uicontent = $viewer->fetch($this->getModuleTpl('MailOpen.tpl'));
         //To remove control characters http://stackoverflow.com/questions/1497885/remove-control-characters-from-php-string
         $uicontent = preg_replace('/[\\x00-\\x09\\x0B\\x0C\\x0E-\\x1F\\x7F]/', '', $uicontent);
         $metainfo = array('from' => $mail->from(), 'subject' => $mail->subject(), 'msgno' => $mail->msgNo(), 'msguid' => $mail->uniqueid(), 'folder' => $foldername);
         $response->isJson();
         $response->setResult(array('folder' => $foldername, 'unread' => $folder->unreadCount(), 'ui' => $uicontent, 'meta' => $metainfo));
     } else {
         if ('mark' == $request->getOperationArg()) {
             $foldername = $request->get('_folder');
             $connector = $this->getConnector($foldername);
             $folder = $connector->folderInstance($foldername);
             $connector->updateFolder($folder, SA_UNSEEN);
             if ('unread' == $request->get('_markas')) {
                 $connector->markMailUnread($request->get('_msgno'));
             }
             $response->isJson();
             $response->setResult(array('folder' => $foldername, 'unread' => $folder->unreadCount() + 1, 'status' => true, 'msgno' => $request->get('_msgno')));
         } else {
             if ('delete' == $request->getOperationArg()) {
                 $msg_no = $request->get('_msgno');
                 $foldername = $request->get('_folder');
                 $connector = $this->getConnector($foldername);
                 $connector->deleteMail($msg_no);
                 $response->isJson();
                 $response->setResult(array('folder' => $foldername, 'status' => true));
             } else {
                 if ('move' == $request->getOperationArg()) {
                     $msg_no = $request->get('_msgno');
                     $foldername = $request->get('_folder');
                     $moveToFolder = $request->get('_moveFolder');
                     $connector = $this->getConnector($foldername);
                     $connector->moveMail($msg_no, $moveToFolder);
                     $response->isJson();
                     $response->setResult(array('folder' => $foldername, 'status' => true));
                 } else {
                     if ('send' == $request->getOperationArg()) {
                         require_once 'modules/MailManager/Config.php';
                         // This is to handle larger uploads
                         $memory_limit = MailManager_Config::get('MEMORY_LIMIT');
                         ini_set('memory_limit', $memory_limit);
                         $to_string = rtrim($request->get('to'), ',');
                         $connector = $this->getConnector('__vt_drafts');
                         if (!empty($to_string)) {
                             $toArray = explode(',', $to_string);
                             foreach ($toArray as $to) {
                                 $relatedtos = MailManager::lookupMailInVtiger($to, $current_user);
                                 $referenceArray = array('Contacts', 'Accounts', 'Leads');
                                 for ($j = 0; $j < count($referenceArray); $j++) {
                                     $val = $referenceArray[$j];
                                     if (!empty($relatedtos) && is_array($relatedtos)) {
                                         for ($i = 0; $i < count($relatedtos); $i++) {
                                             if ($i == count($relatedtos) - 1) {
                                                 $relateto = vtws_getIdComponents($relatedtos[$i]['record']);
                                                 $parentIds = $relateto[1] . "@1";
                                             } elseif ($relatedtos[$i]['module'] == $val) {
                                                 $relateto = vtws_getIdComponents($relatedtos[$i]['record']);
                                                 $parentIds = $relateto[1] . "@1";
                                                 break;
                                             }
                                         }
                                     }
                                     if (isset($parentIds)) {
                                         break;
                                     }
                                 }
                                 if ($parentIds == '') {
                                     if (count($relatedtos) > 0) {
                                         $relateto = vtws_getIdComponents($relatedtos[0]['record']);
                                         $parentIds = $relateto[1] . "@1";
                                         break;
                                     }
                                 }
                                 $cc_string = rtrim($request->get('cc'), ',');
                                 $bcc_string = rtrim($request->get('bcc'), ',');
                                 $subject = $request->get('subject');
                                 $body = $request->get('body');
                                 //Restrict this for users module
                                 if ($relateto[1] != NULL && $relateto[0] != '19') {
                                     $entityId = $relateto[1];
                                     $parent_module = getSalesEntityType($entityId);
                                     $description = getMergedDescription($body, $entityId, $parent_module);
                                 } else {
                                     if ($relateto[0] == '19') {
                                         $parentIds = $relateto[1] . '@-1';
                                     }
                                     $description = $body;
                                 }
                                 $fromEmail = $connector->getFromEmailAddress();
                                 $userFullName = getFullNameFromArray('Users', $current_user->column_fields);
                                 $userId = $current_user->id;
                                 $mailer = new Vtiger_Mailer();
                                 $mailer->IsHTML(true);
                                 $mailer->ConfigSenderInfo($fromEmail, $userFullName, $current_user->email1);
                                 $mailer->Subject = $subject;
                                 $mailer->Body = $description;
                                 $mailer->addSignature($userId);
                                 if ($mailer->Signature != '') {
                                     $mailer->Body .= $mailer->Signature;
                                 }
                                 $ccs = empty($cc_string) ? array() : explode(',', $cc_string);
                                 $bccs = empty($bcc_string) ? array() : explode(',', $bcc_string);
                                 $emailId = $request->get('emailid');
                                 $attachments = $connector->getAttachmentDetails($emailId);
                                 $mailer->AddAddress($to);
                                 foreach ($ccs as $cc) {
                                     $mailer->AddCC($cc);
                                 }
                                 foreach ($bccs as $bcc) {
                                     $mailer->AddBCC($bcc);
                                 }
                                 global $root_directory;
                                 if (is_array($attachments)) {
                                     foreach ($attachments as $attachment) {
                                         $fileNameWithPath = $root_directory . $attachment['path'] . $attachment['fileid'] . "_" . $attachment['attachment'];
                                         if (is_file($fileNameWithPath)) {
                                             $mailer->AddAttachment($fileNameWithPath, $attachment['attachment']);
                                         }
                                     }
                                 }
                                 $status = $mailer->Send(true);
                                 if ($status === true) {
                                     $db = PearDatabase::getInstance();
                                     $dieOnErrorOldValue = $db->dieOnError;
                                     //suppressing dieonerror since for users inserting in to seactivity rel throws error in save_module of emails
                                     $db->dieOnError = false;
                                     $email = CRMEntity::getInstance('Emails');
                                     $email->column_fields['assigned_user_id'] = $current_user->id;
                                     $email->column_fields['date_start'] = date('Y-m-d');
                                     $email->column_fields['time_start'] = date('H:i');
                                     $email->column_fields['parent_id'] = $parentIds;
                                     $email->column_fields['subject'] = $mailer->Subject;
                                     $email->column_fields['description'] = $mailer->Body;
                                     $email->column_fields['activitytype'] = 'Emails';
                                     $email->column_fields['from_email'] = $mailer->From;
                                     $email->column_fields['saved_toid'] = $to;
                                     $email->column_fields['ccmail'] = $cc_string;
                                     $email->column_fields['bccmail'] = $bcc_string;
                                     $email->column_fields['email_flag'] = 'SENT';
                                     if (empty($emailId)) {
                                         $email->save('Emails');
                                     } else {
                                         $email->id = $emailId;
                                         $email->mode = 'edit';
                                         $email->save('Emails');
                                     }
                                     // This is added since the Emails save_module is not handling this
                                     global $adb;
                                     $realid = explode("@", $parentIds);
                                     $mycrmid = $realid[0];
                                     $params = array($mycrmid, $email->id);
                                     if ($realid[1] == -1) {
                                         $adb->pquery('DELETE FROM vtiger_salesmanactivityrel WHERE smid=? AND activityid=?', $params);
                                         $adb->pquery('INSERT INTO vtiger_salesmanactivityrel VALUES (?,?)', $params);
                                     } else {
                                         $adb->pquery('DELETE FROM vtiger_seactivityrel WHERE crmid=? AND activityid=?', $params);
                                         $adb->pquery('INSERT INTO vtiger_seactivityrel VALUES (?,?)', $params);
                                     }
                                     $db->dieOnError = $dieOnErrorOldValue;
                                 }
                             }
                         }
                         if ($status === true) {
                             $response->isJson();
                             $response->setResult(array('sent' => true));
                         } else {
                             $response->isJson();
                             $response->setError(112, 'please verify outgoing server.');
                         }
                     } else {
                         if ('attachment_dld' == $request->getOperationArg()) {
                             $attachmentName = $request->get('_atname');
                             $attachmentName = str_replace(' ', '_', $attachmentName);
                             if (MailManager_Utils::allowedFileExtension($attachmentName)) {
                                 // This is to handle larger uploads
                                 $memory_limit = MailManager_Config::get('MEMORY_LIMIT');
                                 ini_set('memory_limit', $memory_limit);
                                 $mail = new MailManager_Message_Model(false, false);
                                 $mail->readFromDB($request->get('_muid'));
                                 $attachment = $mail->attachments(true, $attachmentName);
                                 if ($attachment[$attachmentName]) {
                                     // Send as downloadable
                                     header("Content-type: application/octet-stream");
                                     header("Pragma: public");
                                     header("Cache-Control: private");
                                     header("Content-Disposition: attachment; filename={$attachmentName}");
                                     echo $attachment[$attachmentName];
                                 } else {
                                     header("Content-Disposition: attachment; filename=INVALIDFILE");
                                     echo "";
                                 }
                             } else {
                                 header("Content-Disposition: attachment; filename=INVALIDFILE");
                                 echo "";
                             }
                             flush();
                             exit;
                         } elseif ('getdraftmail' == $request->getOperationArg()) {
                             $connector = $this->getConnector('__vt_drafts');
                             $draftMail = $connector->getDraftMail($request);
                             $response->isJson();
                             $response->setResult(array($draftMail));
                         } elseif ('save' == $request->getOperationArg()) {
                             $connector = $this->getConnector('__vt_drafts');
                             $draftId = $connector->saveDraft($request);
                             $response->isJson();
                             if (!empty($draftId)) {
                                 $response->setResult(array('success' => true, 'emailid' => $draftId));
                             } else {
                                 $response->setResult(array('success' => false, 'error' => "Draft was not saved"));
                             }
                         } elseif ('deleteAttachment' == $request->getOperationArg()) {
                             $connector = $this->getConnector('__vt_drafts');
                             $deleteResponse = $connector->deleteAttachment($request);
                             $response->isJson(true);
                             $response->setResult(array('success' => $deleteResponse));
                         } elseif ('forward' == $request->getOperationArg()) {
                             $messageId = $request->get('messageid');
                             $folderName = $request->get('folder');
                             $connector = $this->getConnector($folderName);
                             $mail = $connector->openMail($messageId);
                             $attachments = $mail->attachments(true);
                             $draftConnector = $this->getConnector('__vt_drafts');
                             $draftId = $draftConnector->saveDraft($request);
                             if (!empty($attachments)) {
                                 foreach ($attachments as $aName => $aValue) {
                                     $attachInfo = $mail->__SaveAttachmentFile($aName, $aValue);
                                     if (is_array($attachInfo) && !empty($attachInfo) && $attachInfo['size'] > 0) {
                                         if (!MailManager::checkModuleWriteAccessForCurrentUser('Documents')) {
                                             return;
                                         }
                                         $document = CRMEntity::getInstance('Documents');
                                         $document->column_fields['notes_title'] = $attachInfo['name'];
                                         $document->column_fields['filename'] = $attachInfo['name'];
                                         $document->column_fields['filestatus'] = 1;
                                         $document->column_fields['filelocationtype'] = 'I';
                                         $document->column_fields['folderid'] = 1;
                                         // Default Folder
                                         $document->column_fields['filesize'] = $attachInfo['size'];
                                         $document->column_fields['assigned_user_id'] = $current_user->id;
                                         $document->save('Documents');
                                         //save doc-attachment relation
                                         $draftConnector->saveAttachmentRel($document->id, $attachInfo['attachid']);
                                         //save email-doc relation
                                         $draftConnector->saveEmailDocumentRel($draftId, $document->id);
                                         //save email-attachment relation
                                         $draftConnector->saveAttachmentRel($draftId, $attachInfo['attachid']);
                                         $attachmentInfo[] = array('name' => $attachInfo['name'], 'size' => $attachInfo['size'], 'emailid' => $draftId, 'docid' => $document->id);
                                     }
                                     unset($aValue);
                                 }
                             }
                             $response->isJson();
                             $response->setResult(array('attachments' => $attachmentInfo, 'emailid' => $draftId));
                         }
                     }
                 }
             }
         }
     }
     return $response;
 }
 /**
  * Process the request for Folder opertions
  * @global <type> $list_max_entries_per_page
  * @param MailManager_Request $request
  * @return MailManager_Response
  */
 function process(MailManager_Request $request)
 {
     global $list_max_entries_per_page, $current_user;
     $response = new Vtiger_Response();
     if ('open' == $request->getOperationArg()) {
         $q = $request->get('q');
         $foldername = $request->get('_folder');
         $type = $request->get('type');
         $connector = $this->getConnector($foldername);
         $folder = $connector->folderInstance($foldername);
         if (empty($q)) {
             $connector->folderMails($folder, intval($request->get('_page', 0)), $list_max_entries_per_page);
         } else {
             if (empty($type)) {
                 $type = 'ALL';
             }
             if ($type == 'ON') {
                 $dateFormat = $current_user->date_format;
                 if ($dateFormat == 'mm-dd-yyyy') {
                     $dateArray = explode('-', $q);
                     $temp = $dateArray[0];
                     $dateArray[0] = $dateArray[1];
                     $dateArray[1] = $temp;
                     $q = implode('-', $dateArray);
                 }
                 $query = date('d M Y', strtotime($q));
                 $q = '' . $type . ' "' . vtlib_purify($query) . '"';
             } else {
                 $q = '' . $type . ' "' . vtlib_purify($q) . '"';
             }
             $connector->searchMails($q, $folder, intval($request->get('_page', 0)), $list_max_entries_per_page);
         }
         $folderList = $connector->getFolderList();
         $viewer = $this->getViewer();
         $viewer->assign('TYPE', $type);
         $viewer->assign('QUERY', $request->get('q'));
         $viewer->assign('FOLDER', $folder);
         $viewer->assign('FOLDERLIST', $folderList);
         $viewer->assign('SEARCHOPTIONS', self::getSearchOptions());
         $viewer->assign("JS_DATEFORMAT", parse_calendardate(getTranslatedString('NTC_DATE_FORMAT')));
         $response->setResult($viewer->fetch($this->getModuleTpl('FolderOpen.tpl')));
     } elseif ('drafts' == $request->getOperationArg()) {
         $q = $request->get('q');
         $type = $request->get('type');
         $page = intval($request->get('_page', 0));
         $connector = $this->getConnector('__vt_drafts');
         $folder = $connector->folderInstance();
         if (empty($q)) {
             $draftMails = $connector->getDrafts($page, $list_max_entries_per_page, $folder);
         } else {
             $draftMails = $connector->searchDraftMails($q, $type, $page, $list_max_entries_per_page, $folder);
         }
         $viewer = $this->getViewer();
         $viewer->assign('MAILS', $draftMails);
         $viewer->assign('FOLDER', $folder);
         $viewer->assign('SEARCHOPTIONS', MailManager_DraftController::getSearchOptions());
         $response->setResult($viewer->fetch($this->getModuleTpl('FolderDrafts.tpl')));
     }
     return $response;
 }
 /**
  * Process the request for Folder opertions
  * @global <type> $list_max_entries_per_page
  * @param MailManager_Request $request
  * @return MailManager_Response
  */
 function process(MailManager_Request $request)
 {
     global $list_max_entries_per_page;
     $response = new MailManager_Response();
     if ('open' == $request->getOperationArg()) {
         $q = $request->get('q');
         $foldername = $request->get('_folder');
         $type = $request->get('type');
         $connector = $this->getConnector($foldername);
         $folder = $connector->folderInstance($foldername);
         if (empty($q)) {
             $connector->folderMails($folder, intval($request->get('_page', 0)), $list_max_entries_per_page);
         } else {
             if (empty($type)) {
                 $type = 'ALL';
             }
             $q = '' . $type . ' "' . vtlib_purify($q) . '"';
             $connector->searchMails($q, $folder, intval($request->get('_page', 0)), $list_max_entries_per_page);
         }
         $folderList = $connector->getFolderList();
         $viewer = $this->getViewer();
         $viewer->assign('TYPE', $type);
         $viewer->assign('QUERY', $request->get('q'));
         $viewer->assign('FOLDER', $folder);
         $viewer->assign('FOLDERLIST', $folderList);
         $viewer->assign('SEARCHOPTIONS', self::getSearchOptions());
         $response->setResult($viewer->fetch($this->getModuleTpl('Folder.Open.tpl')));
     } elseif ('drafts' == $request->getOperationArg()) {
         $q = $request->get('q');
         $type = $request->get('type');
         $page = intval($request->get('_page', 0));
         $connector = $this->getConnector('__vt_drafts');
         $folder = $connector->folderInstance();
         if (empty($q)) {
             $draftMails = $connector->getDrafts($page, $list_max_entries_per_page, $folder);
         } else {
             $draftMails = $connector->searchDraftMails($q, $type, $page, $list_max_entries_per_page, $folder);
         }
         $viewer = $this->getViewer();
         $viewer->assign('MAILS', $draftMails);
         $viewer->assign('FOLDER', $folder);
         $viewer->assign('SEARCHOPTIONS', MailManager_DraftController::getSearchOptions());
         $response->setResult($viewer->fetch($this->getModuleTpl('Folder.Drafts.tpl')));
     }
     return $response;
 }
 /**
  * Function which processes request for Mail Operations
  * @global Integer $list_max_entries_per_page - Number of entries per page
  * @global PearDataBase Instance $adb
  * @global Users Instance $current_user
  * @global String $root_directory
  * @param MailManager_Request $request
  * @return MailManager_Response
  */
 function process(MailManager_Request $request)
 {
     global $list_max_entries_per_page, $adb, $current_user;
     $response = new MailManager_Response();
     if ('open' == $request->getOperationArg()) {
         $foldername = $request->get('_folder');
         $connector = $this->getConnector($foldername);
         $folder = $connector->folderInstance($foldername);
         $connector->markMailRead($request->get('_msgno'));
         $mail = $connector->openMail($request->get('_msgno'));
         // Get updated count after opening the email
         $connector->updateFolder($folder, SA_MESSAGES | SA_UNSEEN);
         $viewer = $this->getViewer();
         $viewer->assign('FOLDER', $folder);
         $viewer->assign('MAIL', $mail);
         $uicontent = $viewer->fetch($this->getModuleTpl('Mail.Open.tpl'));
         $metainfo = array('from' => $mail->from(), 'subject' => $mail->subject(), 'msgno' => $mail->msgNo(), 'msguid' => $mail->uniqueid(), 'folder' => $foldername);
         $response->isJson(true);
         $response->setResult(array('folder' => $foldername, 'unread' => $folder->unreadCount(), 'ui' => $uicontent, 'meta' => $metainfo));
     } else {
         if ('mark' == $request->getOperationArg()) {
             $foldername = $request->get('_folder');
             $connector = $this->getConnector($foldername);
             $folder = $connector->folderInstance($foldername);
             $connector->updateFolder($folder, SA_UNSEEN);
             if ('unread' == $request->get('_markas')) {
                 $connector->markMailUnread($request->get('_msgno'));
             }
             $response->isJson(true);
             $response->setResult(array('folder' => $foldername, 'unread' => $folder->unreadCount() + 1, 'status' => true, 'msgno' => $request->get('_msgno')));
         } else {
             if ('delete' == $request->getOperationArg()) {
                 $msg_no = $request->get('_msgno');
                 $foldername = $request->get('_folder');
                 $connector = $this->getConnector($foldername);
                 $connector->deleteMail($msg_no);
                 $response->isJson(true);
                 $response->setResult(array('folder' => $foldername, 'status' => true));
             } else {
                 if ('move' == $request->getOperationArg()) {
                     $msg_no = $request->get('_msgno');
                     $foldername = $request->get('_folder');
                     $moveToFolder = $request->get('_moveFolder');
                     $connector = $this->getConnector($foldername);
                     $connector->moveMail($msg_no, $moveToFolder);
                     $response->isJson(true);
                     $response->setResult(array('folder' => $foldername, 'status' => true));
                 } else {
                     if ('send' == $request->getOperationArg()) {
                         require_once 'modules/MailManager/config.inc.php';
                         // This is to handle larger uploads
                         $memory_limit = ConfigPrefs::get('MEMORY_LIMIT');
                         ini_set('memory_limit', $memory_limit);
                         $to_string = rtrim($request->get('to'), ',');
                         $connector = $this->getConnector('__vt_drafts');
                         if (!empty($to_string)) {
                             $toArray = explode(',', $to_string);
                             foreach ($toArray as $to) {
                                 $relatedtos = MailManager::lookupMailInVtiger($to, $current_user);
                                 $referenceArray = array('Contacts', 'Accounts', 'Leads');
                                 for ($j = 0; $j < count($referenceArray); $j++) {
                                     $val = $referenceArray[$j];
                                     if (!empty($relatedtos) && is_array($relatedtos)) {
                                         for ($i = 0; $i < count($relatedtos); $i++) {
                                             if ($i == count($relatedtos) - 1) {
                                                 $relateto = vtws_getIdComponents($relatedtos[$i]['record']);
                                                 $parentIds .= $relateto[1] . "@1";
                                             } elseif ($relatedtos[$i]['module'] == $val) {
                                                 $relateto = vtws_getIdComponents($relatedtos[$i]['record']);
                                                 $parentIds = $relateto[1] . "@1";
                                                 break;
                                             }
                                         }
                                     }
                                     if (isset($parentIds)) {
                                         break;
                                     }
                                 }
                                 if ($parentIds == '') {
                                     if (count($relatedtos) > 0) {
                                         $relateto = vtws_getIdComponents($relatedtos[0]['record']);
                                         $parentIds = $relateto[1] . "@1";
                                         break;
                                     }
                                 }
                                 $cc_string = rtrim($request->get('cc'), ',');
                                 $bcc_string = rtrim($request->get('bcc'), ',');
                                 $subject = $request->get('subject');
                                 $body = $request->get('body');
                                 $description = $body;
                                 if (!empty($relateto) and !empty($relateto[1])) {
                                     $entityId = $relateto[1];
                                     $parent_module = getSalesEntityType($entityId);
                                     if (!empty($parent_module)) {
                                         $description = getMergedDescription($body, $entityId, $parent_module);
                                         $subject = getMergedDescription($subject, $entityId, $parent_module);
                                     } else {
                                         $n = MailManager_RelationControllerAction::ws_modulename($relateto[0]);
                                         if ($n == 'Users') {
                                             $description = getMergedDescription($body, $entityId, 'Users');
                                             $subject = getMergedDescription($subject, $entityId, 'Users');
                                         }
                                     }
                                 }
                                 $pos = strpos($description, '$logo$');
                                 if ($pos !== false) {
                                     $description = str_replace('$logo$', '<img src="cid:logo" />', $description);
                                     $logo = 1;
                                 }
                                 $fromEmail = $connector->getFromEmailAddress();
                                 $userFullName = getFullNameFromArray('Users', $current_user->column_fields);
                                 $userId = $current_user->id;
                                 $mailer = new Vtiger_Mailer();
                                 $mailer->IsHTML(true);
                                 $mailer->ConfigSenderInfo($fromEmail, $userFullName, $current_user->email1);
                                 $mailer->Subject = $subject;
                                 $mailer->Body = $description;
                                 $mailer->addSignature($userId);
                                 if ($mailer->Signature != '') {
                                     $mailer->Body .= $mailer->Signature;
                                 }
                                 $ccs = empty($cc_string) ? array() : explode(',', $cc_string);
                                 $bccs = empty($bcc_string) ? array() : explode(',', $bcc_string);
                                 $emailId = $request->get('emailid');
                                 $attachments = $connector->getAttachmentDetails($emailId);
                                 if ($logo) {
                                     $logo_attach = array('name' => 'logo', 'path' => 'themes/images/', 'attachment' => 'logo_mail.jpg');
                                     $mailer->AddEmbeddedImage($logo_attach['path'] . $logo_attach['attachment'], $logo_attach['name'], $logo_attach['name'] . 'jpg', 'base64', 'image/jpg');
                                 }
                                 $mailer->AddAddress($to);
                                 foreach ($ccs as $cc) {
                                     $mailer->AddCC($cc);
                                 }
                                 foreach ($bccs as $bcc) {
                                     $mailer->AddBCC($bcc);
                                 }
                                 global $root_directory;
                                 if (is_array($attachments)) {
                                     foreach ($attachments as $attachment) {
                                         $fileNameWithPath = $root_directory . $attachment['path'] . $attachment['fileid'] . "_" . $attachment['attachment'];
                                         if (is_file($fileNameWithPath)) {
                                             $mailer->AddAttachment($fileNameWithPath, $attachment['attachment']);
                                         }
                                     }
                                 }
                                 $status = $mailer->Send(true);
                             }
                         }
                         if ($status === true) {
                             $email = CRMEntity::getInstance('Emails');
                             $email->column_fields['assigned_user_id'] = $current_user->id;
                             $email->column_fields['date_start'] = date('Y-m-d');
                             $email->column_fields['time_start'] = date('H:i');
                             $email->column_fields['parent_id'] = $parentIds;
                             $email->column_fields['subject'] = $mailer->Subject;
                             $email->column_fields['description'] = $mailer->Body;
                             $email->column_fields['activitytype'] = 'Emails';
                             $email->column_fields['from_email'] = $mailer->From;
                             $email->column_fields['saved_toid'] = $to_string;
                             $email->column_fields['ccmail'] = $cc_string;
                             $email->column_fields['bccmail'] = $bcc_string;
                             $email->column_fields['email_flag'] = 'SENT';
                             if (empty($emailId)) {
                                 $email->save('Emails');
                             } else {
                                 $email->id = $emailId;
                                 $email->mode = 'edit';
                                 $email->save('Emails');
                             }
                             $response->isJson(true);
                             $response->setResult(array('sent' => true));
                         } else {
                             $response->isJson(true);
                             $response->setError(112, 'please verify outgoing server.');
                         }
                     } else {
                         if ('attachment_dld' == $request->getOperationArg()) {
                             $attachmentName = $request->get('_atname');
                             $attachmentName = str_replace(' ', '_', $attachmentName);
                             if (MailManager_Utils::allowedFileExtension($attachmentName)) {
                                 // This is to handle larger uploads
                                 $memory_limit = ConfigPrefs::get('MEMORY_LIMIT');
                                 ini_set('memory_limit', $memory_limit);
                                 $mail = new MailManager_Model_Message(false, false);
                                 $mail->readFromDB($request->get('_muid'));
                                 $attachment = $mail->attachments(true, $attachmentName);
                                 if ($attachment[$attachmentName]) {
                                     // Send as downloadable
                                     header("Content-type: application/octet-stream");
                                     header("Pragma: public");
                                     header("Cache-Control: private");
                                     header("Content-Disposition: attachment; filename={$attachmentName}");
                                     echo $attachment[$attachmentName];
                                 } else {
                                     header("Content-Disposition: attachment; filename=INVALIDFILE");
                                     echo "";
                                 }
                             } else {
                                 header("Content-Disposition: attachment; filename=INVALIDFILE");
                                 echo "";
                             }
                             flush();
                             exit;
                         } elseif ('getdraftmail' == $request->getOperationArg()) {
                             $connector = $this->getConnector('__vt_drafts');
                             $draftMail = $connector->getDraftMail($request);
                             $response->isJson(true);
                             $response->setResult(array($draftMail));
                         } elseif ('save' == $request->getOperationArg()) {
                             $connector = $this->getConnector('__vt_drafts');
                             $draftId = $connector->saveDraft($request);
                             $response->isJson(true);
                             if (!empty($draftId)) {
                                 $response->setResult(array('success' => true, 'emailid' => $draftId));
                             } else {
                                 $response->setResult(array('success' => false, 'error' => "Draft was not saved"));
                             }
                         } elseif ('deleteAttachment' == $request->getOperationArg()) {
                             $connector = $this->getConnector('__vt_drafts');
                             $deleteResponse = $connector->deleteAttachment($request);
                             $response->isJson(true);
                             $response->setResult(array('success' => $deleteResponse));
                         } elseif ('forward' == $request->getOperationArg()) {
                             $messageId = $request->get('messageid');
                             $folderName = $request->get('folder');
                             $connector = $this->getConnector($folderName);
                             $mail = $connector->openMail($messageId);
                             $attachments = $mail->attachments(true);
                             $draftConnector = $this->getConnector('__vt_drafts');
                             $draftId = $draftConnector->saveDraft($request);
                             if (!empty($attachments)) {
                                 foreach ($attachments as $aName => $aValue) {
                                     $attachInfo = $mail->__SaveAttachmentFile($aName, $aValue);
                                     if (is_array($attachInfo) && !empty($attachInfo) && $attachInfo['size'] > 0) {
                                         if (!MailManager::checkModuleWriteAccessForCurrentUser('Documents')) {
                                             return;
                                         }
                                         $document = CRMEntity::getInstance('Documents');
                                         $document->column_fields['notes_title'] = $attachInfo['name'];
                                         $document->column_fields['filename'] = $attachInfo['name'];
                                         $document->column_fields['filestatus'] = 1;
                                         $document->column_fields['filelocationtype'] = 'I';
                                         $document->column_fields['folderid'] = 1;
                                         // Default Folder
                                         $document->column_fields['filesize'] = $attachInfo['size'];
                                         $document->column_fields['assigned_user_id'] = $current_user->id;
                                         $document->save('Documents');
                                         //save doc-attachment relation
                                         $draftConnector->saveAttachmentRel($document->id, $attachInfo['attachid']);
                                         //save email-doc relation
                                         $draftConnector->saveEmailDocumentRel($draftId, $document->id);
                                         //save email-attachment relation
                                         $draftConnector->saveAttachmentRel($draftId, $attachInfo['attachid']);
                                         $attachmentInfo[] = array('name' => $attachInfo['name'], 'size' => $attachInfo['size'], 'emailid' => $draftId, 'docid' => $document->id);
                                     }
                                     unset($aValue);
                                 }
                             }
                             $response->isJson(true);
                             $response->setResult(array('attachments' => $attachmentInfo, 'emailid' => $draftId));
                         }
                     }
                 }
             }
         }
     }
     return $response;
 }
 /**
  * Function which processes request for Mail Operations
  * @global Integer $list_max_entries_per_page - Number of entries per page
  * @global PearDataBase Instance $adb
  * @global Users Instance $current_user
  * @global String $root_directory 
  * @param MailManager_Request $request
  * @return MailManager_Response
  */
 function process(MailManager_Request $request)
 {
     global $list_max_entries_per_page, $adb, $current_user;
     $response = new MailManager_Response();
     if ('open' == $request->getOperationArg()) {
         $foldername = $request->get('_folder');
         $connector = $this->getConnector($foldername);
         $folder = $connector->folderInstance($foldername);
         $connector->markMailRead($request->get('_msgno'));
         $mail = $connector->openMail($request->get('_msgno'));
         // Get updated count after opening the email
         $connector->updateFolder($folder, SA_MESSAGES | SA_UNSEEN);
         $viewer = $this->getViewer();
         $viewer->assign('FOLDER', $folder);
         $viewer->assign('MAIL', $mail);
         $uicontent = $viewer->fetch($this->getModuleTpl('Mail.Open.tpl'));
         $metainfo = array('from' => $mail->from(), 'subject' => $mail->subject(), 'msgno' => $mail->msgNo(), 'msguid' => $mail->uniqueid(), 'folder' => $foldername);
         $response->isJson(true);
         $response->setResult(array('folder' => $foldername, 'unread' => $folder->unreadCount(), 'ui' => $uicontent, 'meta' => $metainfo));
     } else {
         if ('mark' == $request->getOperationArg()) {
             $foldername = $request->get('_folder');
             $connector = $this->getConnector($foldername);
             $folder = $connector->folderInstance($foldername);
             $connector->updateFolder($folder, SA_UNSEEN);
             if ('unread' == $request->get('_markas')) {
                 $connector->markMailUnread($request->get('_msgno'));
             }
             $response->isJson(true);
             $response->setResult(array('folder' => $foldername, 'unread' => $folder->unreadCount() + 1, 'status' => true, 'msgno' => $request->get('_msgno')));
         } else {
             if ('delete' == $request->getOperationArg()) {
                 $msg_no = $request->get('_msgno');
                 $foldername = $request->get('_folder');
                 $connector = $this->getConnector($foldername);
                 $connector->deleteMail($msg_no);
                 $response->isJson(true);
                 $response->setResult(array('folder' => $foldername, 'status' => true));
             } else {
                 if ('move' == $request->getOperationArg()) {
                     $msg_no = $request->get('_msgno');
                     $foldername = $request->get('_folder');
                     $moveToFolder = $request->get('_moveFolder');
                     $connector = $this->getConnector($foldername);
                     $connector->moveMail($msg_no, $moveToFolder);
                     $response->isJson(true);
                     $response->setResult(array('folder' => $foldername, 'status' => true));
                 } else {
                     if ('send' == $request->getOperationArg()) {
                         require_once 'modules/MailManager/config.inc.php';
                         // This is to handle larger uploads
                         $memory_limit = ConfigPrefs::get('MEMORY_LIMIT');
                         ini_set('memory_limit', $memory_limit);
                         $to_string = rtrim($request->get('to'), ',');
                         $connector = $this->getConnector('__vt_drafts');
                         if (!empty($to_string)) {
                             $toArray = explode(',', $to_string);
                             foreach ($toArray as $to) {
                                 $relatedtos = MailManager::lookupMailInVtiger($to, $current_user);
                                 if (!empty($relatedtos) && is_array($relatedtos)) {
                                     for ($i = 0; $i < count($relatedtos); $i++) {
                                         if ($i == count($relatedtos) - 1) {
                                             $relateto = vtws_getIdComponents($relatedtos[$i]['record']);
                                             $parentIds .= $relateto[1] . "@1";
                                         } else {
                                             $relateto = vtws_getIdComponents($relatedtos[$i]['record']);
                                             $parentIds .= $relateto[1] . "@1|";
                                         }
                                     }
                                 }
                             }
                         }
                         $cc_string = rtrim($request->get('cc'), ',');
                         $bcc_string = rtrim($request->get('bcc'), ',');
                         $subject = $request->get('subject');
                         $body = $request->get('body');
                         $fromEmail = $connector->getFromEmailAddress();
                         $userFullName = $current_user->first_name . ' ' . $current_user->last_name;
                         $mailer = new Vtiger_Mailer();
                         $mailer->IsHTML(true);
                         $mailer->ConfigSenderInfo($fromEmail, $userFullName, $current_user->email1);
                         $mailer->Subject = $subject;
                         $mailer->Body = $body;
                         $tos = explode(',', $to_string);
                         $ccs = empty($cc_string) ? array() : explode(',', $cc_string);
                         $bccs = empty($bcc_string) ? array() : explode(',', $bcc_string);
                         $emailId = $request->get('emailid');
                         $attachments = $connector->getAttachmentDetails($emailId);
                         foreach ($tos as $to) {
                             $mailer->AddAddress($to);
                         }
                         foreach ($ccs as $cc) {
                             $mailer->AddCC($cc);
                         }
                         foreach ($bccs as $bcc) {
                             $mailer->AddBCC($bcc);
                         }
                         global $root_directory;
                         if (is_array($attachments)) {
                             foreach ($attachments as $attachment) {
                                 $fileNameWithPath = $root_directory . $attachment['path'] . $attachment['fileid'] . "_" . $attachment['attachment'];
                                 if (is_file($fileNameWithPath)) {
                                     $mailer->AddAttachment($fileNameWithPath, $attachment['attachment']);
                                 }
                             }
                         }
                         $status = $mailer->Send(true);
                         if ($status === true) {
                             $email = CRMEntity::getInstance('Emails');
                             $email->column_fields['assigned_user_id'] = $current_user->id;
                             $email->column_fields['date_start'] = date('Y-m-d');
                             $email->column_fields['time_start'] = date('H:i');
                             $email->column_fields['parent_id'] = $parentIds;
                             $email->column_fields['subject'] = $mailer->Subject;
                             $email->column_fields['description'] = $mailer->Body;
                             $email->column_fields['activitytype'] = 'Emails';
                             $email->column_fields['from_email'] = $mailer->From;
                             $email->column_fields['saved_toid'] = $to_string;
                             $email->column_fields['ccmail'] = $cc_string;
                             $email->column_fields['bccmail'] = $bcc_string;
                             $email->column_fields['email_flag'] = 'SENT';
                             if (empty($emailId)) {
                                 $email->save('Emails');
                             } else {
                                 $email->id = $emailId;
                                 $email->mode = 'edit';
                                 $email->save('Emails');
                             }
                             $response->isJson(true);
                             $response->setResult(array('sent' => true));
                         } else {
                             $response->isJson(true);
                             $response->setError(112, 'please verify outgoing server.');
                         }
                     } else {
                         if ('attachment_dld' == $request->getOperationArg()) {
                             $attachmentName = $request->get('_atname');
                             $attachmentName = str_replace(' ', '_', $attachmentName);
                             if (MailManager_Utils::allowedFileExtension($attachmentName)) {
                                 // This is to handle larger uploads
                                 $memory_limit = ConfigPrefs::get('MEMORY_LIMIT');
                                 ini_set('memory_limit', $memory_limit);
                                 $mail = new MailManager_Model_Message(false, false);
                                 $mail->readFromDB($request->get('_muid'));
                                 $attachment = $mail->attachments(true, $attachmentName);
                                 if ($attachment[$attachmentName]) {
                                     // Send as downloadable
                                     header("Content-type: application/octet-stream");
                                     header("Pragma: public");
                                     header("Cache-Control: private");
                                     // JFV - convert attachment file name encoding
                                     //                    header("Content-Disposition: attachment; filename=$attachmentName");
                                     // refer - http://linux.ohwada.jp/modules/smartsection/item.php?itemid=516
                                     $name = $attachmentName;
                                     // ブラウザを判定する
                                     $ua = $_SERVER['HTTP_USER_AGENT'];
                                     $browser = 'unknown';
                                     if (strstr($ua, 'MSIE') && !strstr($ua, 'Opera')) {
                                         $browser = 'msie';
                                     } elseif (strstr($ua, 'Opera')) {
                                         $browser = 'opera';
                                     } elseif (strstr($ua, 'Firefox')) {
                                         $browser = 'firefox';
                                     } elseif (strstr($ua, "Chrome")) {
                                         $browser = 'chrome';
                                     } elseif (strstr($ua, "Safari")) {
                                         $browser = 'safari';
                                     }
                                     // 英数字だけかを判定する
                                     $ascii = mb_convert_encoding($name, "US-ASCII", "UTF-8");
                                     if ($ascii == $name) {
                                         $browser = 'ascii';
                                     }
                                     // ブラウザに応じた処理
                                     switch ($browser) {
                                         // urlencode する
                                         case 'ascii':
                                             $name = str_replace(' ', '_', $name);
                                             $name = rawurlencode($name);
                                             break;
                                             // SJIS に変換する
                                         // SJIS に変換する
                                         case 'msie':
                                             $name = mb_convert_encoding($name, "SJIS", "UTF-8");
                                             break;
                                             // RFC2231形式を使用する
                                         // RFC2231形式を使用する
                                         case 'firefox':
                                         case 'chrome':
                                         case 'opera':
                                             $name = "utf-8'ja'" . rawurlencode($name);
                                             $is_rfc2231 = true;
                                             break;
                                             // UTF-8 のまま
                                         // UTF-8 のまま
                                         case 'safari':
                                             break;
                                             // 諦めて代替えを使う
                                         // 諦めて代替えを使う
                                         default:
                                             //                    		$name = $name_alt;
                                             $name = str_replace(' ', '_', $name);
                                             $name = rawurlencode($name);
                                             break;
                                     }
                                     if ($is_rfc2231) {
                                         $dis = 'Content-Disposition: attachment; filename*=';
                                     } else {
                                         $dis = 'Content-Disposition: attachment; filename=';
                                     }
                                     header($dis . $name);
                                     // JFV END
                                     echo $attachment[$attachmentName];
                                 } else {
                                     header("Content-Disposition: attachment; filename=INVALIDFILE");
                                     echo "";
                                 }
                             } else {
                                 header("Content-Disposition: attachment; filename=INVALIDFILE");
                                 echo "";
                             }
                             flush();
                             exit;
                         } elseif ('getdraftmail' == $request->getOperationArg()) {
                             $connector = $this->getConnector('__vt_drafts');
                             $draftMail = $connector->getDraftMail($request);
                             $response->isJson(true);
                             $response->setResult(array($draftMail));
                         } elseif ('save' == $request->getOperationArg()) {
                             $connector = $this->getConnector('__vt_drafts');
                             $draftId = $connector->saveDraft($request);
                             $response->isJson(true);
                             if (!empty($draftId)) {
                                 $response->setResult(array('success' => true, 'emailid' => $draftId));
                             } else {
                                 $response->setResult(array('success' => false, 'error' => "Draft was not saved"));
                             }
                         } elseif ('deleteAttachment' == $request->getOperationArg()) {
                             $connector = $this->getConnector('__vt_drafts');
                             $deleteResponse = $connector->deleteAttachment($request);
                             $response->isJson(true);
                             $response->setResult(array('success' => $deleteResponse));
                         } elseif ('forward' == $request->getOperationArg()) {
                             $messageId = $request->get('messageid');
                             $folderName = $request->get('folder');
                             $connector = $this->getConnector($folderName);
                             $mail = $connector->openMail($messageId);
                             $attachments = $mail->attachments(true);
                             $draftConnector = $this->getConnector('__vt_drafts');
                             $draftId = $draftConnector->saveDraft($request);
                             if (!empty($attachments)) {
                                 foreach ($attachments as $aName => $aValue) {
                                     $attachInfo = $mail->__SaveAttachmentFile($aName, $aValue);
                                     if (is_array($attachInfo) && !empty($attachInfo) && $attachInfo['size'] > 0) {
                                         if (!MailManager::checkModuleWriteAccessForCurrentUser('Documents')) {
                                             return;
                                         }
                                         $document = CRMEntity::getInstance('Documents');
                                         $document->column_fields['notes_title'] = $attachInfo['name'];
                                         $document->column_fields['filename'] = $attachInfo['name'];
                                         $document->column_fields['filestatus'] = 1;
                                         $document->column_fields['filelocationtype'] = 'I';
                                         $document->column_fields['folderid'] = 1;
                                         // Default Folder
                                         $document->column_fields['filesize'] = $attachInfo['size'];
                                         $document->column_fields['assigned_user_id'] = $current_user->id;
                                         $document->save('Documents');
                                         //save doc-attachment relation
                                         $draftConnector->saveAttachmentRel($document->id, $attachInfo['attachid']);
                                         //save email-doc relation
                                         $draftConnector->saveEmailDocumentRel($draftId, $document->id);
                                         //save email-attachment relation
                                         $draftConnector->saveAttachmentRel($draftId, $attachInfo['attachid']);
                                         $attachmentInfo[] = array('name' => $attachInfo['name'], 'size' => $attachInfo['size'], 'emailid' => $draftId, 'docid' => $document->id);
                                     }
                                     unset($aValue);
                                 }
                             }
                             $response->isJson(true);
                             $response->setResult(array('attachments' => $attachmentInfo, 'emailid' => $draftId));
                         }
                     }
                 }
             }
         }
     }
     return $response;
 }