function clearContentFile() {
		if ($this->getContentFileId() != '') {
			try {
				FileRepository::deleteFile($this->getContentFileId());
			} catch (Exception $e) {
				//Logger::log($e->getMessage());
			}
		}
	}
 /**
  * Delete from DB and from the disk
  *
  * @param void
  * @return boolean
  */
 function delete()
 {
     if ($this->getTypeString() == 'sprd') {
         try {
             $bookId = $this->getFileContent();
             ob_start();
             include_once ROOT . "/" . PUBLIC_FOLDER . "/assets/javascript/gelSheet/php/config/settings.php";
             include_once ROOT . "/" . PUBLIC_FOLDER . "/assets/javascript/gelSheet/php/util/db_functions.php";
             //include_once ROOT . "/" . PUBLIC_FOLDER . "/assets/javascript/gelSheet/php/util/lang/languages.php";
             include_once ROOT . "/" . PUBLIC_FOLDER . "/assets/javascript/gelSheet/php/controller/BookController.class.php";
             $bc = new BookController();
             $bc->deleteBook($bookId);
             ob_end_clean();
         } catch (Error $e) {
         }
     }
     try {
         FileRepository::deleteFile($this->getRepositoryId());
     } catch (Exception $ex) {
         Logger::log($ex->getMessage());
     }
     $this->deleteThumb(false);
     return parent::delete();
 }
 /**
  * Add revision
  *
  * @access public
  * @param void
  * @return null
  */
 function add_revision()
 {
     $this->setTemplate('add_revision');
     $file = ProjectFiles::findById(get_id());
     if (!$file instanceof ProjectFile) {
         flash_error(lang('file dnx'));
         $this->redirectToReferer(get_url('files'));
     }
     // if
     if (!$file->canEdit(logged_user())) {
         flash_error(lang('no access permissions'));
         $this->redirectToReferer(get_url('files'));
     }
     // if
     $file_data = array_var($_POST, 'file');
     $revision_data = array_var($_POST, 'revision');
     tpl_assign('file', $file);
     tpl_assign('file_data', $file_data);
     tpl_assign('revision_data', $revision_data);
     if (is_array($revision_data)) {
         try {
             DB::beginWork();
             $uploaded_file = array_var($_FILES, 'file_file');
             //$file->setFilename(array_var($uploaded_file, 'name'));
             //$file->save();
             $revision = $file->handleUploadedFile($uploaded_file, true);
             // handle uploaded file
             $revision->setComment(array_var($revision_data, 'comment'));
             $revision->save();
             ApplicationLogs::createLog($file, active_project(), ApplicationLogs::ACTION_ADD);
             DB::commit();
             flash_success(lang('success add revision', $revision->getFilename()));
             $this->redirectToUrl($file->getDetailsUrl());
         } catch (Exception $e) {
             DB::rollback();
             tpl_assign('error', $e);
             tpl_assign('file', new ProjectFile());
             // reset file
             // If we uploaded the file remove it from repository
             if (isset($revision) && $revision instanceof ProjectFileRevision && FileRepository::isInRepository($revision->getRepositoryId())) {
                 FileRepository::deleteFile($revision->getRepositoryId());
             }
             // if
         }
         // try
     }
     // if
 }
 function delete($condition)
 {
     if (isset($this) && instance_of($this, 'MailContents')) {
         // Delete contents from filesystem
         $sql = "SELECT `content_file_id` FROM " . self::instance()->getTableName(true) . " WHERE {$condition}";
         $rows = DB::executeAll($sql);
         if (is_array($rows)) {
             $count = 0;
             $err = 0;
             foreach ($rows as $row) {
                 if (isset($row['content_file_id']) && $row['content_file_id'] != '') {
                     try {
                         FileRepository::deleteFile($row['content_file_id']);
                         $count++;
                     } catch (Exception $e) {
                         $err++;
                         //Logger::log($e->getMessage());
                     }
                 }
             }
         }
         return parent::delete($condition);
     } else {
         return MailContents::instance()->delete($condition);
     }
 }
 function SaveMail(&$content, MailAccount $account, $uidl, $state = 0, $imap_folder_name = '')
 {
     if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) {
         self::log_connection_status();
         Logger::log("UID: {$uidl}");
     }
     if (!mysql_ping(DB::connection()->getLink())) {
         DB::connection()->reconnect();
         Logger::log("*** Connection Lost -> Reconnected ***");
     }
     if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) {
         Logger::log("mem  1) " . format_filesize(memory_get_usage()));
     }
     if (strpos($content, '+OK ') > 0) {
         $content = substr($content, strpos($content, '+OK '));
     }
     if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) {
         Logger::log("mem  2) " . format_filesize(memory_get_usage()));
     }
     self::parseMail($content, $decoded, $parsedMail, $warnings);
     if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) {
         Logger::log("mem  3) " . format_filesize(memory_get_usage()));
     }
     $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");
     if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) {
         Logger::log("mem  4) " . format_filesize(memory_get_usage()));
     }
     $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);
         }
         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('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) {
             Logger::log("mem  4.1) " . format_filesize(memory_get_usage()));
         }
     }
     if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) {
         Logger::log("mem  5) " . format_filesize(memory_get_usage()));
     }
     if (defined('EMAIL_MESSAGEID_CONTROL') && EMAIL_MESSAGEID_CONTROL) {
         if (trim($message_id) != "") {
             $id_condition = " AND `message_id`='" . trim($message_id) . "'";
         } else {
             $id_condition = " AND `subject`='" . 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;
         }
     }
     if ($state == 0) {
         if ($from == $account->getEmailAddress()) {
             if (strpos($to_addresses, $from) !== FALSE) {
                 $state = 5;
             } else {
                 $state = 1;
             }
             //Show only in sent folder
         }
     }
     if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) {
         Logger::log("mem  6) " . format_filesize(memory_get_usage()));
         self::log_connection_status();
     }
     $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 User ? logged_user()->getId() : $account->getUserId();
     if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) {
         self::log_connection_status();
     }
     $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 (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) {
         Logger::log("mem  7) " . format_filesize(memory_get_usage()));
         self::log_connection_status();
     }
     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:', '');
     }
     if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) {
         self::log_connection_status();
         Logger::log("mem  8) " . format_filesize(memory_get_usage()));
     }
     $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);
     }
     if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) {
         self::log_connection_status();
         Logger::log("mem  9) " . format_filesize(memory_get_usage()));
     }
     $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());
         }
     }
     if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) {
         self::log_connection_status();
         Logger::log("mem 10) " . format_filesize(memory_get_usage()));
     }
     $mail->setSize(strlen($content));
     $mail->setHasAttachments(!empty($parsedMail["Attachments"]));
     $mail->setCreatedOn(new DateTimeValue(time()));
     $mail->setCreatedById($account->getUserId());
     $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', ''));
             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:
             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($utf8_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 (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) {
         self::log_connection_status();
         Logger::log("mem 11) " . format_filesize(memory_get_usage()));
     }
     try {
         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 && 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);
         }
         if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) {
             self::log_connection_status();
             Logger::log("mem 12) " . format_filesize(memory_get_usage()));
         }
         $mail->save();
         if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) {
             self::log_connection_status();
             Logger::log("mem 13) " . format_filesize(memory_get_usage()));
         }
         // CLASSIFY RECEIVED MAIL WITH THE CONVERSATION
         if (user_config_option('classify_mail_with_conversation', null, $account->getUserId()) && isset($conv_mail) && $conv_mail instanceof MailContent) {
             $wss = $conv_mail->getWorkspaces();
             foreach ($wss as $ws) {
                 $acc_user = Users::findById($account->getUserId());
                 if ($acc_user instanceof User && $acc_user->hasProjectPermission($ws, ProjectUsers::CAN_READ_MAILS)) {
                     $mail->addToWorkspace($ws);
                 }
             }
         }
         // CLASSIFY MAILS IF THE ACCOUNT HAS A WORKSPACE
         if ($account->getColumnValue('workspace', 0) != 0) {
             $workspace = Projects::findById($account->getColumnValue('workspace', 0));
             if ($workspace && $workspace instanceof Project && !$mail->hasWorkspace($workspace)) {
                 $mail->addToWorkspace($workspace);
             }
         }
         //END CLASSIFY
         $user = Users::findById($account->getUserId());
         if ($user instanceof User) {
             $mail->subscribeUser($user);
         }
     } catch (Exception $e) {
         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);
     if (defined('DEBUG_EMAIL_RETRIEVAL') && DEBUG_EMAIL_RETRIEVAL) {
         Logger::log("mem fin) " . format_filesize(memory_get_usage()));
         self::log_connection_status();
     }
     return false;
 }
 /**
  * Delete picture
  *
  * @param void
  * @return null
  */
 function deletePicture()
 {
     if ($this->hasPicture()) {
         FileRepository::deleteFile($this->getPictureFile());
         $this->setPictureFile('');
     }
     // if
 }
 function send_outbox_mails()
 {
     session_commit();
     set_time_limit(0);
     $utils = new MailUtilities();
     if (!array_var($_GET, 'acc_id')) {
         $userAccounts = MailAccounts::getMailAccountsByUser(logged_user());
     } else {
         $account = MailAccounts::findById(array_var($_GET, 'acc_id'));
         $userAccounts = array($account);
     }
     $old_memory_limit = ini_get('memory_limit');
     if (php_config_value_to_bytes($old_memory_limit) < 256 * 1024 * 1024) {
         ini_set('memory_limit', '256M');
     }
     foreach ($userAccounts as $account) {
         $accountUser = null;
         if (logged_user() instanceof User) {
             $accountUser = MailAccountUsers::getByAccountAndUser($account, logged_user());
         }
         if (!$account || !$accountUser) {
             flash_error(lang('no access permissions'));
             ajx_current("empty");
             return;
         }
         $errorMailId = 0;
         try {
             $mails = MailContents::findAll(array("conditions" => array("`is_deleted`=0 AND `state` >= 200 AND `account_id` = ? AND `created_by_id` = ?", $account->getId(), $accountUser->getUserId()), "order" => "`state` ASC"));
             $count = 0;
             foreach ($mails as $mail) {
                 // Only send mails with pair status
                 if ($mail->getState() % 2 == 1) {
                     continue;
                 }
                 // Set impair status, to avoid sending it again when sending it in parallel
                 if (!$mail->addToStatus(1)) {
                     continue;
                 }
                 try {
                     $errorMailId = $mail->getId();
                     $to = $mail->getTo();
                     $from = array($account->getEmailAddress() => $account->getFromName());
                     $subject = $mail->getSubject();
                     $body = $mail->getBodyHtml() != '' ? $mail->getBodyHtml() : $mail->getBodyPlain();
                     $cc = $mail->getCc();
                     $bcc = $mail->getBcc();
                     $type = $mail->getBodyHtml() != '' ? 'text/html' : 'text/plain';
                     $msg_id = $mail->getMessageId();
                     $in_reply_to_id = $mail->getInReplyToId();
                     $attachments = self::readAttachmentsFromFileSystem($mail, $att_version);
                     if ($mail->getBodyHtml() != '') {
                         $images = get_image_paths($body);
                     } else {
                         $images = null;
                     }
                     $mail->setSentDate(DateTimeValueLib::now());
                     $mail->setReceivedDate(DateTimeValueLib::now());
                     if (defined('DEBUG') && DEBUG) {
                         file_put_contents(ROOT . "/cache/log_mails.txt", gmdate("d-m-Y H:i:s") . " antes de enviar: " . $mail->getId() . "\n", FILE_APPEND);
                     }
                     $sentOK = $utils->sendMail($account->getSmtpServer(), $to, $from, $subject, $body, $cc, $bcc, $attachments, $account->getSmtpPort(), $account->smtpUsername(), $account->smtpPassword(), $type, $account->getOutgoingTrasnportType(), $msg_id, $in_reply_to_id, $images, $complete_mail, $att_version);
                 } catch (Exception $e) {
                     // actions are taken below depending on the sentOK variable
                     Logger::log("Could not send email: " . $e->getMessage() . "\nmail_id=" . $mail->getId());
                     $sentOK = false;
                 }
                 try {
                     if ($sentOK) {
                         DB::beginWork();
                         $mail->setState(3);
                         $mail->save();
                         DB::commit();
                     } else {
                         Logger::log("Swift returned sentOK = false after sending email\nmail_id=" . $mail->getId());
                         // set status to a higher and pair value, to retry later.
                         if (!$mail->addToStatus(1)) {
                             Logger::log("Swift could not send the email and the state could not be set to retry later.\nmail_id=" . $mail->getId());
                         }
                     }
                 } catch (Exception $e) {
                     Logger::log("Exception marking email as sent: " . $e->getMessage() . "\nmail_id=" . $mail->getId());
                     if ($sentOK) {
                         DB::rollback();
                     }
                 }
                 if (defined('DEBUG') && DEBUG) {
                     file_put_contents(ROOT . "/cache/log_mails.txt", gmdate("d-m-Y H:i:s") . " despues de enviar: " . $mail->getId() . "\n", FILE_APPEND);
                 }
                 try {
                     //if user selected the option to keep a copy of sent mails on the server
                     if ($sentOK && config_option("sent_mails_sync") && $account->getSyncServer() != null && $account->getSyncSsl() != null && $account->getSyncSslPort() != null && $account->getSyncFolder() != null && $account->getSyncAddr() != null && $account->getSyncPass() != null) {
                         $check_sync_box = MailUtilities::checkSyncMailbox($account->getSyncServer(), $account->getSyncSsl(), $account->getOutgoingTrasnportType(), $account->getSyncSslPort(), $account->getSyncFolder(), $account->getSyncAddr(), $account->getSyncPass());
                         if ($check_sync_box) {
                             MailUtilities::sendToServerThroughIMAP($account->getSyncServer(), $account->getSyncSsl(), $account->getOutgoingTrasnportType(), $account->getSyncSslPort(), $account->getSyncFolder(), $account->getSyncAddr(), $account->getSyncPass(), $complete_mail);
                         }
                     }
                 } catch (Exception $e) {
                     Logger::log("Could not save sent mail in server through imap: " . $e->getMessage() . "\nmail_id=" . $mail->getId());
                 }
                 if (defined('DEBUG') && DEBUG) {
                     file_put_contents(ROOT . "/cache/log_mails.txt", gmdate("d-m-Y H:i:s") . " antes de try: " . $mail->getId() . "\n", FILE_APPEND);
                 }
                 try {
                     if ($sentOK) {
                         if (defined('DEBUG') && DEBUG) {
                             file_put_contents(ROOT . "/cache/log_mails.txt", gmdate("d-m-Y H:i:s") . " sentOK=true: " . $mail->getId() . "\n", FILE_APPEND);
                         }
                         if (FileRepository::isInRepository($mail->getContentFileId())) {
                             if ($att_version >= 2) {
                                 // delete attachments from repository
                                 foreach ($attachments as $att) {
                                     if (FileRepository::isInRepository($att['repo_id'])) {
                                         FileRepository::deleteFile($att['repo_id']);
                                     }
                                 }
                                 if (is_file($att['path'])) {
                                     @unlink($att['path']);
                                 }
                                 // if file was copied to tmp -> delete it
                                 if (defined('DEBUG') && DEBUG) {
                                     file_put_contents(ROOT . "/cache/log_mails.txt", gmdate("d-m-Y H:i:s") . " deleted attachments: " . $mail->getId() . "\n", FILE_APPEND);
                                 }
                             }
                             FileRepository::deleteFile($mail->getContentFileId());
                             if (defined('DEBUG') && DEBUG) {
                                 file_put_contents(ROOT . "/cache/log_mails.txt", gmdate("d-m-Y H:i:s") . " deleted att list: " . $mail->getId() . "\n", FILE_APPEND);
                             }
                         }
                     }
                 } catch (Exception $e) {
                     Logger::log("Exception deleting tmp repository files (attachment list): " . $e->getMessage() . "\nmail_id=" . $mail->getId());
                 }
                 try {
                     DB::beginWork();
                     if ($sentOK) {
                         $content = $complete_mail;
                         $repository_id = $utils->saveContent($content);
                         if (defined('DEBUG') && DEBUG) {
                             file_put_contents(ROOT . "/cache/log_mails.txt", gmdate("d-m-Y H:i:s") . " content saved: " . $mail->getId() . "\n", FILE_APPEND);
                         }
                         $mail->setContentFileId($repository_id);
                         $mail->setSize(strlen($content));
                         if (config_option("sent_mails_sync") && isset($check_sync_box) && $check_sync_box) {
                             $mail->setSync(true);
                         }
                         $mail->save();
                         if (defined('DEBUG') && DEBUG) {
                             file_put_contents(ROOT . "/cache/log_mails.txt", gmdate("d-m-Y H:i:s") . " email saved: " . $mail->getId() . "\n", FILE_APPEND);
                         }
                         $properties = array("id" => $mail->getId());
                         evt_add("mail sent", $properties);
                         $count++;
                     }
                     DB::commit();
                 } catch (Exception $e) {
                     DB::rollback();
                     Logger::log("Exception deleting tmp repository files (attachment list): " . $e->getMessage() . "\nmail_id=" . $mail->getId());
                 }
             }
             if ($count > 0) {
                 evt_add("mails sent", $count);
             }
         } catch (Exception $e) {
             $errorEmailUrl = '';
             if ($errorMailId > 0) {
                 $email = MailContents::findById($errorMailId);
                 if ($email instanceof MailContent) {
                     Logger::log("failed to send mail: " . $e->getMessage() . "\n" . $email->getEditUrl());
                     Logger::log($e->getTraceAsString());
                     $errorEmailUrl = $email->getEditUrl();
                 }
             }
             flash_error($errorEmailUrl != '' ? $e->getMessage() : $e->getMessage());
             ajx_current("empty");
         }
     }
     ini_set('memory_limit', $old_memory_limit);
     ajx_current("empty");
 }
	function save_spreadsheet() {
		if (logged_user()->isGuest()) {
			flash_error(lang('no access permissions'));
			ajx_current("empty");
			return;
		}
		ajx_current("empty");
		$id = get_id();
		$file_content = array_var($_GET, "book");
		$name = trim(array_var($_GET, 'name', ''));
		if ($id > 0) {
			//edit spreadsheet
			if ($name == '') $name = $file->getFilename();
			try {
				$file = ProjectFiles::findById(get_id());
				if (!$file->canEdit(logged_user())) {
					flash_error(lang('no access permissions'));
					ajx_current("empty");
					return;
				} // if
				DB::beginWork();
				$file->setFilename($name);
				$post_revision = true;
				$revision_comment = '';

				$file_dt['name'] = $name;
				$file_dt['size'] = strlen($file_content);
				$file_dt['type'] = 'sprd';
				$file_dt['tmp_name'] = ROOT . '/tmp/' . rand () ;
				$handler = fopen($file_dt['tmp_name'], 'w');
				fputs($handler, $file_content);
				fclose($handler);
				$file->save();
				$file->handleUploadedFile($file_dt, $post_revision, $revision_comment);
				
				ApplicationLogs::createLog($file, ApplicationLogs::ACTION_EDIT);
				
				DB::commit();
				unlink($file_dt['tmp_name']);

				flash_success(lang('success save file', $file->getFilename()));
				ajx_add("overview-panel", "reload");
				ajx_extra_data(array("sprdID" => $file->getId()));
			} catch(Exception $e) {
				DB::rollback();
				unlink($file_dt['tmp_name']);
				tpl_assign('error', $e);
				flash_error(lang('error while saving'));
			} // try
		} else  {
			//new spreadsheet
			if ($name == '') $name = lang('new spreadsheet');
			try {
				if(!ProjectFile::canAdd(logged_user() , active_context())) {
					flash_error(lang('no access permissions'));
					$this->redirectToReferer(get_url('files'));
					return ;
				} // if
	
				// create the file object
				$file = new ProjectFile();
				$file->setFilename($name);
				$file->setIsVisible(true);
	
				//seteo esto para despues setear atributos
				$file_dt['name'] = $name;
				$file_dt['size'] = strlen($file_content);
				$file_dt['type'] = 'sprd';
				$file_dt['tmp_name'] = ROOT . '/tmp/' . rand ();
				$handler = fopen($file_dt['tmp_name'], 'w');
				fputs($handler, $file_content);
				fclose($handler);

				$file->setCreatedOn(new DateTimeValue(time()));
				
				DB::beginWork();

				$file->save();
				$file->subscribeUser(logged_user());
				//FIXME $file->addToWorkspace(active_or_personal_project());
				$revision = $file->handleUploadedFile($file_dt, true); // handle uploaded file
				
				ApplicationLogs::createLog($file, ApplicationLogs::ACTION_ADD);

				DB::commit();
				unlink($file_dt['tmp_name']);
				flash_success(lang('success add file', $file->getFilename()));
				ajx_extra_data(array("sprdID" => $file->getId()));
			} catch(Exception $e) {
				DB::rollback();
					
				tpl_assign('error', $e);
				tpl_assign('file', new ProjectFile()); // reset file
				unlink($file_dt['tmp_name']);
				// if we uploaded the file remove it from repository
				if (isset($revision) && ($revision instanceof ProjectFileRevision) && FileRepository::isInRepository($revision->getRepositoryId())) {
					FileRepository::deleteFile($revision->getRepositoryId());
				} // if
				flash_error(lang('error while saving'));
			} // try
		}//new spreadsheet
	}
 /**
  * Delete from DB and from the disk
  *
  * @param void
  * @return boolean
  */
 function delete()
 {
     FileRepository::deleteFile($this->getRepositoryId());
     $this->deleteThumb(false);
     return parent::delete();
 }
 /**
  * Add file
  *
  * @access public
  * @param void
  * @return null
  */
 function add_file()
 {
     if (!ProjectFile::canAdd(logged_user(), active_project())) {
         flash_error(lang('no access permissions'));
         $this->redirectToReferer(get_url('files'));
     }
     // if
     $file = new ProjectFile();
     $file_data = array_var($_POST, 'file');
     $folder = null;
     $folder_id = get_id('folder_id');
     if ($folder_id) {
         $folder = ProjectFolders::findById($folder_id);
     }
     // if
     if ($folder instanceof ProjectFolder && !is_array($file_data)) {
         $file_data = array('folder_id' => $folder->getId());
         // array
     }
     // if
     tpl_assign('file', $file);
     tpl_assign('file_data', $file_data);
     if (is_array(array_var($_POST, 'file'))) {
         try {
             DB::beginWork();
             $uploaded_file = array_var($_FILES, 'file_file');
             $file->setFromAttributes($file_data);
             if (!logged_user()->isMemberOfOwnerCompany()) {
                 $file->setIsPrivate(false);
                 $file->setIsImportant(false);
                 $file->setCommentsEnabled(true);
                 $file->setAnonymousCommentsEnabled(false);
             }
             // if
             $file->setFilename(array_var($uploaded_file, 'name'));
             $file->setProjectId(active_project()->getId());
             $file->setIsVisible(true);
             $file->save();
             $file->setTagsFromCSV(array_var($file_data, 'tags'));
             $revision = $file->handleUploadedFile($uploaded_file, true);
             // handle uploaded file
             ApplicationLogs::createLog($file, active_project(), ApplicationLogs::ACTION_ADD);
             DB::commit();
             flash_success(lang('success add file', $file->getFilename()));
             $this->redirectToUrl($file->getDetailsUrl());
         } catch (Exception $e) {
             DB::rollback();
             tpl_assign('error', $e);
             tpl_assign('file', new ProjectFile());
             // reset file
             // If we uploaded the file remove it from repository
             if (isset($revision) && $revision instanceof ProjectFileRevision && FileRepository::isInRepository($revision->getRepositoryId())) {
                 FileRepository::deleteFile($revision->getRepositoryId());
             }
             // if
         }
         // try
     }
     // if
 }
 function SaveMail(&$content, MailAccount $account, $uidl, $state = 0, $imap_folder_name = '', $read = null, &$received_count)
 {
     try {
         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) . "' AND `from`='{$from}'";
             } else {
                 $id_condition = " AND `name`= " . DB::escape(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;
         }
         $spam_level_header = 'x-spam-level:';
         foreach ($decoded[0]['Headers'] as $hdr_name => $hdrval) {
             if (strpos(strtolower($hdr_name), "spamscore") !== false || strpos(strtolower($hdr_name), "x-spam-level")) {
                 $spam_level_header = $hdr_name;
                 break;
             }
         }
         $mail_spam_level = strlen(trim(array_var($decoded[0]['Headers'], $spam_level_header, '')));
         // 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
         if ($state != 4) {
             $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 (strtolower($from) == strtolower($account->getEmailAddress())) {
                         if (strpos($to_addresses, $from) !== FALSE) {
                             $state = 5;
                         } 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);
         $subject_multipart_encoding = array_var($parsedMail, 'SubjectEncoding', strtoupper($encoding));
         if ($subject_multipart_encoding != 'UTF-8' && ($subject_multipart_encoding == 'KOI8-R' || $subject_multipart_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($subject_multipart_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->setCreatedOn(new DateTimeValue(time()));
         $mail->setCreatedById($account->getContactId());
         $mail->setAccountEmail($account->getEmail());
         $mail->setMessageId($message_id);
         $mail->setInReplyToId($in_reply_to_id);
         // set hasAttachments=true onlu if there is any attachment with FileDisposition='attachment'
         $has_attachments = false;
         foreach (array_var($parsedMail, "Attachments", array()) as $attachment) {
             if (array_var($attachment, 'FileDisposition') == 'attachment') {
                 $has_attachments = true;
             }
         }
         $mail->setHasAttachments($has_attachments);
         $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);
         // START TRANSACTION
         DB::beginWork();
         // Conversation
         //check if exists a conversation for this mail
         $conv_mail = "";
         if ($in_reply_to_id != "" && $message_id != "") {
             $conv_mail = MailContents::findOne(array("conditions" => "`account_id`=" . $account->getId() . " AND (`message_id` = '{$in_reply_to_id}' OR `in_reply_to_id` = '{$message_id}')"));
             //check if this mail is in two diferent conversations and fixit
             if ($conv_mail) {
                 $other_conv_mail = MailContents::findOne(array("conditions" => "`account_id`=" . $account->getId() . " AND `conversation_id` != " . $conv_mail->getConversationId() . " AND (`message_id` = '{$in_reply_to_id}' OR `in_reply_to_id` = '{$message_id}')"));
                 if ($other_conv_mail) {
                     $other_conv = MailContents::findAll(array("conditions" => "`account_id`=" . $account->getId() . " AND `conversation_id` = " . $other_conv_mail->getConversationId()));
                     if ($other_conv) {
                         foreach ($other_conv as $mail_con) {
                             $mail_con->setConversationId($conv_mail->getConversationId());
                             $mail_con->save();
                         }
                     }
                 }
             }
         } elseif ($in_reply_to_id != "") {
             $conv_mail = MailContents::findOne(array("conditions" => "`account_id`=" . $account->getId() . " AND `message_id` = '{$in_reply_to_id}'"));
         } elseif ($message_id != "") {
             $conv_mail = MailContents::findOne(array("conditions" => "`account_id`=" . $account->getId() . " AND `in_reply_to_id` = '{$message_id}'"));
         }
         if ($conv_mail instanceof MailContent) {
             $conv_id = $conv_mail->getConversationId();
         } else {
             $conv_id = MailContents::getNextConversationId($account->getId());
         }
         $mail->setConversationId($conv_id);
         $mail->save();
         // CLASSIFY RECEIVED MAIL WITH THE CONVERSATION
         $classified_with_conversation = false;
         $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());
             $classified_with_conversation = true;
         }
         // CLASSIFY MAILS IF THE ACCOUNT HAS A DIMENSION MEMBER AND NOT CLASSIFIED WITH CONVERSATION
         $account_owner = Contacts::findById($account->getContactId());
         if ($account->getMemberId() != '' && !$classified_with_conversation) {
             $acc_mem_ids = explode(',', $account->getMemberId());
             foreach ($acc_mem_ids as $acc_mem_id) {
                 $member_ids[] = $acc_mem_id;
             }
         }
         foreach ($member_ids as $k => &$mem_id) {
             if ($mem_id == "") {
                 unset($member_ids[$k]);
             }
         }
         if (count($member_ids) > 0) {
             $members = Members::instance()->findAll(array('conditions' => 'id IN (' . implode(',', $member_ids) . ')'));
             $mail->addToMembers($members, true);
             /*	$ctrl = new ObjectController();
             			$ctrl->add_to_members($mail, $member_ids, $account_owner);*/
             $mail_controller = new MailController();
             $mail_controller->do_classify_mail($mail, $member_ids, null, false, true);
         }
         $user = Contacts::findById($account->getContactId());
         if ($user instanceof Contact) {
             $mail->subscribeUser($user);
         }
         $mail->addToSharingTable();
         $mail->orderConversation();
         //if email is from an imap account copy the state (read/unread) from the server
         if (!is_null($read)) {
             $mail->setIsRead($account->getContactId(), $read);
         }
         // increase received count
         $received_count++;
         // 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;
 }
 function uploadFile($username, $password, $workspaces, $tags, $generate_rev, $filename, $description, $do_checkin, $data)
 {
     $result = array('status' => true, 'errorid' => 0, 'message' => '');
     if ($this->loginUser($username, $password)) {
         try {
             DB::beginWork();
             $file = null;
             $files = ProjectFiles::getAllByFilename($filename, logged_user()->getWorkspacesQuery());
             if (is_array($files) && count($files) > 0) {
                 if ($generate_rev) {
                     $file = ProjectFiles::findById($files[0]->getId());
                     if ($file->isCheckedOut()) {
                         if (!$file->canCheckin(logged_user())) {
                             $result['status'] = false;
                             $result['errorid'] = 1004;
                             $result['message'] = lang('no access permissions');
                         }
                         $file->setCheckedOutById(0);
                     } else {
                         // Check for edit permissions
                         if (!$file->canEdit(logged_user())) {
                             $result['status'] = false;
                             $result['errorid'] = 1004;
                             $result['message'] = lang('no access permissions');
                         }
                     }
                 }
             }
             if ($result['status']) {
                 $enteredWS = Projects::findByCSVIds($workspaces);
                 $validWS = array();
                 foreach ($enteredWS as $ws) {
                     if (ProjectFile::canAdd(logged_user(), $ws)) {
                         $validWS[] = $ws;
                     }
                 }
                 if (count($validWS) == 0) {
                     $result['status'] = false;
                     $result['errorid'] = 1005;
                     $result['message'] = 'Invalid workspaces given. Check access permissions.';
                 } else {
                     $make_revision_comment = $file != null;
                     if ($file == null) {
                         $file = new ProjectFile();
                         $file->setFilename($filename);
                         $file->setIsVisible(true);
                         $file->setIsPrivate(false);
                         $file->setIsImportant(false);
                         $file->setCommentsEnabled(true);
                         $file->setAnonymousCommentsEnabled(false);
                         $file->setCreatedOn(new DateTimeValue(time()));
                         $file->setDescription($description);
                     }
                     $file_dt['name'] = $file->getFilename();
                     $file_dt['size'] = strlen($data);
                     $file_dt['tmp_name'] = ROOT . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR . rand();
                     $extension = trim(get_file_extension($file->getFilename()));
                     $file_dt['type'] = Mime_Types::instance()->get_type($extension);
                     if (!trim($file_dt['type'])) {
                         $file_dt['type'] = 'text/html';
                     }
                     $handle = fopen($file_dt['tmp_name'], "w");
                     fwrite($handle, $data, $file_dt['size']);
                     fclose($handle);
                     $file->save();
                     $revision = $file->handleUploadedFile($file_dt, true, $make_revision_comment ? $description : '');
                     $file->setTagsFromCSV($tags);
                     foreach ($validWS as $w) {
                         $file->addToWorkspace($w);
                     }
                     foreach ($validWS as $w) {
                         ApplicationLogs::createLog($file, $w, ApplicationLogs::ACTION_ADD);
                     }
                     DB::commit();
                     $result['message'] = 'd' . str_pad($file->getId(), 3, '0', STR_PAD_LEFT) . 'r' . $file->getRevisionNumber();
                     if (!$do_checkin) {
                         $this->checkoutFile($username, $password, $file->getId());
                     }
                 }
             }
         } catch (Exception $e) {
             DB::rollback();
             $result['message'] = $e->getMessage();
             $result['errorid'] = 1003;
             $result['status'] = false;
             // If we uploaded the file remove it from repository
             if (isset($revision) && $revision instanceof ProjectFileRevision && FileRepository::isInRepository($revision->getRepositoryId())) {
                 FileRepository::deleteFile($revision->getRepositoryId());
             }
         }
     } else {
         $result['status'] = false;
         $result['errorid'] = 1002;
         $result['message'] = lang('invalid login data');
     }
     return $this->result_to_xml($result, 'result');
 }
 function send_outbox_mails($user = null, $user_account = null, $from_time = null)
 {
     if (is_null($user)) {
         $user = logged_user();
     }
     $from_time_cond = "";
     if (!is_null($from_time) && $from_time instanceof DateTimeValue) {
         $from_time_cond = " AND `created_on` > '" . $from_time->toMySQL() . "'";
     }
     session_commit();
     set_time_limit(0);
     $utils = new MailUtilities();
     if (!is_null($user_account)) {
         $userAccounts = array($user_account);
     } elseif (array_var($_GET, 'acc_id')) {
         $account = MailAccounts::findById(array_var($_GET, 'acc_id'));
         $userAccounts = array($account);
     } else {
         $userAccounts = MailAccounts::getMailAccountsByUser($user);
     }
     $old_memory_limit = ini_get('memory_limit');
     if (php_config_value_to_bytes($old_memory_limit) < 256 * 1024 * 1024) {
         ini_set('memory_limit', '256M');
     }
     foreach ($userAccounts as $account) {
         $accountUser = null;
         if ($user instanceof Contact) {
             $accountUser = MailAccountContacts::getByAccountAndContact($account, $user);
         }
         if (!$account || !$accountUser) {
             flash_error(lang('no access permissions'));
             ajx_current("empty");
             return;
         }
         $errorMailId = 0;
         try {
             $mails = MailContents::findAll(array("conditions" => array("`is_deleted`=0 AND `state` >= 200 AND `account_id` = ? AND `created_by_id` = ? {$from_time_cond}", $account->getId(), $accountUser->getContactId()), "order" => "`state` ASC"));
             $count = 0;
             foreach ($mails as $mail) {
                 /* @var $mail MailContent */
                 if ($mail->getTrashedById() > 0) {
                     continue;
                 }
                 // Only send mails with pair status
                 if ($mail->getState() % 2 == 1) {
                     continue;
                 }
                 //if is archived do not send it
                 if ($mail->isArchived()) {
                     continue;
                 }
                 // Set impair status, to avoid sending it again when sending it in parallel
                 if (!$mail->addToStatus(1)) {
                     continue;
                 }
                 try {
                     $errorMailId = $mail->getId();
                     $to = $mail->getTo();
                     if (!$accountUser instanceof MailAccountContact) {
                         $from = array($account->getEmailAddress() => $account->getFromName());
                     } else {
                         if ($user instanceof Contact && $accountUser->getIsDefault() && $accountUser->getSenderName() == "") {
                             $from = array($account->getEmailAddress() => $user->getObjectName());
                         } else {
                             $from = array($account->getEmailAddress() => $accountUser->getSenderName());
                         }
                     }
                     $subject = $mail->getSubject();
                     $body = $mail->getBodyHtml() != '' ? $mail->getBodyHtml() : $mail->getBodyPlain();
                     $cc = $mail->getCc();
                     $bcc = $mail->getBcc();
                     $type = $mail->getBodyHtml() != '' ? 'text/html' : 'text/plain';
                     $msg_id = $mail->getMessageId();
                     $in_reply_to_id = $mail->getInReplyToId();
                     $attachments = self::readAttachmentsFromFileSystem($mail, $att_version);
                     if ($mail->getBodyHtml() != '') {
                         $images = get_image_paths($body);
                     } else {
                         $images = null;
                     }
                     // Inline images
                     preg_match_all("/<img[^>]*src=[\"'][^\"']*[\"']/", $body, $matches);
                     foreach ($matches as $match) {
                         $pos = strpos($match[0], 'src="');
                         $url = substr($match[0], $pos + 5);
                         $url = substr($url, 0, -1);
                         if (str_starts_with($url, ROOT_URL . "/tmp/")) {
                             $path = str_replace(ROOT_URL, ROOT, $url);
                             if (!is_array($images)) {
                                 $images = array();
                             }
                             $images[$url] = $path;
                         }
                         if (str_starts_with($url, "data:")) {
                             $mime_type = substr($url, 5, strpos($url, ';') - 5);
                             $extension = substr($mime_type, strpos($mime_type, "/") + 1);
                             if (!is_array($images)) {
                                 $images = array();
                             }
                             $file_url = ROOT_URL . "/tmp/" . gen_id() . ".{$extension}";
                             $path = str_replace(ROOT_URL, ROOT, $file_url);
                             $data = substr($url, strpos($url, "base64") + 6);
                             file_put_contents($path, base64_decode($data));
                             $images[$file_url] = $path;
                             $body = str_replace($url, $file_url, $body);
                         }
                     }
                     $mail->setSentDate(DateTimeValueLib::now());
                     $mail->setReceivedDate(DateTimeValueLib::now());
                     if (defined('DEBUG') && DEBUG) {
                         file_put_contents(ROOT . "/cache/log_mails.txt", gmdate("d-m-Y H:i:s") . " antes de enviar: " . $mail->getId() . "\n", FILE_APPEND);
                     }
                     $sentOK = $utils->sendMail($account->getSmtpServer(), $to, $from, $subject, $body, $cc, $bcc, $attachments, $account->getSmtpPort(), $account->smtpUsername(), $account->smtpPassword(), $type, $account->getOutgoingTrasnportType(), $msg_id, $in_reply_to_id, $images, $complete_mail, $att_version);
                     $mail->orderConversation();
                 } catch (Exception $e) {
                     // actions are taken below depending on the sentOK variable
                     Logger::log("Could not send email: " . $e->getMessage() . "\nmail_id=" . $mail->getId());
                     $sentOK = false;
                 }
                 try {
                     if ($sentOK) {
                         DB::beginWork();
                         $mail->setState(3);
                         $mail->save();
                         DB::commit();
                     } else {
                         Logger::log("Swift returned sentOK = false after sending email\nmail_id=" . $mail->getId());
                         // set status to a higher and pair value, to retry later.
                         if (!$mail->addToStatus(1)) {
                             Logger::log("Swift could not send the email and the state could not be set to retry later.\nmail_id=" . $mail->getId());
                         }
                     }
                 } catch (Exception $e) {
                     $extra_exception_info = $sentOK == true ? '(but it has been sent)' : '(and it has NOT been sent)';
                     Logger::log("Exception marking email as sent " . $extra_exception_info . ": " . $e->getMessage() . "\nmail_id=" . $mail->getId());
                     if ($sentOK) {
                         DB::rollback();
                     }
                 }
                 if (defined('DEBUG') && DEBUG) {
                     file_put_contents(ROOT . "/cache/log_mails.txt", gmdate("d-m-Y H:i:s") . " despues de enviar: " . $mail->getId() . "\n", FILE_APPEND);
                 }
                 try {
                     //if user selected the option to keep a copy of sent mails on the server
                     if ($sentOK && config_option("sent_mails_sync") && $account->getSyncServer() != null && $account->getSyncSsl() != null && $account->getSyncSslPort() != null && $account->getSyncFolder() != null && $account->getSyncAddr() != null && $account->getSyncPass() != null) {
                         $check_sync_box = MailUtilities::checkSyncMailbox($account->getSyncServer(), $account->getSyncSsl(), $account->getOutgoingTrasnportType(), $account->getSyncSslPort(), $account->getSyncFolder(), $account->getSyncAddr(), $account->getSyncPass());
                         if ($check_sync_box) {
                             MailUtilities::sendToServerThroughIMAP($account->getSyncServer(), $account->getSyncSsl(), $account->getOutgoingTrasnportType(), $account->getSyncSslPort(), $account->getSyncFolder(), $account->getSyncAddr(), $account->getSyncPass(), $complete_mail);
                         }
                     }
                 } catch (Exception $e) {
                     Logger::log("Could not save sent mail in server through imap: " . $e->getMessage() . "\nmail_id=" . $mail->getId());
                 }
                 if (defined('DEBUG') && DEBUG) {
                     file_put_contents(ROOT . "/cache/log_mails.txt", gmdate("d-m-Y H:i:s") . " antes de try: " . $mail->getId() . "\n", FILE_APPEND);
                 }
                 try {
                     if ($sentOK) {
                         if (defined('DEBUG') && DEBUG) {
                             file_put_contents(ROOT . "/cache/log_mails.txt", gmdate("d-m-Y H:i:s") . " sentOK=true: " . $mail->getId() . "\n", FILE_APPEND);
                         }
                         if (FileRepository::isInRepository($mail->getContentFileId())) {
                             if ($att_version >= 2) {
                                 // delete attachments from repository
                                 foreach ($attachments as $att) {
                                     if (FileRepository::isInRepository($att['repo_id'])) {
                                         FileRepository::deleteFile($att['repo_id']);
                                     }
                                 }
                                 if (isset($att['path']) && is_file($att['path'])) {
                                     @unlink($att['path']);
                                 }
                                 // if file was copied to tmp -> delete it
                                 if (defined('DEBUG') && DEBUG) {
                                     file_put_contents(ROOT . "/cache/log_mails.txt", gmdate("d-m-Y H:i:s") . " deleted attachments: " . $mail->getId() . "\n", FILE_APPEND);
                                 }
                             }
                             FileRepository::deleteFile($mail->getContentFileId());
                             if (defined('DEBUG') && DEBUG) {
                                 file_put_contents(ROOT . "/cache/log_mails.txt", gmdate("d-m-Y H:i:s") . " deleted att list: " . $mail->getId() . "\n", FILE_APPEND);
                             }
                         }
                     } else {
                         if (defined('DEBUG') && DEBUG) {
                             file_put_contents(ROOT . "/cache/log_mails.txt", gmdate("d-m-Y H:i:s") . " sentOK=false: " . $mail->getId() . " - Error when sending mail: SentOK = false \n", FILE_APPEND);
                         }
                     }
                 } catch (Exception $e) {
                     Logger::log("Exception deleting tmp repository files (attachment list): " . $e->getMessage() . "\nmail_id=" . $mail->getId());
                 }
                 try {
                     DB::beginWork();
                     if ($sentOK) {
                         $content = $complete_mail;
                         $repository_id = $utils->saveContent($content);
                         if (defined('DEBUG') && DEBUG) {
                             file_put_contents(ROOT . "/cache/log_mails.txt", gmdate("d-m-Y H:i:s") . " content saved: " . $mail->getId() . "\n", FILE_APPEND);
                         }
                         $mail->setContentFileId($repository_id);
                         $mail->setSize(strlen($content));
                         if (config_option("sent_mails_sync") && isset($check_sync_box) && $check_sync_box) {
                             $mail->setSync(true);
                         }
                         $mail->save();
                         if (defined('DEBUG') && DEBUG) {
                             file_put_contents(ROOT . "/cache/log_mails.txt", gmdate("d-m-Y H:i:s") . " email saved: " . $mail->getId() . "\n", FILE_APPEND);
                         }
                         $properties = array("id" => $mail->getId());
                         evt_add("mail sent", $properties);
                         $count++;
                     }
                     DB::commit();
                 } catch (Exception $e) {
                     DB::rollback();
                     Logger::log("Exception deleting tmp repository files (attachment list): " . $e->getMessage() . "\nmail_id=" . $mail->getId());
                 }
             }
             if ($count > 0) {
                 evt_add("mails sent", $count);
             }
         } catch (Exception $e) {
             $errorEmailUrl = '';
             if ($errorMailId > 0) {
                 $email = MailContents::findById($errorMailId);
                 if ($email instanceof MailContent) {
                     Logger::log("failed to send mail: " . $e->getMessage() . "\n" . $email->getEditUrl());
                     Logger::log($e->getTraceAsString());
                     $errorEmailUrl = $email->getEditUrl();
                 }
             }
             flash_error($errorEmailUrl != '' ? $e->getMessage() : $e->getMessage());
             ajx_current("empty");
         }
     }
     ini_set('memory_limit', $old_memory_limit);
     ajx_current("empty");
 }
Exemple #14
0
 /**
  * Delete avatar
  *
  * @param void
  * @return null
  */
 function deleteAvatar()
 {
     if ($this->hasAvatar()) {
         FileRepository::deleteFile($this->getAvatarFile());
         $this->setAvatarFile('');
     }
     // if
 }
 /**
  * Delete logo
  *
  * @param void
  * @return null
  */
 function deleteLogo()
 {
     if ($this->hasLogo()) {
         FileRepository::deleteFile($this->getLogoFile());
         $this->setLogoFile('');
     }
     // if
 }