public function save() { if (strlen($this->getContent()) > 65535) { // TEXT type has a limit of 65535 $this->setContent(utf8_safe(substr($this->getContent(), 0, 65535))); } if (!(defined('LUCENE_SEARCH') && LUCENE_SEARCH)) { return parent::save(); } else { LuceneDB::AddToIndex($this); parent::save(); } }
function format_value_to_print($col, $value, $type, $obj_type_id, $textWrapper = '', $dateformat = 'Y-m-d') { switch ($type) { case DATA_TYPE_STRING: if (preg_match(EMAIL_FORMAT, strip_tags($value))) { $formatted = strip_tags($value); } else { if ($col == 'is_user') { $formatted = $value == 1 ? lang('yes') : lang('no'); } else { if (strpos($value, "�") !== false) { $value = preg_replace('/\\xA0/s', ' ', $value); } $value = utf8_safe($value); $formatted = $textWrapper . $value . $textWrapper; } } break; case DATA_TYPE_INTEGER: if ($col == 'priority') { switch ($value) { case 100: $formatted = lang('low priority'); break; case 200: $formatted = lang('normal priority'); break; case 300: $formatted = lang('high priority'); break; case 400: $formatted = lang('urgent priority'); break; default: $formatted = clean($value); } } elseif ($col == 'time_estimate') { if ($value > 0) { $formatted = DateTimeValue::FormatTimeDiff(new DateTimeValue(0), new DateTimeValue($value * 60), 'hm', 60); } else { $formatted = clean($value); } } else { $formatted = clean($value); } break; case DATA_TYPE_BOOLEAN: $formatted = $value == 1 ? lang('yes') : lang('no'); break; case DATA_TYPE_DATE: if ($value != 0) { if (str_ends_with($value, "00:00:00")) { $dateformat .= " H:i:s"; } try { $dtVal = DateTimeValueLib::dateFromFormatAndString($dateformat, $value); } catch (Exception $e) { $formatted = $value; } if (!isset($formatted)) { $formatted = format_date($dtVal, null, 0); } } else { $formatted = ''; } break; case DATA_TYPE_DATETIME: if ($value != 0) { try { $dtVal = DateTimeValueLib::dateFromFormatAndString("{$dateformat} H:i:s", $value); } catch (Exception $e) { $formatted = $value; } if ($dtVal instanceof DateTimeValue) { if ($obj_type_id == ProjectEvents::instance()->getObjectTypeId() || $obj_type_id == ProjectTasks::instance()->getObjectTypeId()) { $dtVal->advance(logged_user()->getTimezone() * 3600, true); } if ($obj_type_id == ProjectEvents::instance()->getObjectTypeId() && ($col == 'start' || $col == 'duration')) { $formatted = format_datetime($dtVal); } else { $formatted = format_date($dtVal, null, 0); } } } else { $formatted = ''; } break; default: $formatted = $value; } if ($formatted == '') { $formatted = '--'; } return $formatted; }
$description .= '<tr><td>' . lang('mail CC') . ':</td><td>' . MailUtilities::displayMultipleAddresses(clean($email->getCc())) . '</td></tr>'; } if ($email->getBcc() != '') { $description .= '<tr><td>' . lang('mail BCC') . ':</td><td>' . MailUtilities::displayMultipleAddresses(clean($email->getBcc())) . '</td></tr>'; } $description .= '<tr><td>' . lang('date') . ':</td><td>' . format_datetime($email->getSentDate(), 'l, j F Y - '.$time_format, logged_user()->getTimezone()) . '</td></tr>'; if ($email->getHasAttachments() && is_array($attachments) && count($attachments) > 0) { $description .= '<tr><td colspan=2> <fieldset> <legend class="toggle_collapsed" onclick="og.toggle(\'mv_attachments\',this)">' . lang('attachments') . '</legend> <div id="mv_attachments" style="display:none"> <table>'; foreach($attachments as $att) { if (!array_var($att, 'hide')) { $size = $att['size'];//format_filesize(strlen($att["Data"])); $fName = str_starts_with($att["FileName"], "=?") ? iconv_mime_decode($att["FileName"], 0, "UTF-8") : utf8_safe($att["FileName"]); if (trim($fName) == "" && strlen($att["FileName"]) > 0) $fName = utf8_encode($att["FileName"]); $description .= '<tr><td style="padding-right: 10px">'; $ext = get_file_extension($fName); $fileType = FileTypes::getByExtension($ext); if (isset($fileType)) $icon = $fileType->getIcon(); else $icon = "unknown.png"; $download_url = get_url('mail', 'download_attachment', array('email_id' => $email->getId(), 'attachment_id' => $c)); include_once ROOT . "/library/browser/Browser.php"; if (Browser::instance()->getBrowser() == Browser::BROWSER_IE) { $download_url = "javascript:location.href = '$download_url';"; } $description .= '<img src="' . get_image_url("filetypes/" . $icon) .'"></td> <td><a target="_self" href="' . $download_url . '">' . clean($fName) . " ($size)" . '</a></td></tr>';
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; }
function zip_add() { if (logged_user()->isGuest()) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } ajx_current("empty"); if (!zip_supported()) { flash_error(lang('zip not supported')); return; } $files = ProjectFiles::findByCSVIds(array_var($_GET, 'objects'), '`type` = 0'); if (count($files) == 0) { flash_error(lang('no files to compress')); return; } $isnew = false; $file = null; if (array_var($_GET, 'filename')) { $filename = array_var($_GET, 'filename'); $isnew = true; } else if (array_var($_GET, 'id')) { $file = ProjectFiles::findById(array_var($_GET, 'id')); $filename = $file->getFilename(); } $tmp_zip_path = ROOT.'/tmp/'.rand().'.zip'; $handle = fopen($tmp_zip_path, 'wb'); if (!$isnew) { $content = $file->getLastRevision()->getFileContent(); fwrite($handle, $content, $file->getLastRevision()->getFilesize()); } fclose($handle); $zip = new ZipArchive(); if (!$isnew) $zip->open($tmp_zip_path); else $zip->open($tmp_zip_path, ZipArchive::OVERWRITE); $tmp_dir = ROOT.'/tmp/'.rand().'/'; mkdir($tmp_dir); $members = array(); foreach ($files as $file_to_add) { if (FileRepository::getBackend() instanceof FileRepository_Backend_FileSystem) { $file_to_add_path = FileRepository::getBackend()->getFilePath($file_to_add->getLastRevision()->getRepositoryId()); } else { $file_to_add_path = $tmp_dir . $file_to_add->getFilename(); $handle = fopen($file_to_add_path, 'wb'); fwrite($handle, $file_to_add->getLastRevision()->getFileContent(), $file_to_add->getLastRevision()->getFilesize()); fclose($handle); } $zip->addFile($file_to_add_path, utf8_safe($file_to_add->getFilename())); $members[] = $file_to_add->getMemberIds(); } $zip->close(); delete_dir($tmp_dir); $this->upload_file($file, $filename, $tmp_zip_path, $members); unlink($tmp_zip_path); flash_success(lang('success compressing files', count($files))); ajx_current("reload"); }
function classifyFile($classification_data, $email, $parsedEmail, $validWS, $mantainWs = true, $csv = '') { if (!is_array($classification_data)) { $classification_data = array(); } if (!isset($parsedEmail["Attachments"])) { throw new Exception(lang('no attachments found for email')); } for ($c = 0; $c < count($classification_data); $c++) { if (isset($classification_data["att_" . $c]) && $classification_data["att_" . $c]) { $att = $parsedEmail["Attachments"][$c]; $fName = str_starts_with($att["FileName"], "=?") ? iconv_mime_decode($att["FileName"], 0, "UTF-8") : utf8_safe($att["FileName"]); if (trim($fName) == "" && strlen($att["FileName"]) > 0) { $fName = utf8_encode($att["FileName"]); } try { $file = ProjectFiles::findOne(array('conditions' => "`filename` = " . DB::escape($fName) . " AND `mail_id` = " . $email->getId())); DB::beginWork(); if ($file == null) { $fileIsNew = true; $file = new ProjectFile(); $file->setFilename($fName); $file->setIsVisible(true); $file->setIsPrivate(false); $file->setIsImportant(false); $file->setCommentsEnabled(true); $file->setAnonymousCommentsEnabled(false); $file->setMailId($email->getId()); $file->save(); } else { $fileIsNew = false; } if (!$mantainWs && !$fileIsNew) { $file->removeFromWorkspaces(logged_user()->getWorkspacesQuery()); } foreach ($validWS as $w) { if (!$file->hasWorkspace($w)) { $file->addToWorkspace($w); } } $file->setTagsFromCSV($csv); $enc = array_var($parsedMail, 'Encoding', 'UTF-8'); $ext = utf8_substr($fName, strrpos($fName, '.') + 1, utf8_strlen($fName, $enc), $enc); $mime_type = ''; if (Mime_Types::instance()->has_type($att["content-type"])) { $mime_type = $att["content-type"]; //mime type is listed & valid } else { $mime_type = Mime_Types::instance()->get_type($ext); //Attempt to infer mime type } if ($fileIsNew) { $tempFileName = ROOT . "/tmp/" . logged_user()->getId() . "x" . gen_id(); $fh = fopen($tempFileName, 'w') or die("Can't open file"); fwrite($fh, $att["Data"]); fclose($fh); $fileToSave = array("name" => $fName, "type" => $mime_type, "tmp_name" => $tempFileName, "error" => 0, "size" => filesize($tempFileName)); $revision = $file->handleUploadedFile($fileToSave, true, lang('attachment from email', $email->getSubject())); // handle uploaded file $email->linkObject($file); ApplicationLogs::createLog($file, $email->getWorkspaces(), ApplicationLogs::ACTION_ADD); } DB::commit(); // Error... } catch (Exception $e) { DB::rollback(); flash_error($e->getMessage()); ajx_current("empty"); } if (isset($tempFileName) && is_file($tempFileName)) { unlink($tempFileName); } } } }
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 addToSearchableObjects($wasNew = false) { $columns_to_drop = array(); if ($wasNew) { $columns_to_drop = $this->getSearchableColumns(); } else { $searchable_columns = $this->getSearchableColumns(); if (is_array($searchable_columns)) { foreach ($searchable_columns as $column_name) { if (isset($this->searchable_composite_columns[$column_name])) { foreach ($this->searchable_composite_columns[$column_name] as $colName) { if ($this->isColumnModified($colName)) { $columns_to_drop[] = $column_name; break; } } } else { if ($this->isColumnModified($column_name)) { $columns_to_drop[] = $column_name; } } } } $searchable_columns = null; } if (count($columns_to_drop) > 0) { if (!$wasNew) { SearchableObjects::dropContentByObjectColumns($this, $columns_to_drop); } $docx_id = FileTypes::findOne(array('id' => true, 'conditions' => '`extension` = ' . DB::escape('docx'))); $pdf_id = FileTypes::findOne(array('id' => true, 'conditions' => '`extension` = ' . DB::escape('pdf'))); $odt_id = FileTypes::findOne(array('id' => true, 'conditions' => '`extension` = ' . DB::escape('odt'))); $fodt_id = FileTypes::findOne(array('id' => true, 'conditions' => '`extension` = ' . DB::escape('fodt'))); foreach ($columns_to_drop as $column_name) { $content = $this->getSearchableColumnContent($column_name); if (get_class($this->manager()) == 'ProjectFiles') { $content = utf8_encode($content); } elseif (get_class($this->manager()) == 'ProjectFileRevisions') { if ($column_name == "filecontent") { $file = ProjectFileRevisions::findById($this->getObjectId()); try { if ($file->getFileTypeId() == $docx_id) { if (class_exists('DOMDocument')) { $file_path = "tmp/doc_filecontent_" . $this->getObjectId() . ".docx"; $file_tmp = @fopen($file_path, 'w'); if ($file_tmp) { fwrite($file_tmp, $file->getFileContent()); fclose($file_tmp); $content = docx2text($file_path); unlink($file_path); } } } elseif ($file->getFileTypeId() == $pdf_id) { $file_path = "tmp/pdf_filecontent_" . $this->getObjectId() . ".pdf"; $file_tmp = @fopen($file_path, 'w'); if ($file_tmp) { fwrite($file_tmp, $file->getFileContent()); fclose($file_tmp); $content = pdf2text($file_path); unlink($file_path); } } elseif ($file->getFileTypeId() == $odt_id) { if (class_exists('DOMDocument')) { $file_path = "tmp/odt_filecontent_" . $this->getObjectId() . ".odt"; $file_tmp = @fopen($file_path, 'w'); if ($file_tmp) { fwrite($file_tmp, $file->getFileContent()); fclose($file_tmp); $content = odt2text($file_path); unlink($file_path); } } } elseif ($file->getFileTypeId() == $fodt_id) { $file_path = "tmp/fodt_filecontent_" . $this->getObjectId() . ".fodt"; $file_tmp = @fopen($file_path, 'w'); if ($file_tmp) { fwrite($file_tmp, $file->getFileContent()); fclose($file_tmp); $content = fodt2text($file_path, $this->getObjectId()); unlink($file_path); } } } catch (FileNotInRepositoryError $e) { $content = ""; } } else { $content = utf8_encode($content); } } if (trim($content) != '') { $searchable_object = new SearchableObject(); $searchable_object->setRelObjectId($this->getObjectId()); $searchable_object->setColumnName(DB::escape($column_name)); if (strlen($content) > 65535) { $content = utf8_safe(substr($content, 0, 65535)); } $content = DB::escape($content); $sql = "\n\t\t\t\t\t\tINSERT INTO " . TABLE_PREFIX . "searchable_objects (rel_object_id, column_name, content)\n\t\t\t\t\t\tVALUES (" . $searchable_object->getRelObjectId() . "," . $searchable_object->getColumnName() . "," . $content . ")\n\t\t\t\t\t\tON DUPLICATE KEY UPDATE content = {$content}"; DB::execute($sql); $searchable_object = null; } $content = null; } } $columns_to_drop = null; }
function classifyFile($classification_data, $email, $parsedEmail, $members, $remove_prev, $use_transaction) { if (!is_array($classification_data)) { $classification_data = array(); } if (!isset($parsedEmail["Attachments"])) { return; //throw new Exception(lang('no attachments found for email')); } $account_owner = logged_user() instanceof contact ? logged_user() : Contacts::findById($email->getAccount()->getContactId()); for ($c = 0; $c < count($classification_data); $c++) { if (isset($classification_data["att_" . $c]) && $classification_data["att_" . $c] && isset($parsedEmail["Attachments"][$c])) { // dont classify inline images if (array_var($parsedEmail["Attachments"][$c], 'FileDisposition') == 'attachment') { $att = $parsedEmail["Attachments"][$c]; $fName = str_starts_with($att["FileName"], "=?") ? iconv_mime_decode($att["FileName"], 0, "UTF-8") : utf8_safe($att["FileName"]); if (trim($fName) == "" && strlen($att["FileName"]) > 0) { $fName = utf8_encode($att["FileName"]); } $extension = get_file_extension(basename($fName)); $type_file_allow = FileTypes::getByExtension($extension); if (!$type_file_allow instanceof FileType || $type_file_allow->getIsAllow() == 1) { try { $remove_previous_members = $remove_prev; // check for file name and size, if there are some then compare the contents, if content is equal do not classify the attachment. $file_exists = 0; $possible_equal_file_rows = DB::executeAll("SELECT * FROM " . TABLE_PREFIX . "project_file_revisions r \r\n\t\t\t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "objects o ON o.id=r.file_id \r\n\t\t\t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "project_files f ON f.object_id=r.file_id\r\n\t\t\t\t\t\t\t\tWHERE o.name=" . DB::escape($fName) . " AND r.filesize='" . strlen($att["Data"]) . "' \r\n\t\t\t\t\t\t\t\tAND r.revision_number=(SELECT max(r2.revision_number) FROM " . TABLE_PREFIX . "project_file_revisions r2 WHERE r2.file_id=r.file_id)"); if (is_array($possible_equal_file_rows)) { foreach ($possible_equal_file_rows as $row) { $content = FileRepository::getFileContent($row['repository_id']); if ($content == $att['Data']) { // file already exists $file_exists = $row['file_id']; //Logger::log($email->getId()." - ".$row['mail_id']." - $fName"); if ($remove_previous_members && $row['mail_id'] != $email->getId()) { $remove_previous_members = false; } break; } } } if ($file_exists > 0) { $file = ProjectFiles::findById($file_exists); } else { $file = ProjectFiles::findOne(array('conditions' => "mail_id = " . $email->getId() . " AND o.name = " . DB::escape($fName) . "")); } if ($use_transaction) { DB::beginWork(); } if ($file == null) { $fileIsNew = true; $file = new ProjectFile(); $file->setFilename($fName); $file->setIsVisible(true); $file->setMailId($email->getId()); $file->setCreatedById($account_owner->getId()); $file->save(); } else { $fileIsNew = false; } if ($remove_previous_members) { $dim_ids = array(0); foreach ($members as $m) { $dim_ids[$m->getDimensionId()] = $m->getDimensionId(); } ObjectMembers::delete('`object_id` = ' . $file->getId() . ' AND `member_id` IN (SELECT `m`.`id` FROM `' . TABLE_PREFIX . 'members` `m` WHERE `m`.`dimension_id` IN (' . implode(',', $dim_ids) . '))'); } $file->addToMembers($members); // fill sharing table in background add_object_to_sharing_table($file, $account_owner); //$file->addToSharingTable(); $enc = array_var($parsedMail, 'Encoding', 'UTF-8'); $ext = utf8_substr($fName, strrpos($fName, '.') + 1, utf8_strlen($fName, $enc), $enc); $mime_type = ''; if (Mime_Types::instance()->has_type($att["content-type"])) { $mime_type = $att["content-type"]; //mime type is listed & valid } else { $mime_type = Mime_Types::instance()->get_type($ext); //Attempt to infer mime type } $userid = logged_user() ? logged_user()->getId() : "0"; $tempFileName = ROOT . "/tmp/" . $userid . "x" . gen_id(); $fh = fopen($tempFileName, 'w') or die("Can't open file"); fwrite($fh, $att["Data"]); fclose($fh); $fileToSave = array("name" => $fName, "type" => $mime_type, "tmp_name" => $tempFileName, "error" => 0, "size" => filesize($tempFileName)); if ($fileIsNew || !$file->getLastRevision() instanceof ProjectFileRevision) { $revision = $file->handleUploadedFile($fileToSave, true, lang('attachment from email', $email->getSubject())); // handle uploaded file $revision->setCreatedById($account_owner->getId()); $revision->save(); ApplicationLogs::createLog($file, ApplicationLogs::ACTION_ADD); /* }else{ $revision = $file->getLastRevision(); $new_hash = hash_file("sha256", $tempFileName); if ($revision->getHash() != $new_hash) { $revision = $file->handleUploadedFile($fileToSave, true, lang('attachment from email', $email->getSubject())); // handle uploaded file ApplicationLogs::createLog($file, ApplicationLogs::ACTION_ADD); }*/ } if ($use_transaction) { DB::commit(); } // Error... } catch (Exception $e) { if ($use_transaction) { DB::rollback(); } flash_error($e->getMessage()); ajx_current("empty"); } } else { flash_error(lang('file extension no allow classify', $fName)); } if (isset($tempFileName) && is_file($tempFileName)) { unlink($tempFileName); } } } } }
function getSummary($options = null) { $text = $this->getSummaryText(); $size = array_var($options, 'size'); $near = array_var($options, 'near'); if (is_array($options)) { if ($near) { $position = strpos($text, $near); $spacesBefore = min(10, $position); // TODO: buscar la ultima palabra antes if ($size && strlen($text) > $size) { return utf8_safe(substr($text, $position - $spacesBefore, $size)) . "..."; } else { return $text; } } } }
function classifyFile($classification_data, $email, $parsedEmail, $members, $remove_prev) { if (!is_array($classification_data)) $classification_data = array(); if (!isset($parsedEmail["Attachments"])) { return; //throw new Exception(lang('no attachments found for email')); } $account_owner = logged_user() instanceof contact ? logged_user() : Contacts::findById($email->getAccount()->getContactId()); for ($c = 0; $c < count($classification_data); $c++) { if (isset($classification_data["att_".$c]) && $classification_data["att_".$c]) { $att = $parsedEmail["Attachments"][$c]; $fName = str_starts_with($att["FileName"], "=?") ? iconv_mime_decode($att["FileName"], 0, "UTF-8") : utf8_safe($att["FileName"]); if (trim($fName) == "" && strlen($att["FileName"]) > 0) $fName = utf8_encode($att["FileName"]); $extension = get_file_extension(basename($fName)); $type_file_allow = FileTypes::getByExtension($extension); if(!($type_file_allow instanceof FileType) || $type_file_allow->getIsAllow() == 1){ try { //$sql = "SELECT o.id FROM ".TABLE_PREFIX."objects o,".TABLE_PREFIX."project_files f WHERE o.id = f.object_id AND f.mail_id = ".$email->getId()." AND o.name = ".DB::escape($fName).""; $sql = "SELECT o.id FROM ".TABLE_PREFIX."objects o,".TABLE_PREFIX."project_files f WHERE o.id = f.object_id AND o.name = ".DB::escape($fName).""; $db_res = DB::execute($sql); $row = $db_res->fetchRow(); $file = ProjectFiles::findById($row['id']); DB::beginWork(); if ($file == null){ $fileIsNew = true; $file = new ProjectFile(); $file->setFilename($fName); $file->setIsVisible(true); $file->setMailId($email->getId()); $file->save(); $object_controller = new ObjectController(); $object_controller->add_to_members($file, array(), $account_owner); } else { $fileIsNew = false; } if($remove_prev){ $dim_ids = array(0); foreach ($members as $m) $dim_ids[$m->getDimensionId()] = $m->getDimensionId(); ObjectMembers::delete('`object_id` = ' . $file->getId() . ' AND `member_id` IN (SELECT `m`.`id` FROM `'.TABLE_PREFIX.'members` `m` WHERE `m`.`dimension_id` IN ('.implode(',',$dim_ids).'))'); } $file->addToMembers($members); $file->addToSharingTable(); $enc = array_var($parsedMail,'Encoding','UTF-8'); $ext = utf8_substr($fName, strrpos($fName, '.') + 1, utf8_strlen($fName, $enc), $enc); $mime_type = ''; if (Mime_Types::instance()->has_type($att["content-type"])) { $mime_type = $att["content-type"]; //mime type is listed & valid } else { $mime_type = Mime_Types::instance()->get_type($ext); //Attempt to infer mime type } $userid = logged_user() ? logged_user()->getId() : "0"; $tempFileName = ROOT ."/tmp/". $userid ."x". gen_id(); $fh = fopen($tempFileName, 'w') or die("Can't open file"); fwrite($fh, $att["Data"]); fclose($fh); $fileToSave = array( "name" => $fName, "type" => $mime_type, "tmp_name" => $tempFileName, "error" => 0, "size" => filesize($tempFileName) ); if ($fileIsNew) { $revision = $file->handleUploadedFile($fileToSave, true, lang('attachment from email', $email->getSubject())); // handle uploaded file ApplicationLogs::createLog($file, ApplicationLogs::ACTION_ADD); }else{ $revision = $file->getLastRevision(); $new_hash = hash_file("sha256", $tempFileName); if ($revision->getHash() != $new_hash) { $revision = $file->handleUploadedFile($fileToSave, true, lang('attachment from email', $email->getSubject())); // handle uploaded file ApplicationLogs::createLog($file, ApplicationLogs::ACTION_ADD); } } DB::commit(); // Error... } catch(Exception $e) { DB::rollback(); flash_error($e->getMessage()); ajx_current("empty"); } }else{ flash_error(lang('file extension no allow classify', $fName)); } if (isset($tempFileName) && is_file($tempFileName)) unlink($tempFileName); } } }