Inheritance: extends AppController
 function handler()
 {
     $messages = parent::handler();
     if ($messages["status"] == "success" && !empty($this->_FORMDATA)) {
         foreach ($this->_FORMDATA as $name => $value) {
             if ($name == "email") {
                 $user = UserClass::getByEmail($value);
                 if ($user !== false) {
                     $error_message[] = "Пользователь с таким email уже зарегистрирован";
                 }
             } else {
                 if ($name == "login") {
                     $user = UserClass::getByLogin($value);
                     if ($user !== false) {
                         $error_message[] = "Пользователь с таким логином уже зарегистрирован";
                     }
                 }
             }
         }
         if ($error_message) {
             $messages["status"] = "error";
             $messages["error"] = $error_message;
             unset($messages["success"]);
         } else {
             $arFields = array("login" => $this->_FORMDATA["login"], "email" => $this->_FORMDATA["email"], "full_name" => $this->_FORMDATA["full_name"], "pass" => $this->_FORMDATA["pass"], "active" => false, "code" => md5(date("Y-m-d H:i:s")));
             UserClass::createUser($arFields);
             $messages["success"] = "Спасибо за регистрацию. На Ваш email выслано письмо для активации аккаунта.";
             MailController::RegisterMail($this->_FORMDATA["email"], $arFields["code"]);
         }
     }
     return $messages;
 }
示例#2
0
 public function support()
 {
     $this->layout = 'frontend_menu';
     if ($this->request->is('post') && !empty($this->data)) {
         $Mail = new MailController();
         $Mail->constructClasses();
         $arr = array();
         $arr['TO_EMAIL'] = '*****@*****.**';
         $arr['TO_NAME'] = 'Admin';
         $arr['NAME'] = $this->data['first_name'] . ' ' . $this->data['last_name'];
         $arr['EMAIL'] = $this->data['email'];
         $arr['PHONE'] = $this->data['phone'];
         $arr['MESSAGE'] = $this->data['message'];
         $Mail->individualMail('support_mail', $arr);
         die;
     }
     $this->render('support');
 }
 function show_html_mail()
 {
     $user = $this->loginUserByToken();
     $mc = new MailController();
     $mc->show_html_mail();
 }
 function list_objects()
 {
     //alert("debugging. remove this line");ajx_current('empty'); return array() ; //TODO remove this line
     /* get query parameters */
     $filesPerPage = config_option('files_per_page');
     $start = array_var($_GET, 'start') ? (int) array_var($_GET, 'start') : 0;
     $limit = array_var($_GET, 'limit') ? array_var($_GET, 'limit') : $filesPerPage;
     $order = array_var($_GET, 'sort');
     $ignore_context = (bool) array_var($_GET, 'ignore_context');
     if ($order == "dateUpdated") {
         $order = "updated_on";
     } elseif ($order == "dateArchived") {
         $order = "archived_on";
     } elseif ($order == "dateDeleted") {
         $order = "trashed_on";
     }
     $orderdir = array_var($_GET, 'dir');
     $page = (int) ($start / $limit) + 1;
     $hide_private = !logged_user()->isMemberOfOwnerCompany();
     $typeCSV = array_var($_GET, 'type');
     $types = null;
     if ($typeCSV) {
         $types = explode(",", $typeCSV);
     }
     $name_filter = mysql_escape_string(array_var($_GET, 'name'));
     $linked_obj_filter = array_var($_GET, 'linkedobject');
     $object_ids_filter = '';
     if (!is_null($linked_obj_filter)) {
         $linkedObject = Objects::findObject($linked_obj_filter);
         $objs = $linkedObject->getLinkedObjects();
         foreach ($objs as $obj) {
             $object_ids_filter .= ($object_ids_filter == '' ? '' : ',') . $obj->getId();
         }
     }
     $filters = array();
     if (!is_null($types)) {
         $filters['types'] = $types;
     }
     if (!is_null($name_filter)) {
         $filters['name'] = $name_filter;
     }
     if ($object_ids_filter != '') {
         $filters['object_ids'] = $object_ids_filter;
     }
     $user = array_var($_GET, 'user');
     $trashed = array_var($_GET, 'trashed', false);
     $archived = array_var($_GET, 'archived', false);
     /* if there's an action to execute, do so */
     if (array_var($_GET, 'action') == 'delete') {
         $ids = explode(',', array_var($_GET, 'objects'));
         $result = ContentDataObjects::listing(array("extra_conditions" => " AND o.id IN (" . implode(",", $ids) . ") ", "include_deleted" => true));
         $objects = $result->objects;
         list($succ, $err) = $this->do_delete_objects($objects);
         if ($err > 0) {
             flash_error(lang('error delete objects', $err));
         } else {
             Hook::fire('after_object_delete_permanently', $ids, $ignored);
             flash_success(lang('success delete objects', $succ));
         }
     } else {
         if (array_var($_GET, 'action') == 'delete_permanently') {
             $ids = explode(',', array_var($_GET, 'objects'));
             //$result = Objects::getObjectsFromContext(active_context(), null, null, true, false, array('object_ids' => implode(",",$ids)));
             $objects = Objects::instance()->findAll(array("conditions" => "id IN (" . implode(",", $ids) . ")"));
             list($succ, $err) = $this->do_delete_objects($objects, true);
             if ($err > 0) {
                 flash_error(lang('error delete objects', $err));
             }
             if ($succ > 0) {
                 Hook::fire('after_object_delete_permanently', $ids, $ignored);
                 flash_success(lang('success delete objects', $succ));
             }
         } else {
             if (array_var($_GET, 'action') == 'markasread') {
                 $ids = explode(',', array_var($_GET, 'objects'));
                 list($succ, $err) = $this->do_mark_as_read_unread_objects($ids, true);
             } else {
                 if (array_var($_GET, 'action') == 'markasunread') {
                     $ids = explode(',', array_var($_GET, 'objects'));
                     list($succ, $err) = $this->do_mark_as_read_unread_objects($ids, false);
                 } else {
                     if (array_var($_GET, 'action') == 'empty_trash_can') {
                         $result = Objects::getObjectsFromContext(active_context(), 'trashed_on', 'desc', true);
                         $objects = $result->objects;
                         list($succ, $err) = $this->do_delete_objects($objects, true);
                         if ($err > 0) {
                             flash_error(lang('error delete objects', $err));
                         }
                         if ($succ > 0) {
                             flash_success(lang('success delete objects', $succ));
                         }
                     } else {
                         if (array_var($_GET, 'action') == 'archive') {
                             $ids = explode(',', array_var($_GET, 'objects'));
                             list($succ, $err) = $this->do_archive_unarchive_objects($ids, 'archive');
                             if ($err > 0) {
                                 flash_error(lang('error archive objects', $err));
                             } else {
                                 flash_success(lang('success archive objects', $succ));
                             }
                         } else {
                             if (array_var($_GET, 'action') == 'unarchive') {
                                 $ids = explode(',', array_var($_GET, 'objects'));
                                 list($succ, $err) = $this->do_archive_unarchive_objects($ids, 'unarchive');
                                 if ($err > 0) {
                                     flash_error(lang('error unarchive objects', $err));
                                 } else {
                                     flash_success(lang('success unarchive objects', $succ));
                                 }
                             } else {
                                 if (array_var($_GET, 'action') == 'unclassify') {
                                     $ids = explode(',', array_var($_GET, 'objects'));
                                     $err = 0;
                                     $succ = 0;
                                     foreach ($ids as $id) {
                                         $split = explode(":", $id);
                                         $type = $split[0];
                                         if (Plugins::instance()->isActivePlugin('mail') && $type == 'MailContents') {
                                             $email = MailContents::findById($split[1]);
                                             if (isset($email) && !$email->isDeleted() && $email->canEdit(logged_user())) {
                                                 if (MailController::do_unclassify($email)) {
                                                     $succ++;
                                                 } else {
                                                     $err++;
                                                 }
                                             } else {
                                                 $err++;
                                             }
                                         }
                                     }
                                     if ($err > 0) {
                                         flash_error(lang('error unclassify emails', $err));
                                     } else {
                                         flash_success(lang('success unclassify emails', $succ));
                                     }
                                 } else {
                                     if (array_var($_GET, 'action') == 'restore') {
                                         $errorMessage = null;
                                         $ids = explode(',', array_var($_GET, 'objects'));
                                         $success = 0;
                                         $error = 0;
                                         foreach ($ids as $id) {
                                             $obj = Objects::findObject($id);
                                             if ($obj->canDelete(logged_user())) {
                                                 try {
                                                     $obj->untrash($errorMessage);
                                                     if ($obj->getObjectTypeId() == 11) {
                                                         $event = ProjectEvents::findById($obj->getId());
                                                         if ($event->getExtCalId() != "") {
                                                             $this->created_event_google_calendar($obj, $event);
                                                         }
                                                     }
                                                     ApplicationLogs::createLog($obj, ApplicationLogs::ACTION_UNTRASH);
                                                     $success++;
                                                 } catch (Exception $e) {
                                                     $error++;
                                                 }
                                             } else {
                                                 $error++;
                                             }
                                         }
                                         if ($success > 0) {
                                             flash_success(lang("success untrash objects", $success));
                                         }
                                         if ($error > 0) {
                                             $errorString = is_null($errorMessage) ? lang("error untrash objects", $error) : $errorMessage;
                                             flash_error($errorString);
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     $filterName = array_var($_GET, 'name');
     $result = null;
     $context = active_context();
     $obj_type_types = array('content_object', 'dimension_object');
     if (array_var($_GET, 'include_comments')) {
         $obj_type_types[] = 'comment';
     }
     $type_condition = "";
     if ($types) {
         $type_condition = " AND name IN ('" . implode("','", $types) . "')";
     }
     $res = DB::executeAll("SELECT id from " . TABLE_PREFIX . "object_types WHERE type IN ('" . implode("','", $obj_type_types) . "') AND name <> 'file revision' {$type_condition} ");
     $type_ids = array();
     foreach ($res as $row) {
         if (ObjectTypes::isListableObjectType($row['id'])) {
             $types_ids[] = $row['id'];
         }
     }
     //Hook::fire('list_objects_type_ids', null, $types_ids);
     $type_ids_csv = implode(',', $types_ids);
     $extra_conditions = array();
     $extra_conditions[] = "object_type_id in ({$type_ids_csv})";
     if ($name_filter) {
         $extra_conditions[] = "name LIKE '%{$name_filter}%'";
     }
     //$pagination = Objects::getObjects($context,$start,$limit,$order,$orderdir,$trashed,$archived, $filters,$start, $limit, $obj_type_types);
     $pagination = ContentDataObjects::listing(array("start" => $start, "limit" => $limit, "order" => $order, "order_dir" => $orderdir, "trashed" => $trashed, "archived" => $archived, "types" => $types, "count_results" => false, "extra_conditions" => " AND " . implode(" AND ", $extra_conditions), "ignore_context" => $ignore_context));
     $result = $pagination->objects;
     $total_items = $pagination->total;
     if (!$result) {
         $result = array();
     }
     /* prepare response object */
     $info = array();
     foreach ($result as $obj) {
         $info_elem = $obj->getArrayInfo($trashed, $archived);
         $instance = Objects::instance()->findObject($info_elem['object_id']);
         $info_elem['url'] = $instance->getViewUrl();
         /* @var $instance Contact  */
         if ($instance instanceof Contact) {
             if ($instance->isCompany()) {
                 $info_elem['icon'] = 'ico-company';
                 $info_elem['type'] = 'company';
             }
         } else {
             if ($instance instanceof ProjectFile) {
                 $info_elem['mimeType'] = $instance->getTypeString();
             }
         }
         $info_elem['isRead'] = $instance->getIsRead(logged_user()->getId());
         $info_elem['manager'] = get_class($instance->manager());
         $info_elem['memPath'] = json_encode($instance->getMembersToDisplayPath());
         $info[] = $info_elem;
     }
     $listing = array("totalCount" => $total_items, "start" => $start, "objects" => $info);
     ajx_extra_data($listing);
     tpl_assign("listing", $listing);
     if (isset($reload) && $reload) {
         ajx_current("reload");
     } else {
         ajx_current("empty");
     }
 }
 /**
  * Resolve action to perform
  *
  * @param string $action
  * @param array $attributes
  * @return string $message
  */
 private function resolveAction($action, $attributes)
 {
     $resultMessage = "";
     $resultCode = 0;
     switch ($action) {
         case "delete":
             $err = 0;
             $succ = 0;
             for ($i = 0; $i < count($attributes["ids"]); $i++) {
                 $id = $attributes["ids"][$i];
                 $type = $attributes["types"][$i];
                 switch ($type) {
                     case "email":
                         $email = MailContents::findById($id);
                         if (isset($email) && $email->canDelete(logged_user())) {
                             if ($email->getState() == 2) {
                                 // we are deleting a draft email
                                 $emails_in_conversation = array($email);
                             } else {
                                 if (user_config_option('show_emails_as_conversations', true, logged_user()->getId())) {
                                     $emails_in_conversation = MailContents::getMailsFromConversation($email);
                                 } else {
                                     $emails_in_conversation = array($email);
                                 }
                             }
                             foreach ($emails_in_conversation as $email) {
                                 if ($email->canDelete(logged_user())) {
                                     try {
                                         $email->trash();
                                         ApplicationLogs::createLog($email, $email->getWorkspaces(), ApplicationLogs::ACTION_TRASH);
                                         $succ++;
                                     } catch (Exception $e) {
                                         $err++;
                                     }
                                 } else {
                                     $err++;
                                 }
                             }
                         } else {
                             $err++;
                         }
                         break;
                     default:
                         $err++;
                         break;
                 }
                 // switch
             }
             // for
             if ($err > 0) {
                 $resultCode = 2;
                 $resultMessage = lang("error delete objects", $err) . "<br />" . ($succ > 0 ? lang("success delete objects", $succ) : "");
             } else {
                 $resultMessage = lang("success delete objects", $succ);
             }
             ajx_add("overview-panel", "reload");
             break;
         case "tag":
             $tag = $attributes["tag"];
             if (!trim($tag)) {
                 break;
             }
             for ($i = 0; $i < count($attributes["ids"]); $i++) {
                 $id = $attributes["ids"][$i];
                 $type = $attributes["types"][$i];
                 switch ($type) {
                     case "email":
                         $email = MailContents::findById($id);
                         if (isset($email)) {
                             if (user_config_option('show_emails_as_conversations', true, logged_user()->getId())) {
                                 $emails_in_conversation = MailContents::getMailsFromConversation($email);
                             } else {
                                 $emails_in_conversation = array($email);
                             }
                             foreach ($emails_in_conversation as $email) {
                                 if ($email->canEdit(logged_user())) {
                                     Tags::addObjectTag($tag, $email);
                                     ApplicationLogs::createLog($email, $email->getWorkspaces(), ApplicationLogs::ACTION_TAG, false, null, true, $tag);
                                 }
                             }
                             $resultMessage = lang("success tag objects", '');
                         }
                         break;
                     default:
                         $resultMessage = lang("Unimplemented type: '" . $type . "'");
                         // if
                         $resultCode = 2;
                         break;
                 }
                 // switch
             }
             // for
             break;
         case "untag":
             $tag = $attributes["tag"];
             for ($i = 0; $i < count($attributes["ids"]); $i++) {
                 $id = $attributes["ids"][$i];
                 $type = $attributes["types"][$i];
                 switch ($type) {
                     case "email":
                         $email = MailContents::findById($id);
                         if (isset($email)) {
                             if (user_config_option('show_emails_as_conversations', true, logged_user()->getId())) {
                                 $emails_in_conversation = MailContents::getMailsFromConversation($email);
                             } else {
                                 $emails_in_conversation = array($email);
                             }
                             foreach ($emails_in_conversation as $email) {
                                 if ($email->canEdit(logged_user())) {
                                     if ($tag != '') {
                                         $email->deleteTag($tag);
                                     } else {
                                         $email->clearTags();
                                     }
                                 }
                             }
                             //ApplicationLogs::createLog($email, $email->getWorkspaces(), ApplicationLogs::ACTION_TAG,false,null,true,$tag);
                             $resultMessage = lang("success untag objects", '');
                         }
                         break;
                     default:
                         $resultMessage = lang("Unimplemented type: '" . $type . "'");
                         // if
                         $resultCode = 2;
                         break;
                 }
                 // switch
             }
             // for
             break;
         case "unclassify":
             for ($i = 0; $i < count($attributes["ids"]); $i++) {
                 $id = $attributes["ids"][$i];
                 $type = $attributes["types"][$i];
                 switch ($type) {
                     case "email":
                         $email = MailContents::findById($id);
                         if (isset($email) && !$email->isDeleted() && $email->canEdit(logged_user())) {
                             $this->do_unclassify($email);
                             ApplicationLogs::createLog($email, $email->getWorkspaces(), ApplicationLogs::ACTION_TAG, false, null, true, $tag);
                             $resultMessage = lang("success unclassify emails", count($attributes["ids"]));
                         }
                         break;
                     default:
                         $resultMessage = lang("Unimplemented type: '" . $type . "'");
                         // if
                         $resultCode = 2;
                         break;
                 }
                 // switch
             }
             // for
             break;
         case "move":
             $wsid = $attributes["moveTo"];
             $destination = Projects::findById($wsid);
             if (!$destination instanceof Project) {
                 $resultMessage = lang('project dnx');
                 $resultCode = 1;
             } else {
                 if (!can_add(logged_user(), $destination, 'MailContents')) {
                     $resultMessage = lang('no access permissions');
                     $resultCode = 1;
                 } else {
                     $count = 0;
                     for ($i = 0; $i < count($attributes["ids"]); $i++) {
                         $id = $attributes["ids"][$i];
                         $type = $attributes["types"][$i];
                         switch ($type) {
                             case "email":
                                 $email = MailContents::findById($id);
                                 if (user_config_option('show_emails_as_conversations', true, logged_user()->getId())) {
                                     $conversation = MailContents::getMailsFromConversation($email);
                                 } else {
                                     $conversation = array($email);
                                 }
                                 foreach ($conversation as $conv_email) {
                                     $this->addEmailToWorkspace($conv_email->getId(), $destination, array_var($attributes, "mantainWs", true));
                                     if (array_var($attributes, 'classify_atts') && $conv_email->getHasAttachments()) {
                                         MailUtilities::parseMail($conv_email->getContent(), $decoded, $parsedEmail, $warnings);
                                         $classification_data = array();
                                         for ($j = 0; $j < count(array_var($parsedEmail, "Attachments", array())); $j++) {
                                             $classification_data["att_" . $j] = true;
                                         }
                                         $tags = implode(",", $conv_email->getTagNames());
                                         $this->classifyFile($classification_data, $conv_email, $parsedEmail, array($destination), array_var($attributes, "mantainWs", true), $tags);
                                     }
                                 }
                                 $count++;
                                 break;
                             default:
                                 $resultMessage = lang("Unimplemented type: '" . $type . "'");
                                 // if
                                 $resultCode = 2;
                                 break;
                         }
                         // switch
                     }
                     // for
                     $resultMessage = lang("success move objects", $count);
                     $resultCode = 0;
                 }
             }
             break;
         case "checkmail":
             $resultCheck = MailController::checkmail();
             $resultMessage = $resultCheck[1];
             // if
             $resultCode = $resultCheck[0];
             ajx_add("overview-panel", "reload");
             break;
         case "markAsRead":
         case "markAsUnRead":
             for ($i = 0; $i < count($attributes["ids"]); $i++) {
                 $id = $attributes["ids"][$i];
                 $type = $attributes["types"][$i];
                 switch ($type) {
                     case "email":
                         $email = MailContents::findById($id);
                         if (isset($email)) {
                             if (user_config_option('show_emails_as_conversations', true, logged_user()->getId())) {
                                 $emails_in_conversation = MailContents::getMailsFromConversation($email);
                             } else {
                                 $emails_in_conversation = array($email);
                             }
                             foreach ($emails_in_conversation as $email) {
                                 if ($email->canEdit(logged_user())) {
                                     $email->setIsRead(logged_user()->getId(), $action == 'markAsRead');
                                 }
                             }
                         }
                         break;
                     default:
                         $resultMessage = lang("Unimplemented type: '" . $type . "'");
                         // if
                         $resultCode = 2;
                         break;
                 }
                 // switch
             }
             // for
             ajx_add("overview-panel", "reload");
             break;
         case "archive":
             $err = 0;
             $succ = 0;
             for ($i = 0; $i < count($attributes["ids"]); $i++) {
                 $id = $attributes["ids"][$i];
                 $type = $attributes["types"][$i];
                 switch ($type) {
                     case "email":
                         $email = MailContents::findById($id);
                         if (isset($email)) {
                             if (user_config_option('show_emails_as_conversations', true, logged_user()->getId())) {
                                 $emails_in_conversation = MailContents::getMailsFromConversation($email);
                             } else {
                                 $emails_in_conversation = array($email);
                             }
                             foreach ($emails_in_conversation as $email) {
                                 if ($email->canEdit(logged_user())) {
                                     try {
                                         $email->archive(null);
                                         ApplicationLogs::createLog($email, $email->getWorkspaces(), ApplicationLogs::ACTION_ARCHIVE);
                                         $succ++;
                                     } catch (Exception $e) {
                                         $err++;
                                     }
                                 }
                             }
                         } else {
                             $err++;
                         }
                         break;
                     default:
                         $err++;
                         break;
                 }
                 // switch
             }
             // for
             if ($err > 0) {
                 $resultCode = 2;
                 $resultMessage = lang("error archive objects", $err) . "<br />" . ($succ > 0 ? lang("success archive objects", $succ) : "");
             } else {
                 $resultMessage = lang("success archive objects", $succ);
             }
             ajx_add("overview-panel", "reload");
             break;
         default:
             if ($action) {
                 $resultMessage = lang("Unimplemented action: '" . $action . "'");
                 // if
                 $resultCode = 2;
             }
             break;
     }
     // switch
     return array("errorMessage" => $resultMessage, "errorCode" => $resultCode);
 }
示例#6
0
 public function forget_pass()
 {
     if (!empty($this->data)) {
         $data = $this->data['ForgetPassForm'];
         if (!isset($this->Captcha)) {
             //if Component was not loaded throug $components array()
             App::import('Component', 'Captcha');
             //load it
             $this->Captcha = new CaptchaComponent();
             //make instance
             $this->Captcha->startup($this);
             //and do some manually calling
         }
         $cap = $this->Captcha->getVerCode();
         if ($cap == $data['code']) {
             $user = $this->User->find('first', array('conditions' => array('User.username' => $data['username'], 'User.user_role_id' => $data['user_role_id'])));
             if (!empty($user)) {
                 $Mail = new MailController();
                 $Mail->constructClasses();
                 $pass = random_password();
                 $this->User->id = $user['User']['id'];
                 $this->User->save(array('password' => encrypt($pass, SALT)));
                 $arr = array();
                 $arr['TO_EMAIL'] = $user['User']['email'];
                 $arr['TO_NAME'] = $user['User']['username'];
                 $arr['USERNAME'] = $user['User']['username'];
                 $arr['PASSWORD'] = $pass;
                 $Mail->sendMail($user['User']['id'], 'forgot_password', $arr);
                 echo 'success';
                 die;
             } else {
                 echo 'error';
             }
         } else {
             echo 'code';
             die;
         }
     }
     die;
 }
if ($controller == "driver") {
    $driverCon = new DriverController($request, $method);
    $driverCon->resolve();
} else {
    if ($controller == "user") {
    } else {
        if ($controller == "admin") {
            $adminCon = new AdminController($request, $method);
            $adminCon->resolve();
        } else {
            if ($controller == "validate") {
                $validCon = new ValidationController($request, $method);
                $validCon->resolve();
            } else {
                if ($controller == "mail") {
                    $mailCon = new MailController($request, $method);
                    $mailCon->resolve();
                } else {
                    header('HTTP/1.1 400 Bad Request');
                    header('Content-Type: text/xml; charset=UTF-8');
                    echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
                    echo "<error>\n";
                    echo "<reason>Undefined API</reason>\n";
                    echo "<description>Kindly refer Ride on Bike API documentation</description>\n";
                    echo "</error>";
                    return;
                }
            }
        }
    }
}
    /**
     * Used for Drag & Drop, adds objects to a member
     * @author alvaro
     */
    function add_objects_to_member()
    {
        $ids = json_decode(array_var($_POST, 'objects'));
        $mem_id = array_var($_POST, 'member');
        if (!is_array($ids) || count($ids) == 0) {
            ajx_current("empty");
            return;
        }
        try {
            DB::beginWork();
            if ($mem_id) {
                $user_ids = array();
                $member = Members::findById($mem_id);
                $objects = array();
                $from = array();
                foreach ($ids as $oid) {
                    /* @var $obj ContentDataObject */
                    $obj = Objects::findObject($oid);
                    if ($obj instanceof ContentDataObject && $obj->canAddToMember(logged_user(), $member, active_context())) {
                        $dim_obj_type_content = DimensionObjectTypeContents::findOne(array('conditions' => array('`dimension_id`=? AND `dimension_object_type_id`=? AND `content_object_type_id`=?', $member->getDimensionId(), $member->getObjectTypeId(), $obj->getObjectTypeId())));
                        if (!$dim_obj_type_content instanceof DimensionObjectTypeContent) {
                            continue;
                        }
                        if (!$dim_obj_type_content->getIsMultiple() || array_var($_POST, 'remove_prev')) {
                            $db_res = DB::execute("SELECT group_concat(om.member_id) as old_members FROM " . TABLE_PREFIX . "object_members om INNER JOIN " . TABLE_PREFIX . "members m ON om.member_id=m.id WHERE m.dimension_id=" . $member->getDimensionId() . " AND om.object_id=" . $obj->getId());
                            $row = $db_res->fetchRow();
                            if (array_var($row, 'old_members') != "") {
                                $from[$obj->getId()] = $row['old_members'];
                            }
                            // remove from previous members
                            ObjectMembers::delete('`object_id` = ' . $obj->getId() . ' AND `member_id` IN (SELECT `m`.`id` FROM `' . TABLE_PREFIX . 'members` `m` WHERE `m`.`dimension_id` = ' . $member->getDimensionId() . ')');
                        }
                        $obj->addToMembers(array($member));
                        $obj->addToSharingTable();
                        $objects[] = $obj;
                        if (Plugins::instance()->isActivePlugin('mail') && $obj instanceof MailContent) {
                            $conversation = MailContents::getMailsFromConversation($obj);
                            foreach ($conversation as $conv_email) {
                                if (array_var($_POST, 'attachment') && $conv_email->getHasAttachments()) {
                                    MailUtilities::parseMail($conv_email->getContent(), $decoded, $parsedEmail, $warnings);
                                    $classification_data = array();
                                    for ($j = 0; $j < count(array_var($parsedEmail, "Attachments", array())); $j++) {
                                        $classification_data["att_" . $j] = true;
                                    }
                                    MailController::classifyFile($classification_data, $conv_email, $parsedEmail, array($member), array_var($_POST, 'remove_prev'), false);
                                }
                            }
                        }
                        // if object is contact ask to add default permissions in member
                        if ($obj instanceof Contact && $obj->isUser() && can_manage_security(logged_user())) {
                            $user_ids[] = $obj->getId();
                        }
                    } else {
                        throw new Exception(lang('you dont have permissions to classify object in member', $obj->getName(), $member->getName()));
                    }
                }
                // if object is contact ask to add default permissions in member
                if (can_manage_security(logged_user()) && count($user_ids) > 0 && $member->getDimension()->getDefinesPermissions()) {
                    evt_add('ask to assign default permissions', array('user_ids' => $user_ids, 'member' => array('id' => $member->getId(), 'name' => clean($member->getName())), ''));
                }
                Hook::fire('after_dragdrop_classify', $objects, $member);
                $display_name = $member->getName();
                $lang_key = count($ids) > 1 ? 'objects moved to member success' : 'object moved to member success';
                $log_datas = array();
                $actions = array();
                // add to application logs
                foreach ($objects as $obj) {
                    $actions[$obj->getId()] = array_var($from, $obj->getId()) ? ApplicationLogs::ACTION_MOVE : ApplicationLogs::ACTION_COPY;
                    $log_datas[$obj->getId()] = (array_var($from, $obj->getId()) ? "from:" . array_var($from, $obj->getId()) . ";" : "") . "to:" . $member->getId();
                }
            } else {
                if ($dim_id = array_var($_POST, 'dimension')) {
                    $dimension = Dimensions::getDimensionById($dim_id);
                    $from = array();
                    foreach ($ids as $oid) {
                        /* @var $obj ContentDataObject */
                        $obj = Objects::findObject($oid);
                        if ($obj instanceof ContentDataObject) {
                            $db_res = DB::execute("SELECT group_concat(om.member_id) as old_members FROM " . TABLE_PREFIX . "object_members om INNER JOIN " . TABLE_PREFIX . "members m ON om.member_id=m.id WHERE m.dimension_id=" . $dim_id . " AND om.object_id=" . $obj->getId());
                            $row = $db_res->fetchRow();
                            if (array_var($row, 'old_members') != "") {
                                $from[$obj->getId()] = $row['old_members'];
                            }
                            // remove from previous members
                            ObjectMembers::delete('`object_id` = ' . $obj->getId() . ' AND `member_id` IN (
							SELECT `m`.`id` FROM `' . TABLE_PREFIX . 'members` `m` WHERE `m`.`dimension_id` = ' . $dim_id . ')');
                        }
                        $obj->addToMembers(array());
                        $obj->addToSharingTable();
                        $objects[] = $obj;
                    }
                    $display_name = $dimension->getName();
                    $lang_key = count($ids) > 1 ? 'objects removed from' : 'object removed from';
                    $log_datas = array();
                    $actions = array();
                    // add to application logs
                    foreach ($objects as $obj) {
                        $actions[$obj->getId()] = array_var($from, $obj->getId()) ? ApplicationLogs::ACTION_MOVE : ApplicationLogs::ACTION_COPY;
                        $log_datas[$obj->getId()] = array_var($from, $obj->getId()) ? "from:" . array_var($from, $obj->getId()) . ";" : "";
                    }
                }
            }
            DB::commit();
            foreach ($objects as $object) {
                ApplicationLogs::instance()->createLog($object, $actions[$object->getId()], false, true, true, $log_datas[$object->getId()]);
            }
            flash_success(lang($lang_key, $display_name));
            if (array_var($_POST, 'reload')) {
                ajx_current('reload');
            } else {
                ajx_current('empty');
            }
        } catch (Exception $e) {
            DB::rollback();
            ajx_current("empty");
            flash_error($e->getMessage());
        }
    }
 /**
  * 
  * 
  */
 public function activity_feed()
 {
     ajx_set_no_back(true);
     require_javascript("og/modules/dashboardComments.js");
     require_javascript("jquery/jquery.scrollTo-min.js");
     /* get query parameters */
     $filesPerPage = config_option('files_per_page');
     $start = array_var($_GET, 'start') ? (int) array_var($_GET, 'start') : 0;
     $limit = array_var($_GET, 'limit') ? array_var($_GET, 'limit') : $filesPerPage;
     $order = array_var($_GET, 'sort');
     $orderdir = array_var($_GET, 'dir');
     $page = (int) ($start / $limit) + 1;
     $hide_private = !logged_user()->isMemberOfOwnerCompany();
     $typeCSV = array_var($_GET, 'type');
     $types = null;
     if ($typeCSV) {
         $types = explode(",", $typeCSV);
     }
     $name_filter = array_var($_GET, 'name');
     $linked_obj_filter = array_var($_GET, 'linkedobject');
     $object_ids_filter = '';
     if (!is_null($linked_obj_filter)) {
         $linkedObject = Objects::findObject($linked_obj_filter);
         $objs = $linkedObject->getLinkedObjects();
         foreach ($objs as $obj) {
             $object_ids_filter .= ($object_ids_filter == '' ? '' : ',') . $obj->getId();
         }
     }
     $filters = array();
     if (!is_null($types)) {
         $filters['types'] = $types;
     }
     if (!is_null($name_filter)) {
         $filters['name'] = $name_filter;
     }
     if ($object_ids_filter != '') {
         $filters['object_ids'] = $object_ids_filter;
     }
     $user = array_var($_GET, 'user');
     $trashed = array_var($_GET, 'trashed', false);
     $archived = array_var($_GET, 'archived', false);
     /* if there's an action to execute, do so */
     if (array_var($_GET, 'action') == 'delete') {
         $ids = explode(',', array_var($_GET, 'objects'));
         $result = Objects::getObjectsFromContext(active_context(), null, null, false, false, array('object_ids' => implode(",", $ids)));
         $objects = $result->objects;
         list($succ, $err) = $this->do_delete_objects($objects);
         if ($err > 0) {
             flash_error(lang('error delete objects', $err));
         } else {
             flash_success(lang('success delete objects', $succ));
         }
     } else {
         if (array_var($_GET, 'action') == 'delete_permanently') {
             $ids = explode(',', array_var($_GET, 'objects'));
             $result = Objects::getObjectsFromContext(active_context(), null, null, true, false, array('object_ids' => implode(",", $ids)));
             $objects = $result->objects;
             list($succ, $err) = $this->do_delete_objects($objects, true);
             if ($err > 0) {
                 flash_error(lang('error delete objects', $err));
             }
             if ($succ > 0) {
                 flash_success(lang('success delete objects', $succ));
             }
         } else {
             if (array_var($_GET, 'action') == 'markasread') {
                 $ids = explode(',', array_var($_GET, 'objects'));
                 list($succ, $err) = $this->do_mark_as_read_unread_objects($ids, true);
             } else {
                 if (array_var($_GET, 'action') == 'markasunread') {
                     $ids = explode(',', array_var($_GET, 'objects'));
                     list($succ, $err) = $this->do_mark_as_read_unread_objects($ids, false);
                 } else {
                     if (array_var($_GET, 'action') == 'empty_trash_can') {
                         $result = Objects::getObjectsFromContext(active_context(), 'trashed_on', 'desc', true);
                         $objects = $result->objects;
                         list($succ, $err) = $this->do_delete_objects($objects, true);
                         if ($err > 0) {
                             flash_error(lang('error delete objects', $err));
                         }
                         if ($succ > 0) {
                             flash_success(lang('success delete objects', $succ));
                         }
                     } else {
                         if (array_var($_GET, 'action') == 'archive') {
                             $ids = explode(',', array_var($_GET, 'objects'));
                             list($succ, $err) = $this->do_archive_unarchive_objects($ids, 'archive');
                             if ($err > 0) {
                                 flash_error(lang('error archive objects', $err));
                             } else {
                                 flash_success(lang('success archive objects', $succ));
                             }
                         } else {
                             if (array_var($_GET, 'action') == 'unarchive') {
                                 $ids = explode(',', array_var($_GET, 'objects'));
                                 list($succ, $err) = $this->do_archive_unarchive_objects($ids, 'unarchive');
                                 if ($err > 0) {
                                     flash_error(lang('error unarchive objects', $err));
                                 } else {
                                     flash_success(lang('success unarchive objects', $succ));
                                 }
                             } else {
                                 if (array_var($_GET, 'action') == 'unclassify') {
                                     $ids = explode(',', array_var($_GET, 'objects'));
                                     $err = 0;
                                     $succ = 0;
                                     foreach ($ids as $id) {
                                         $split = explode(":", $id);
                                         $type = $split[0];
                                         if ($type == 'MailContents') {
                                             $email = MailContents::findById($split[1]);
                                             if (isset($email) && !$email->isDeleted() && $email->canEdit(logged_user())) {
                                                 if (MailController::do_unclassify($email)) {
                                                     $succ++;
                                                 } else {
                                                     $err++;
                                                 }
                                             } else {
                                                 $err++;
                                             }
                                         }
                                     }
                                     if ($err > 0) {
                                         flash_error(lang('error unclassify emails', $err));
                                     } else {
                                         flash_success(lang('success unclassify emails', $succ));
                                     }
                                 } else {
                                     if (array_var($_GET, 'action') == 'restore') {
                                         $errorMessage = null;
                                         $ids = explode(',', array_var($_GET, 'objects'));
                                         $success = 0;
                                         $error = 0;
                                         foreach ($ids as $id) {
                                             $obj = Objects::findObject($id);
                                             if ($obj->canDelete(logged_user())) {
                                                 try {
                                                     $obj->untrash($errorMessage);
                                                     ApplicationLogs::createLog($obj, ApplicationLogs::ACTION_UNTRASH);
                                                     $success++;
                                                 } catch (Exception $e) {
                                                     $error++;
                                                 }
                                             } else {
                                                 $error++;
                                             }
                                         }
                                         if ($success > 0) {
                                             flash_success(lang("success untrash objects", $success));
                                         }
                                         if ($error > 0) {
                                             $errorString = is_null($errorMessage) ? lang("error untrash objects", $error) : $errorMessage;
                                             flash_error($errorString);
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     /*FIXME else if (array_var($_GET, 'action') == 'move') {
     			$wsid = array_var($_GET, "moveTo");
     			$destination = Projects::findById($wsid);
     			if (!$destination instanceof Project) {
     				$resultMessage = lang('project dnx');
     				$resultCode = 1;
     			} else if (!can_add(logged_user(), $destination, 'ProjectMessages')) {
     				$resultMessage = lang('no access permissions');
     				$resultCode = 1;
     			} else {
     				$ids = explode(',', array_var($_GET, 'objects'));
     				$count = 0;
     				DB::beginWork();
     				foreach ($ids as $id) {
     					$split = explode(":", $id);
     					$type = $split[0];
     					$obj = Objects::findObject($split[1]);
     					$mantainWs = array_var($_GET, "mantainWs");
     					if ($type != 'Projects' && $obj->canEdit(logged_user())) {
     						if ($type == 'MailContents') {
     							$email = MailContents::findById($split[1]);
     							$conversation = MailContents::getMailsFromConversation($email);
     							foreach ($conversation as $conv_email) {
     								$count += MailController::addEmailToWorkspace($conv_email->getId(), $destination, $mantainWs);
     								if (array_var($_GET, 'classify_atts') && $conv_email->getHasAttachments()) {
     									MailUtilities::parseMail($conv_email->getContent(), $decoded, $parsedEmail, $warnings);
     									$classification_data = array();
     									for ($j=0; $j < count(array_var($parsedEmail, "Attachments", array())); $j++) {
     										$classification_data["att_".$j] = true;		
     									}
     									$tags = implode(",", $conv_email->getTagNames());
     									MailController::classifyFile($classification_data, $conv_email, $parsedEmail, array($destination), $mantainWs, $tags);
     								}								
     							}
     							$count++;
     						} else {
     							if (!$mantainWs || $type == 'ProjectTasks' || $type == 'ProjectMilestones') {
     								$removed = "";
     								$ws = $obj->getWorkspaces();
     								foreach ($ws as $w) {
     									if (can_add(logged_user(), $w, $type)) {
     										$obj->removeFromWorkspace($w);
     										$removed .= $w->getId() . ",";
     									}
     								}
     								$removed = substr($removed, 0, -1);
     								$log_action = ApplicationLogs::ACTION_MOVE;
     								$log_data = ($removed == "" ? "" : "from:$removed;") . "to:$wsid";
     							} else {
     								$log_action = ApplicationLogs::ACTION_COPY;
     								$log_data = "to:$wsid";
     							}
     							$obj->addToWorkspace($destination);
     							ApplicationLogs::createLog($obj, $log_action, false, null, true, $log_data);
     							$count++;
     						}
     					}
     				}
     				if ($count > 0) {
     					$reload = true;
     					DB::commit();
     					flash_success(lang("success move objects", $count));
     				} else {
     					DB::rollback();
     				}
     			}
     		}*/
     $filterName = array_var($_GET, 'name');
     $result = null;
     $context = active_context();
     $obj_type_types = array('content_object');
     if (array_var($_GET, 'include_comments')) {
         $obj_type_types[] = 'comment';
     }
     $pagination = Objects::getObjects($context, $start, $limit, $order, $orderdir, $trashed, $archived, $filters, $start, $limit, $obj_type_types);
     $result = $pagination->objects;
     $total_items = $pagination->total;
     if (!$result) {
         $result = array();
     }
     /* prepare response object */
     $info = array();
     foreach ($result as $obj) {
         $info_elem = $obj->getArrayInfo($trashed, $archived);
         $instance = Objects::instance()->findObject($info_elem['object_id']);
         $info_elem['url'] = $instance->getViewUrl();
         if (method_exists($instance, "getText")) {
             $info_elem['content'] = $instance->getText();
         }
         $info_elem['picture'] = $instance->getCreatedBy()->getPictureUrl();
         $info_elem['friendly_date'] = friendly_date($instance->getCreatedOn());
         $info_elem['comment'] = $instance->getComments();
         /* @var $instance Contact  */
         if ($instance instanceof Contact) {
             if ($instance->isCompany()) {
                 $info_elem['icon'] = 'ico-company';
                 $info_elem['type'] = 'company';
             }
         }
         $info_elem['isRead'] = $instance->getIsRead(logged_user()->getId());
         $info_elem['manager'] = get_class($instance->manager());
         $info[] = $info_elem;
     }
     $listing = array("totalCount" => $total_items, "start" => $start, "objects" => $info);
     tpl_assign("feeds", $listing);
 }
 /**
  * Handle demand for contact page
  *
  * @param array $get : get parameters
  * @param array $post : post parameters
  * @return Template
  */
 private function handlePageContact($post)
 {
     $mailController = new MailController();
     $t = $mailController->handleMail($post);
     $t = $this->prepareDatasForNewsPanel($t);
     $t->central = $this->targetPageContact;
     //$t->centralFooter = $this::targetPageGeneralFooter;
     $t->template = $this->templateSimple;
     return $t;
 }
 function move()
 {
     if (logged_user()->isGuest()) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     ajx_current("empty");
     $ids = array_var($_GET, 'ids');
     if (!$ids) {
         return;
     }
     $wsid = array_var($_GET, 'ws');
     $keep = array_var($_GET, 'keep', 1) == 1;
     $atts = array_var($_GET, 'atts', 0) == 1;
     $workspace = Projects::findById($wsid);
     if (!$workspace instanceof Project) {
         flash_error(lang('project dnx'));
         return;
     }
     $id_list = explode(",", $ids);
     $err = 0;
     $succ = 0;
     foreach ($id_list as $cid) {
         list($manager, $id) = explode(":", $cid);
         if (isset($maganer) && $maganer == 'Projects') {
             continue;
         }
         try {
             $obj = get_object_by_manager_and_id($id, $manager);
             if ($obj instanceof ProjectDataObject && $obj->canEdit(logged_user())) {
                 if ($obj instanceof MailContent) {
                     $conversation = MailContents::getMailsFromConversation($obj);
                     $count = 0;
                     foreach ($conversation as $conv_email) {
                         $count += MailController::addEmailToWorkspace($conv_email->getId(), $workspace, $keep);
                         if (array_var($_GET, 'atts') && $conv_email->getHasAttachments()) {
                             MailUtilities::parseMail($conv_email->getContent(), $decoded, $parsedEmail, $warnings);
                             $classification_data = array();
                             for ($j = 0; $j < count(array_var($parsedEmail, "Attachments", array())); $j++) {
                                 $classification_data["att_" . $j] = true;
                             }
                             $tags = implode(",", $conv_email->getTagNames());
                             MailController::classifyFile($classification_data, $conv_email, $parsedEmail, array($workspace), $keep, $tags);
                         }
                     }
                     $succ++;
                 } else {
                     $remain = 0;
                     if (!$keep || $obj instanceof ProjectTask || $obj instanceof ProjectMilestone) {
                         // Tasks and Milestones can have only 1 workspace
                         $removed = "";
                         $ws = $obj->getWorkspaces();
                         foreach ($ws as $w) {
                             if (can_add(logged_user(), $w, get_class($obj->manager()))) {
                                 $obj->removeFromWorkspace($w);
                                 $removed .= $w->getId() . ",";
                             } else {
                                 $remain++;
                             }
                         }
                         $removed = substr($removed, 0, -1);
                         $log_action = ApplicationLogs::ACTION_MOVE;
                         $log_data = ($removed == "" ? "" : "from:{$removed};") . "to:{$wsid}";
                     } else {
                         $log_action = ApplicationLogs::ACTION_COPY;
                         $log_data = "to:{$wsid}";
                     }
                     if ($remain > 0 && ($obj instanceof ProjectTask || $obj instanceof ProjectMilestone)) {
                         $err++;
                     } else {
                         $obj->addToWorkspace($workspace);
                         ApplicationLogs::createLog($obj, $obj->getWorkspaces(), $log_action, false, null, true, $log_data);
                         $succ++;
                     }
                 }
             } else {
                 $err++;
             }
         } catch (Exception $e) {
             $err++;
         }
     }
     if ($err > 0) {
         flash_error(lang("error move objects", $err));
     } else {
         flash_success(lang("success move objects", $succ));
     }
 }
 /**
  * Resolve action to perform
  *
  * @param string $action
  * @param array $attributes
  * @return string $message
  */
 private function resolveAction($action, $attributes)
 {
     $resultMessage = "";
     $resultCode = 0;
     switch ($action) {
         case "delete":
             $err = 0;
             $succ = 0;
             for ($i = 0; $i < count($attributes["ids"]); $i++) {
                 $id = $attributes["ids"][$i];
                 $type = $attributes["types"][$i];
                 switch ($type) {
                     case "email":
                         $email = MailContents::findById($id);
                         if ($email instanceof MailContent && $email->canDelete(logged_user())) {
                             if ($email->getState() == 2) {
                                 // we are deleting a draft email
                                 $emails_in_conversation = array($email);
                             } else {
                                 if (user_config_option('show_emails_as_conversations', true, logged_user()->getId())) {
                                     $emails_in_conversation = MailContents::getMailsFromConversation($email);
                                 } else {
                                     $emails_in_conversation = array($email);
                                 }
                             }
                             foreach ($emails_in_conversation as $email) {
                                 if ($email->canDelete(logged_user())) {
                                     try {
                                         $email->trash();
                                         ApplicationLogs::createLog($email, $email->getWorkspaces(), ApplicationLogs::ACTION_TRASH);
                                         $succ++;
                                     } catch (Exception $e) {
                                         $err++;
                                     }
                                 } else {
                                     $err++;
                                 }
                             }
                         } else {
                             $err++;
                         }
                         break;
                     default:
                         $err++;
                         break;
                 }
                 // switch
             }
             // for
             if ($err > 0) {
                 $resultCode = 2;
                 $resultMessage = lang("error delete objects", $err) . "<br />" . ($succ > 0 ? lang("success delete objects", $succ) : "");
             } else {
                 $resultMessage = lang("success delete objects", $succ);
             }
             ajx_add("overview-panel", "reload");
             break;
         case "unclassify":
             for ($i = 0; $i < count($attributes["ids"]); $i++) {
                 $id = $attributes["ids"][$i];
                 $type = $attributes["types"][$i];
                 switch ($type) {
                     case "email":
                         $email = MailContents::findById($id);
                         if (isset($email) && !$email->isDeleted() && $email->canEdit(logged_user())) {
                             $this->do_unclassify($email);
                             ApplicationLogs::createLog($email, $email->getWorkspaces(), ApplicationLogs::ACTION_TAG, false, null, true, $tag);
                             $resultMessage = lang("success unclassify emails", count($attributes["ids"]));
                         }
                         break;
                     default:
                         $resultMessage = "Unimplemented type: '" . $type . "'";
                         $resultCode = 2;
                         break;
                 }
                 // switch
             }
             // for
             break;
         case "checkmail":
             $resultCheck = MailController::checkmail();
             $resultMessage = $resultCheck[1];
             // if
             $resultCode = $resultCheck[0];
             ajx_add("overview-panel", "reload");
             break;
         case "markAsRead":
         case "markAsUnRead":
             for ($i = 0; $i < count($attributes["ids"]); $i++) {
                 $id = $attributes["ids"][$i];
                 $type = $attributes["types"][$i];
                 switch ($type) {
                     case "email":
                         $email = MailContents::findById($id);
                         if (isset($email)) {
                             if (user_config_option('show_emails_as_conversations', true, logged_user()->getId())) {
                                 $emails_in_conversation = MailContents::getMailsFromConversation($email);
                             } else {
                                 $emails_in_conversation = array($email);
                             }
                             foreach ($emails_in_conversation as $email) {
                                 if ($email->canEdit(logged_user())) {
                                     $email->setIsRead(logged_user()->getId(), $action == 'markAsRead');
                                 }
                             }
                         }
                         break;
                     default:
                         $resultMessage = "Unimplemented type: '" . $type . "'";
                         $resultCode = 2;
                         break;
                 }
                 // switch
             }
             // for
             ajx_add("overview-panel", "reload");
             break;
         case "archive":
             $err = 0;
             $succ = 0;
             for ($i = 0; $i < count($attributes["ids"]); $i++) {
                 $id = $attributes["ids"][$i];
                 $type = $attributes["types"][$i];
                 switch ($type) {
                     case "email":
                         $email = MailContents::findById($id);
                         if (isset($email)) {
                             if (user_config_option('show_emails_as_conversations', true, logged_user()->getId())) {
                                 $emails_in_conversation = MailContents::getMailsFromConversation($email);
                             } else {
                                 $emails_in_conversation = array($email);
                             }
                             foreach ($emails_in_conversation as $email) {
                                 if ($email->canEdit(logged_user())) {
                                     try {
                                         $email->archive(null);
                                         ApplicationLogs::createLog($email, $email->getWorkspaces(), ApplicationLogs::ACTION_ARCHIVE);
                                         $succ++;
                                     } catch (Exception $e) {
                                         $err++;
                                     }
                                 }
                             }
                         } else {
                             $err++;
                         }
                         break;
                     default:
                         $err++;
                         break;
                 }
                 // switch
             }
             // for
             if ($err > 0) {
                 $resultCode = 2;
                 $resultMessage = lang("error archive objects", $err) . "<br />" . ($succ > 0 ? lang("success archive objects", $succ) : "");
             } else {
                 $resultMessage = lang("success archive objects", $succ);
             }
             ajx_add("overview-panel", "reload");
             break;
         default:
             if ($action) {
                 $resultMessage = "Unimplemented action: '" . $action . "'";
                 $resultCode = 2;
             }
             break;
     }
     // switch
     return array("errorMessage" => $resultMessage, "errorCode" => $resultCode);
 }
	/**
	 * Used for Drag & Drop, adds objects to a member
	 * @author alvaro
	 */
	function add_objects_to_member() {
		$ids = json_decode(array_var($_POST, 'objects'));
		$mem_id = array_var($_POST, 'member');
		
		if (!is_array($ids) || count($ids) == 0) {
			ajx_current("empty");
			return;
		}
                
		$member = Members::findById($mem_id);
		
		try {
			DB::beginWork();
			
			$objects = array();
			$from = array();
			foreach ($ids as $oid) {
				/* @var $obj ContentDataObject */
				$obj = Objects::findObject($oid);
				if ($obj instanceof ContentDataObject && $obj->canAddToMember(logged_user(), $member, active_context())) {
					
					$dim_obj_type_content = DimensionObjectTypeContents::findOne(array('conditions' => array('`dimension_id`=? AND `dimension_object_type_id`=? AND `content_object_type_id`=?', $member->getDimensionId(), $member->getObjectTypeId(), $obj->getObjectTypeId())));
					if (!($dim_obj_type_content instanceof DimensionObjectTypeContent)) continue;
					if (!$dim_obj_type_content->getIsMultiple() || array_var($_POST, 'remove_prev')) {
						$db_res = DB::execute("SELECT group_concat(om.member_id) as old_members FROM ".TABLE_PREFIX."object_members om INNER JOIN ".TABLE_PREFIX."members m ON om.member_id=m.id WHERE m.dimension_id=".$member->getDimensionId()." AND om.object_id=".$obj->getId());
						$row = $db_res->fetchRow();
						if (array_var($row, 'old_members') != "") $from[$obj->getId()] = $row['old_members'];
						// remove from previous members
						ObjectMembers::delete('`object_id` = ' . $obj->getId() . ' AND `member_id` IN (SELECT `m`.`id` FROM `'.TABLE_PREFIX.'members` `m` WHERE `m`.`dimension_id` = '.$member->getDimensionId().')');
					}
					
					$obj->addToMembers(array($member));
					$obj->addToSharingTable();
					$objects[] = $obj;
					
					if ($obj->allowsTimeslots()) {
						$timeslots = $obj->getTimeslots();
						foreach ($timeslots as $timeslot) {
							$ts_mids = ObjectMembers::getMemberIdsByObject($timeslot->getId());
							// if classified then reclassify
							if (count($ts_mids)) {
								if (array_var($_POST, 'remove_prev')) {
									ObjectMembers::delete('`object_id` = ' . $timeslot->getId() . ' AND `member_id` IN (SELECT `m`.`id` FROM `'.TABLE_PREFIX.'members` `m` WHERE `m`.`dimension_id` = '.$member->getDimensionId().')');
								}
								$timeslot->addToMembers(array($member));
								$timeslot->addToSharingTable();
								$objects[] = $timeslot;
							}
						}
					}
					
					if ($obj instanceof MailContent) {
						$conversation = MailContents::getMailsFromConversation($obj);
						foreach ($conversation as $conv_email) {
							if (array_var($_POST, 'attachment') && $conv_email->getHasAttachments()) {
								MailUtilities::parseMail($conv_email->getContent(), $decoded, $parsedEmail, $warnings);
								$classification_data = array();
								for ($j=0; $j < count(array_var($parsedEmail, "Attachments", array())); $j++) {
									$classification_data["att_".$j] = true;
								}
								MailController::classifyFile($classification_data, $conv_email, $parsedEmail, array($member), array_var($_POST, 'remove_prev'));
							}
						}
					}
				} else {
					throw new Exception(lang('you dont have permissions to classify object in member', $obj->getName(), $member->getName()));
				}
			}
			
			Hook::fire('after_dragdrop_classify', $objects, $member);
			
			DB::commit();
			
			// add to application logs
			foreach ($objects as $object) {
				$action = array_var($from, $obj->getId()) ? ApplicationLogs::ACTION_MOVE : ApplicationLogs::ACTION_COPY;
				$log_data = (array_var($from, $obj->getId()) ? "from:" . array_var($from, $obj->getId()) . ";" : "") . "to:" . $member->getId();
				ApplicationLogs::instance()->createLog($object, $action, false, true, true, $log_data);
			}
			
			$lang_key = count($ids)>1 ? 'objects moved to member success' : 'object moved to member success';
			flash_success(lang($lang_key, $member->getName()));
			if (array_var($_POST, 'reload')) ajx_current('reload');
			else ajx_current('empty');
			
		} catch (Exception $e) {
			DB::rollback();
			ajx_current("empty");
			flash_error($e->getMessage());
		}
	}
 private function processListActions()
 {
     $linkedObject = null;
     if (array_var($_GET, 'action') == 'delete') {
         $ids = explode(',', array_var($_GET, 'objects'));
         $result = ContentDataObjects::listing(array("extra_conditions" => " AND o.id IN (" . implode(",", $ids) . ") ", "include_deleted" => true));
         $objects = $result->objects;
         foreach ($objects as $object) {
             $object->setDontMakeCalculations(true);
         }
         $real_deleted_ids = array();
         list($succ, $err) = $this->do_delete_objects($objects, false, $real_deleted_ids);
         if ($err > 0) {
             flash_error(lang('error delete objects', $err));
         } else {
             Hook::fire('after_object_delete_permanently', $real_deleted_ids, $ignored);
             flash_success(lang('success delete objects', $succ));
         }
     } else {
         if (array_var($_GET, 'action') == 'delete_permanently') {
             $ids = explode(',', array_var($_GET, 'objects'));
             $objects = Objects::instance()->findAll(array("conditions" => "id IN (" . implode(",", $ids) . ")"));
             $real_deleted_ids = array();
             list($succ, $err) = $this->do_delete_objects($objects, true, $real_deleted_ids);
             if ($err > 0) {
                 flash_error(lang('error delete objects', $err));
             }
             if ($succ > 0) {
                 Hook::fire('after_object_delete_permanently', $real_deleted_ids, $ignored);
                 flash_success(lang('success delete objects', $succ));
             }
         } else {
             if (array_var($_GET, 'action') == 'markasread') {
                 $ids = explode(',', array_var($_GET, 'objects'));
                 list($succ, $err) = $this->do_mark_as_read_unread_objects($ids, true);
             } else {
                 if (array_var($_GET, 'action') == 'markasunread') {
                     $ids = explode(',', array_var($_GET, 'objects'));
                     list($succ, $err) = $this->do_mark_as_read_unread_objects($ids, false);
                 } else {
                     if (array_var($_GET, 'action') == 'empty_trash_can') {
                         $result = ContentDataObjects::listing(array("select_columns" => array('id'), "raw_data" => true, "trashed" => true));
                         $objects = $result->objects;
                         foreach ($objects as $object) {
                             $object->setDontMakeCalculations(true);
                         }
                         if (count($objects) > 0) {
                             $obj_ids_str = implode(',', array_flat($objects));
                             $extra_conds = "AND o.id IN ({$obj_ids_str})";
                             $count = Trash::purge_trash(0, 1000, $extra_conds);
                             flash_success(lang('success delete objects', $count));
                         }
                     } else {
                         if (array_var($_GET, 'action') == 'archive') {
                             $ids = explode(',', array_var($_GET, 'objects'));
                             list($succ, $err) = $this->do_archive_unarchive_objects($ids, 'archive');
                             if ($err > 0) {
                                 flash_error(lang('error archive objects', $err));
                             } else {
                                 flash_success(lang('success archive objects', $succ));
                             }
                         } else {
                             if (array_var($_GET, 'action') == 'unarchive') {
                                 $ids = explode(',', array_var($_GET, 'objects'));
                                 list($succ, $err) = $this->do_archive_unarchive_objects($ids, 'unarchive');
                                 if ($err > 0) {
                                     flash_error(lang('error unarchive objects', $err));
                                 } else {
                                     flash_success(lang('success unarchive objects', $succ));
                                 }
                             } else {
                                 if (array_var($_GET, 'action') == 'unclassify') {
                                     $ids = explode(',', array_var($_GET, 'objects'));
                                     $err = 0;
                                     $succ = 0;
                                     foreach ($ids as $id) {
                                         $split = explode(":", $id);
                                         $type = $split[0];
                                         if (Plugins::instance()->isActivePlugin('mail') && $type == 'MailContents') {
                                             $email = MailContents::findById($split[1]);
                                             if (isset($email) && !$email->isDeleted() && $email->canEdit(logged_user())) {
                                                 if (MailController::do_unclassify($email)) {
                                                     $succ++;
                                                 } else {
                                                     $err++;
                                                 }
                                             } else {
                                                 $err++;
                                             }
                                         }
                                     }
                                     if ($err > 0) {
                                         flash_error(lang('error unclassify emails', $err));
                                     } else {
                                         flash_success(lang('success unclassify emails', $succ));
                                     }
                                 } else {
                                     if (array_var($_GET, 'action') == 'restore') {
                                         $errorMessage = null;
                                         $ids = explode(',', array_var($_GET, 'objects'));
                                         $success = 0;
                                         $error = 0;
                                         foreach ($ids as $id) {
                                             $obj = Objects::findObject($id);
                                             $obj->setDontMakeCalculations(true);
                                             if ($obj->canDelete(logged_user())) {
                                                 try {
                                                     $obj->untrash($errorMessage);
                                                     if ($obj->getObjectTypeId() == 11) {
                                                         $event = ProjectEvents::findById($obj->getId());
                                                         if ($event->getExtCalId() != "") {
                                                             $this->created_event_google_calendar($obj, $event);
                                                         }
                                                     }
                                                     ApplicationLogs::createLog($obj, ApplicationLogs::ACTION_UNTRASH);
                                                     $success++;
                                                 } catch (Exception $e) {
                                                     $error++;
                                                 }
                                             } else {
                                                 $error++;
                                             }
                                         }
                                         if ($success > 0) {
                                             flash_success(lang("success untrash objects", $success));
                                         }
                                         if ($error > 0) {
                                             $errorString = is_null($errorMessage) ? lang("error untrash objects", $error) : $errorMessage;
                                             flash_error($errorString);
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     if (!array_var($_GET, 'only_result')) {
         $ignored = null;
         Hook::fire('after_multi_object_action', array('object_ids' => explode(',', array_var($_GET, 'objects')), 'action' => array_var($_GET, 'action')), $ignored);
     }
 }
示例#15
0
<?php

$PAGELEVEL = EMISOR;
$AUTH_redirectTo = $NOAU;
pageClearence($PAGELEVEL, $AUTH_redirectTo);
$data = array();
$path = '../';
if (isset($_POST['button'])) {
    $data = "";
    $data = $_POST;
    $mailController = new MailController($path);
    $data['idEmpresa'] = base64_decode($_SESSION['idempresa']);
    $response = $mailController->execute('enviarMail', $data);
    error_log($response);
    ob_clean();
    header("location: contenido.php?pr=envr&fc=" . $_GET["fc"] . "&exitoMail=" . $response);
}
if (isset($_GET["exitoMail"])) {
    if ($_GET["exitoMail"]) {
        $msg = '<div id="barr">
						<div class="bari"><a href="contenido.php">Men&uacute; principal</a> :: Facturas</div>
					</div>
					<div id="cont">
						<span class="titt">Facturas</span>
						<!-- Inicia columna izquierda -->
						<div class="coli"><a href="contenido.php?pr=fact">Ver todas las facturas emitidas</a></div>
						<!-- Termina columna izquierda -->
						<!-- Inicia columna derecha -->
						<div class="cold">La factura ha sido enviada</div>
					</div>';
    } else {
示例#16
0
    $controller = new HelpController();
    $controller->show();
});
$app->get('/search', function () {
    UserHelper::requireProfile();
    $controller = new SearchController();
    $controller->index();
});
$app->post('/inbox', function () {
    fAuthorization::requireLoggedIn();
    $controller = new MailController();
    $controller->create();
});
$app->delete('/inbox/:id', function ($id) {
    fAuthorization::requireLoggedIn();
    $controller = new MailController();
    $controller->delete($id);
});
$app->post('/msgs', function () {
    fAuthorization::requireLoggedIn();
    $controller = new MsgController();
    $controller->create();
});
$app->post('/search', function () {
    fAuthorization::requireLoggedIn();
    $controller = new SearchController();
    $controller->show();
});
$app->delete('/msgs/:id', function ($id) {
    fAuthorization::requireLoggedIn();
    $controller = new MsgController();
示例#17
0
<?php

include "../Controllers/MailController.php";
$mail = new MailController();
$mail->SendMail();
 function sendOutboxMailsAllAccounts($from_time)
 {
     if (is_null($from_time) || !$from_time instanceof DateTimeValue) {
         return;
     }
     $mail_controller = new MailController();
     $accounts = MailAccounts::findAll();
     foreach ($accounts as $account) {
         try {
             if ($account instanceof MailAccount) {
                 $user = Contacts::findById($account->getContactId());
                 if ($user instanceof Contact) {
                     $mail_controller->send_outbox_mails($user, $account, $from_time);
                 }
             }
         } catch (Exception $e) {
             Logger::log($e->getMessage());
         }
     }
 }
 public function deny_agent($id = null)
 {
     $this->Access->checkRestaurantSession();
     if (!empty($id)) {
         $Mail = new MailController();
         $Mail->constructClasses();
         $this->AgentRestaurant->id = $id;
         $this->AgentRestaurant->save(array('status' => '2'));
         $this->AgentRestaurant->recursive = 2;
         $data = $this->AgentRestaurant->find('first', array('conditions' => array('AgentRestaurant.id' => $id)));
         $arr = array();
         $arr['TO_EMAIL'] = $data['Agent']['User']['email'];
         $arr['TO_NAME'] = $data['Agent']['name'];
         $arr['RESTAURANT_NAME'] = $data['Restaurant']['restaurant_name'];
         $arr['CONTACT'] = $data['Restaurant']['phone'];
         $Mail->sendMail($data['Agent']['User']['id'], 'denied_agent_request', $arr);
         $this->Session->setFlash(__('Agent request has been denied.'));
         $this->redirect(array('controller' => 'restaurants', 'action' => 'my_agents'));
     }
 }
示例#20
0
	function SaveMail(&$content, MailAccount $account, $uidl, $state = 0, $imap_folder_name = '') {
		
		try {
			DB::beginWork();
			
			if (strpos($content, '+OK ') > 0) $content = substr($content, strpos($content, '+OK '));
			self::parseMail($content, $decoded, $parsedMail, $warnings);
			$encoding = array_var($parsedMail,'Encoding', 'UTF-8');
			$enc_conv = EncodingConverter::instance();
			$to_addresses = self::getAddresses(array_var($parsedMail, "To"));
			$from = self::getAddresses(array_var($parsedMail, "From"));
			
			$message_id = self::getHeaderValueFromContent($content, "Message-ID");
			$in_reply_to_id = self::getHeaderValueFromContent($content, "In-Reply-To");
			
			$uid = trim($uidl);
			if (str_starts_with($uid, '<') && str_ends_with($uid, '>')) {
				$uid = utf8_substr($uid, 1, utf8_strlen($uid, $encoding) - 2, $encoding);
			}
			if ($uid == '') {
				$uid = trim($message_id);
				if ($uid == '') {
					$uid = array_var($parsedMail, 'Subject', 'MISSING UID');
				}
				if (str_starts_with($uid, '<') && str_ends_with($uid, '>')) {
					$uid = utf8_substr($uid, 1, utf8_strlen($uid, $encoding) - 2, $encoding);
				}
			}
			// do not save duplicate emails
			if (MailContents::mailRecordExists($account->getId(), $uid, $imap_folder_name == '' ? null : $imap_folder_name)) {
				return;
			}
			
			if (!$from) {
				$parsedMail["From"] = self::getFromAddressFromContent($content);
				$from = array_var($parsedMail["From"][0], 'address', '');
			}
			
			if (defined('EMAIL_MESSAGEID_CONTROL') && EMAIL_MESSAGEID_CONTROL) {
				if (trim($message_id) != "") {
					$id_condition = " AND `message_id`='".trim($message_id)."'";
				} else {
					$id_condition = " AND `name`='". trim(array_var($parsedMail, 'Subject')) ."' AND `from`='$from'";
					if (array_var($parsedMail, 'Date')) {
						$sent_date_dt = new DateTimeValue(strtotime(array_var($parsedMail, 'Date')));
						$sent_date_str = $sent_date_dt->toMySQL();
						$id_condition .= " AND `sent_date`='".$sent_date_str."'";
					}
				}
				$same = MailContents::findOne(array('conditions' => "`account_id`=".$account->getId() . $id_condition, 'include_trashed' => true));
				if ($same instanceof MailContent) return;
			}
			
			$from_spam_junk_folder = strpos(strtolower($imap_folder_name), 'spam') !== FALSE 
				|| strpos(strtolower($imap_folder_name), 'junk')  !== FALSE
				|| strpos(strtolower($imap_folder_name), 'trash') !== FALSE;
			
			$user_id = logged_user() instanceof Contact ? logged_user()->getId() : $account->getContactId();
			$max_spam_level = user_config_option('max_spam_level', null, $user_id);
			if ($max_spam_level < 0) $max_spam_level = 0;
			$mail_spam_level = strlen(trim( array_var($decoded[0]['Headers'], 'x-spam-level:', '') ));
			// if max_spam_level >= 10 then nothing goes to junk folder
			$spam_in_subject = false;
			if (config_option('check_spam_in_subject')) {
				$spam_in_subject = strpos_utf(strtoupper(array_var($parsedMail, 'Subject')), "**SPAM**") !== false;
			}
			if (($max_spam_level < 10 && ($mail_spam_level > $max_spam_level || $from_spam_junk_folder)) || $spam_in_subject) {
				$state = 4; // send to Junk folder
			}
	                
			//if you are in the table spam MailSpamFilters
			$spam_email = MailSpamFilters::getFrom($account->getId(),$from);
			if($spam_email) {
				$state = 0;
				if($spam_email[0]->getSpamState() == "spam") {
					$state = 4;
				}
			} else {
				if ($state == 0) {
					if ($from == $account->getEmailAddress()) {
						if (strpos($to_addresses, $from) !== FALSE) $state = 5; //Show in inbox and sent folders
						else $state = 1; //Show only in sent folder
					}
				}
			}
	
			if (!isset($parsedMail['Subject'])) $parsedMail['Subject'] = '';
			$mail = new MailContent();
			$mail->setAccountId($account->getId());
			$mail->setState($state);
			$mail->setImapFolderName($imap_folder_name);
			$mail->setFrom($from);
			$cc = trim(self::getAddresses(array_var($parsedMail, "Cc")));
			if ($cc == '' && array_var($decoded, 0) && array_var($decoded[0], 'Headers')) {
				$cc = array_var($decoded[0]['Headers'], 'cc:', '');
			}
			$mail->setCc($cc);
			
			$from_name = trim(array_var(array_var(array_var($parsedMail, 'From'), 0), 'name'));		
			$from_encoding = detect_encoding($from_name);	
				
			if ($from_name == ''){
				$from_name = $from;
			} else if (strtoupper($encoding) =='KOI8-R' || strtoupper($encoding) =='CP866' || $from_encoding != 'UTF-8' || !$enc_conv->isUtf8RegExp($from_name)){ //KOI8-R and CP866 are Russian encodings which PHP does not detect
				$utf8_from = $enc_conv->convert($encoding, 'UTF-8', $from_name);
	
				if ($enc_conv->hasError()) {
					$utf8_from = utf8_encode($from_name);
				}
				$utf8_from = utf8_safe($utf8_from);
				$mail->setFromName($utf8_from);
			} else {
				$mail->setFromName($from_name);
			}
			
			$subject_aux = $parsedMail['Subject'];
			$subject_encoding = detect_encoding($subject_aux);
			
			if (strtoupper($encoding) =='KOI8-R' || strtoupper($encoding) =='CP866' || $subject_encoding != 'UTF-8' || !$enc_conv->isUtf8RegExp($subject_aux)){ //KOI8-R and CP866 are Russian encodings which PHP does not detect
				$utf8_subject = $enc_conv->convert($encoding, 'UTF-8', $subject_aux);
				
				if ($enc_conv->hasError()) {
					$utf8_subject = utf8_encode($subject_aux);
				}
				$utf8_subject = utf8_safe($utf8_subject);
				$mail->setSubject($utf8_subject);
			} else {
				$utf8_subject = utf8_safe($subject_aux);
				$mail->setSubject($utf8_subject);
			}
			$mail->setTo($to_addresses);
			$sent_timestamp = false;
			if (array_key_exists("Date", $parsedMail)) {
				$sent_timestamp = strtotime($parsedMail["Date"]);
			}
			if ($sent_timestamp === false || $sent_timestamp === -1 || $sent_timestamp === 0) {
				$mail->setSentDate(DateTimeValueLib::now());
			} else {
				$mail->setSentDate(new DateTimeValue($sent_timestamp));
			}
			
			// if this constant is defined, mails older than this date will not be fetched 
			if (defined('FIRST_MAIL_DATE')) {
				$first_mail_date = DateTimeValueLib::makeFromString(FIRST_MAIL_DATE);
				if ($mail->getSentDate()->getTimestamp() < $first_mail_date->getTimestamp()) {
					// return true to stop getting older mails from the server
					return true;
				}
			}
			
			$received_timestamp = false;
			if (array_key_exists("Received", $parsedMail) && $parsedMail["Received"]) {
				$received_timestamp = strtotime($parsedMail["Received"]);
			}
			if ($received_timestamp === false || $received_timestamp === -1 || $received_timestamp === 0) {
				$mail->setReceivedDate($mail->getSentDate());
			} else {
				$mail->setReceivedDate(new DateTimeValue($received_timestamp));
				if ($state == 5 && $mail->getSentDate()->getTimestamp() > $received_timestamp)
					$mail->setReceivedDate($mail->getSentDate());
			}
			$mail->setSize(strlen($content));
			$mail->setHasAttachments(!empty($parsedMail["Attachments"]));
			$mail->setCreatedOn(new DateTimeValue(time()));
			$mail->setCreatedById($account->getContactId());
			$mail->setAccountEmail($account->getEmail());
			
			$mail->setMessageId($message_id);
			$mail->setInReplyToId($in_reply_to_id);
	
			$mail->setUid($uid);
			$type = array_var($parsedMail, 'Type', 'text');
			
			switch($type) {
				case 'html':
					$utf8_body = $enc_conv->convert($encoding, 'UTF-8', array_var($parsedMail, 'Data', ''));
					//Solve bad syntax styles outlook if it exists
					if(substr_count($utf8_body, "<style>") != substr_count($utf8_body, "</style>") && substr_count($utf8_body, "/* Font Definitions */") >= 1) {
						$p1 = strpos($utf8_body, "/* Font Definitions */", 0);
						$utf8_body1 = substr($utf8_body, 0, $p1);
						$p0 = strrpos($utf8_body1, "</style>");
						$html_content = ($p0 >= 0 ? substr($utf8_body1, 0, $p0) : $utf8_body1) . substr($utf8_body, $p1);
						
						$utf8_body = str_replace_first("/* Font Definitions */","<style>", $utf8_body);
					}
					if ($enc_conv->hasError()) $utf8_body = utf8_encode(array_var($parsedMail, 'Data', ''));
					$utf8_body = utf8_safe($utf8_body);
					$mail->setBodyHtml($utf8_body);
					break;
				case 'text': 
					$utf8_body = $enc_conv->convert($encoding, 'UTF-8', array_var($parsedMail, 'Data', ''));
					if ($enc_conv->hasError()) $utf8_body = utf8_encode(array_var($parsedMail, 'Data', ''));
					$utf8_body = utf8_safe($utf8_body);
					$mail->setBodyPlain($utf8_body);
					break;
				case 'delivery-status': 
					$utf8_body = $enc_conv->convert($encoding, 'UTF-8', array_var($parsedMail, 'Response', ''));
					if ($enc_conv->hasError()) $utf8_body = utf8_encode(array_var($parsedMail, 'Response', ''));
					$utf8_body = utf8_safe($utf8_body);
					$mail->setBodyPlain($utf8_body);
					break;
				default: 
					if (array_var($parsedMail, 'FileDisposition') == 'inline') {
						$attachs = array_var($parsedMail, 'Attachments', array());
						$attached_body = "";
						foreach ($attachs as $k => $attach) {
							if (array_var($attach, 'Type') == 'html' || array_var($attach, 'Type') == 'text') {
								$attached_body .= $enc_conv->convert(array_var($attach, 'Encoding'), 'UTF-8', array_var($attach, 'Data'));
							}
						}
						$mail->setBodyHtml($attached_body);
					} else if (isset($parsedMail['FileName'])) {
						// content-type is a file type => set as it has attachments, they will be parsed when viewing email
						$mail->setHasAttachments(true);
					}
					break;
			}
				
			if (isset($parsedMail['Alternative'])) {
				foreach ($parsedMail['Alternative'] as $alt) {
					if ($alt['Type'] == 'html' || $alt['Type'] == 'text') {
						$body = $enc_conv->convert(array_var($alt,'Encoding','UTF-8'),'UTF-8', array_var($alt, 'Data', ''));
						if ($enc_conv->hasError()) $body = utf8_encode(array_var($alt, 'Data', ''));
						
						// remove large white spaces
						$exploded = preg_split("/[\s]+/", $body, -1, PREG_SPLIT_NO_EMPTY);
						$body = implode(" ", $exploded);
						// remove html comments
						$body = preg_replace('/<!--.*-->/i', '', $body);
					}
					$body = utf8_safe($body);
					if ($alt['Type'] == 'html') {
						$mail->setBodyHtml($body);
					} else if ($alt['Type'] == 'text') {
						$plain = html_to_text(html_entity_decode($body, null, "UTF-8"));
						$mail->setBodyPlain($plain);
					}
					// other alternative parts (like images) are not saved in database.
				}
			}
	
			$repository_id = self::SaveContentToFilesystem($mail->getUid(), $content);
			$mail->setContentFileId($repository_id);
			
			
			if ($in_reply_to_id != "") {
				if ($message_id != "") {
					$conv_mail = MailContents::findOne(array("conditions" => "`account_id`=".$account->getId()." AND `in_reply_to_id` = '$message_id'"));
					if (!$conv_mail) {
						$conv_mail = MailContents::findOne(array("conditions" => "`account_id`=".$account->getId()." AND `message_id` = '$in_reply_to_id'"));
					} else {
						// Search for other discontinued conversation part to link it
						$other_conv_emails = MailContents::findAll(array("conditions" => "`account_id`=".$account->getId()." AND `message_id` = '$in_reply_to_id' AND `conversation_id`<>".$conv_mail->getConversationId()));
					}
				} else {
					$conv_mail = MailContents::findOne(array("conditions" => "`account_id`=".$account->getId()." AND `message_id` = '$in_reply_to_id'"));
				}
				
				if ($conv_mail instanceof MailContent) {// Remove "Re: ", "Fwd: ", etc to compare the subjects
					$conv_original_subject = strtolower($conv_mail->getSubject());
					if (($pos = strrpos($conv_original_subject, ":")) !== false) {
						$conv_original_subject = trim(substr($conv_original_subject, $pos+1));
					}
				}
				if ($conv_mail instanceof MailContent && $conv_original_subject != "" && strpos(strtolower($mail->getSubject()), strtolower($conv_original_subject)) !== false) {
					$mail->setConversationId($conv_mail->getConversationId());
					if (isset($other_conv_emails) && is_array($other_conv_emails)) {
						foreach ($other_conv_emails as $ocm) {
							$ocm->setConversationId($conv_mail->getConversationId());
							$ocm->save();
						}
					}
				} else {
					$conv_id = MailContents::getNextConversationId($account->getId());
					$mail->setConversationId($conv_id);
				}
			} else {
				$conv_id = MailContents::getNextConversationId($account->getId());
				$mail->setConversationId($conv_id);
			}
			
			$mail->save();

			
			// CLASSIFY RECEIVED MAIL WITH THE CONVERSATION
			$member_ids = array();
			if (user_config_option('classify_mail_with_conversation', null, $account->getContactId()) && isset($conv_mail) && $conv_mail instanceof MailContent) {
				$member_ids = array_merge($member_ids, $conv_mail->getMemberIds());
			}
			
			// CLASSIFY MAILS IF THE ACCOUNT HAS A DIMENSION MEMBER
			$account_owner = Contacts::findById($account->getContactId());
			if ($account->getMemberId() != 0) {
				$member = $account->getMember() ;
				if ($member && $member instanceof Member ) {
					$member_ids[] = $member->getId();
			 	}
			}
			
			if (count($member_ids) > 0) {
				$ctrl = new ObjectController();
				$ctrl->add_to_members($mail, $member_ids, $account_owner);
				$mail_controller = new MailController();
				$mail_controller->do_classify_mail($mail, $member_ids);
			}
		
			$user = Contacts::findById($account->getContactId());
			if ($user instanceof Contact) {
				$mail->subscribeUser($user);
			}
			$mail->addToSharingTable();
                        
			// to apply email rules
			$null = null;
			Hook::fire('after_mail_download', $mail, $null);
			
			DB::commit();
		} catch(Exception $e) {
			$ret = null;
			Hook::fire('on_save_mail_error', array('content' => $content, 'account' => $account, 'exception' => $e), $ret);
			
			Logger::log($e->__toString());
			DB::rollback();
			if (FileRepository::isInRepository($repository_id)) {
				FileRepository::deleteFile($repository_id);
			}
			if (strpos($e->getMessage(), "Query failed with message 'Got a packet bigger than 'max_allowed_packet' bytes'") === false) {
				throw $e;
			}
		}
		unset($parsedMail);
		return false;
	}