/**
  * Return parent file object
  *
  * @param void
  * @return ProjectFile
  */
 function getFile()
 {
     if (is_null($this->file)) {
         $this->file = ProjectFiles::findById($this->getFileId());
     }
     // if
     return $this->file;
 }
Ejemplo n.º 2
0
 /**
  * Detach file from related object
  *
  * @param void
  * @return null
  */
 function detach_from_object()
 {
     $manager_class = array_var($_GET, 'manager');
     $object_id = get_id('object_id');
     $file_id = get_id('file_id');
     $object = get_object_by_manager_and_id($object_id, $manager_class);
     if (!$object instanceof ProjectDataObject) {
         flash_error(lang('no access permissions'));
         $this->redirectToReferer(get_url('dashboard'));
     }
     // if
     $file = ProjectFiles::findById($file_id);
     if (!$file instanceof ProjectFile) {
         flash_error(lang('file dnx'));
         $this->redirectToReferer(get_url('dashboard'));
     }
     // if
     $attached_file = AttachedFiles::findById(array('rel_object_manager' => $manager_class, 'rel_object_id' => $object_id, 'file_id' => $file_id));
     // findById
     if (!$attached_file instanceof AttachedFile) {
         flash_error(lang('file not attached to object'));
         $this->redirectToReferer(get_url('dashboard'));
     }
     // if
     try {
         DB::beginWork();
         $attached_file->delete();
         DB::commit();
         flash_success(lang('success detach file'));
     } catch (Exception $e) {
         flash_error(lang('error detach file'));
         DB::rollback();
     }
     // try
     $this->redirectToReferer($object->getObjectUrl());
 }
Ejemplo n.º 3
0
 /**
  * Return file
  *
  * @param void
  * @return ProjectFile
  */
 function getFile()
 {
     return ProjectFiles::findById($this->getFileId());
 }
 /**
  * Add single mail
  *
  * @access public
  * @param void
  * @return null
  */
 function add_mail()
 {
     if (logged_user()->isGuest()) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     $this->addHelper('textile');
     $mail_accounts = MailAccounts::getMailAccountsByUser(logged_user());
     if (count($mail_accounts) < 1) {
         flash_error(lang('no mail accounts set'));
         ajx_current("empty");
         return;
     }
     $this->setTemplate('add_mail');
     $mail_data = array_var($_POST, 'mail');
     $isDraft = array_var($mail_data, 'isDraft', '') == 'true' ? true : false;
     $isUpload = array_var($mail_data, 'isUpload', '') == 'true' ? true : false;
     $autosave = array_var($mail_data, 'autosave', '') == 'true';
     $id = array_var($mail_data, 'id');
     $mail = MailContents::findById($id);
     $isNew = false;
     if (!$mail) {
         $isNew = true;
         $mail = new MailContent();
     }
     tpl_assign('mail_to', urldecode(array_var($_GET, 'to')));
     tpl_assign('link_to_objects', array_var($_GET, 'link_to_objects'));
     $def_acc = $this->getDefaultAccountId();
     if ($def_acc > 0) {
         tpl_assign('default_account', $def_acc);
     }
     tpl_assign('mail', $mail);
     tpl_assign('mail_data', $mail_data);
     tpl_assign('mail_accounts', $mail_accounts);
     // Form is submited
     if (is_array($mail_data)) {
         $account = MailAccounts::findById(array_var($mail_data, 'account_id'));
         if (!$account instanceof MailAccount) {
             flash_error(lang('mail account dnx'));
             ajx_current("empty");
             return;
         }
         $accountUser = MailAccountUsers::getByAccountAndUser($account, logged_user());
         if (!$accountUser instanceof MailAccountUser) {
             flash_error(lang('no access permissions'));
             ajx_current("empty");
             return;
         }
         if ($account->getOutgoingTrasnportType() == 'ssl' || $account->getOutgoingTrasnportType() == 'tls') {
             $available_transports = stream_get_transports();
             if (array_search($account->getOutgoingTrasnportType(), $available_transports) === FALSE) {
                 flash_error('The server does not support SSL.');
                 ajx_current("empty");
                 return;
             }
         }
         $cp_errs = $this->checkRequiredCustomPropsBeforeSave(array_var($_POST, 'object_custom_properties', array()));
         if (is_array($cp_errs) && count($cp_errs) > 0) {
             foreach ($cp_errs as $err) {
                 flash_error($err);
             }
             ajx_current("empty");
             return;
         }
         $subject = array_var($mail_data, 'subject');
         $body = array_var($mail_data, 'body');
         if (($pre_body_fname = array_var($mail_data, 'pre_body_fname')) != "") {
             $body = str_replace(lang('content too long not loaded'), '', $body, $count = 1);
             $tmp_filename = ROOT . "/tmp/{$pre_body_fname}";
             if (is_file($tmp_filename)) {
                 $body .= file_get_contents($tmp_filename);
                 if (!$isDraft) {
                     @unlink($tmp_filename);
                 }
             }
         }
         if (array_var($mail_data, 'format') == 'html') {
             $css = "font-family:Arial,Verdana,sans-serif;font-size:12px;color:#222;";
             Hook::fire('email_base_css', null, $css);
             str_replace(array("\r", "\n"), "", $css);
             $body = '<div style="' . $css . '">' . $body . '</div>';
             $body = str_replace('<blockquote>', '<blockquote style="border-left:1px solid #987ADD;padding-left:10px;">', $body);
         }
         $type = 'text/' . array_var($mail_data, 'format');
         $to = trim(array_var($mail_data, 'to'));
         if (str_ends_with($to, ",") || str_ends_with($to, ";")) {
             $to = substr($to, 0, strlen($to) - 1);
         }
         $mail_data['to'] = $to;
         $cc = trim(array_var($mail_data, 'cc'));
         if (str_ends_with($cc, ",") || str_ends_with($cc, ";")) {
             $cc = substr($cc, 0, strlen($cc) - 1);
         }
         $mail_data['cc'] = $cc;
         $bcc = trim(array_var($mail_data, 'bcc'));
         if (str_ends_with($bcc, ",") || str_ends_with($bcc, ";")) {
             $bcc = substr($bcc, 0, strlen($bcc) - 1);
         }
         $mail_data['bcc'] = $bcc;
         if (!$isDraft && trim($to . $cc . $bcc) == '') {
             flash_error(lang('recipient must be specified'));
             ajx_current("empty");
             return;
         }
         $invalid_to = MailUtilities::validate_email_addresses($to);
         if (is_array($invalid_to)) {
             flash_error(lang('error invalid recipients', lang('mail to'), implode(", ", $invalid_to)));
             ajx_current("empty");
             return;
         }
         $invalid_cc = MailUtilities::validate_email_addresses($cc);
         if (is_array($invalid_cc)) {
             flash_error(lang('error invalid recipients', lang('mail CC'), implode(", ", $invalid_cc)));
             ajx_current("empty");
             return;
         }
         $invalid_bcc = MailUtilities::validate_email_addresses($bcc);
         if (is_array($invalid_bcc)) {
             flash_error(lang('error invalid recipients', lang('mail BCC'), implode(", ", $invalid_bcc)));
             ajx_current("empty");
             return;
         }
         $last_mail_in_conversation = array_var($mail_data, 'last_mail_in_conversation');
         $conversation_id = array_var($mail_data, 'conversation_id');
         if ($last_mail_in_conversation && $conversation_id) {
             $new_mail_in_conversation = MailContents::getLastMailIdInConversation($conversation_id, true);
             if ($new_mail_in_conversation != $last_mail_in_conversation) {
                 ajx_current("empty");
                 evt_add("new email in conversation", array('id' => $new_mail_in_conversation, 'genid' => array_var($_POST, 'instanceName')));
                 return;
             }
         }
         $mail->setFromAttributes($mail_data);
         $mail->setTo($to);
         $mail->setCc($cc);
         $mail->setBcc($bcc);
         $mail->setSubject($mail_data['subject']);
         $utils = new MailUtilities();
         // attachment
         $linked_attachments = array();
         $attachments = array();
         $objects = array_var($_POST, 'linked_objects');
         $attach_contents = array_var($_POST, 'attach_contents', array());
         if (is_array($objects)) {
             $err = 0;
             $count = -1;
             foreach ($objects as $objid) {
                 $count++;
                 $split = explode(":", $objid);
                 if (count($split) == 2) {
                     $object = get_object_by_manager_and_id($split[1], $split[0]);
                 } else {
                     if (count($split) == 4) {
                         if ($split[0] == 'FwdMailAttach') {
                             $tmp_filename = ROOT . "/tmp/" . logged_user()->getId() . "_" . $mail_data['account_id'] . "_FwdMailAttach_" . $split[3];
                             if (is_file($tmp_filename)) {
                                 $attachments[] = array("data" => file_get_contents($tmp_filename), "name" => $split[1], "type" => $split[2]);
                                 continue;
                             }
                         }
                     }
                 }
                 if (!isset($object) || !$object) {
                     flash_error(lang('file dnx'));
                     $err++;
                 } else {
                     if (isset($attach_contents[$count])) {
                         if ($split[0] == 'ProjectFiles') {
                             $file = ProjectFiles::findById($object->getId());
                             if (!$file instanceof ProjectFile) {
                                 flash_error(lang('file dnx'));
                                 $err++;
                             }
                             // if
                             if (!$file->canDownload(logged_user())) {
                                 flash_error(lang('no access permissions'));
                                 $err++;
                             }
                             // if
                             $attachments[] = array("data" => $file->getFileContent(), "name" => $file->getFilename(), "type" => $file->getTypeString());
                         } else {
                             if ($split[0] == 'MailContents') {
                                 $email = MailContents::findById($object->getId());
                                 if (!$email instanceof MailContent) {
                                     flash_error(lang('email dnx'));
                                     $err++;
                                 }
                                 // if
                                 if (!$email->canView(logged_user())) {
                                     flash_error(lang('no access permissions'));
                                     $err++;
                                 }
                                 // if
                                 $attachments[] = array("data" => $email->getContent(), "name" => $email->getSubject() . ".eml", "type" => 'message/rfc822');
                             }
                         }
                     } else {
                         $linked_attachments[] = array("data" => $object->getViewUrl(), "name" => clean($object->getObjectName()), "type" => lang($object->getObjectTypeName()), "manager" => $object->getObjectManagerName(), "id" => $object->getId());
                     }
                 }
             }
             if ($err > 0) {
                 flash_error(lang('some objects could not be linked', $err));
                 ajx_current('empty');
                 return;
             }
         }
         $to = preg_split('/;|,/', $to);
         $to = $utils->parse_to($to);
         if ($body == '') {
             $body .= ' ';
         }
         try {
             if (count($linked_attachments)) {
                 $linked_users = array();
                 foreach ($to as $to_user) {
                     $linked_user = Users::getByEmail($to_user[1]);
                     if (!$linked_user instanceof User) {
                         try {
                             $linked_user = create_user_from_email($to_user[1], $to_user[0]);
                         } catch (Exception $e) {
                             //Logger::log($e->getMessage());
                         }
                     }
                     if ($linked_user instanceof User) {
                         $linked_users[] = $linked_user;
                     }
                 }
                 $linked_atts = $type == 'text/html' ? '<div style="font-family:arial;"><br><br><br><span style="font-size:12pt;font-weight:bold;color:#777">' . lang('linked attachments') . '</span><ul>' : "\n\n\n-----------------------------------------\n" . lang('linked attachments') . "\n\n";
                 foreach ($linked_attachments as $att) {
                     $linked_atts .= $type == 'text/html' ? '<li><a href="' . $att['data'] . '">' . $att['name'] . ' (' . $att['type'] . ')</a></li>' : $att['name'] . ' (' . $att['type'] . '): ' . $att['data'] . "\n";
                     foreach ($linked_users as $linked_user) {
                         try {
                             $linked_user->giveAccessToObject(get_object_by_manager_and_id($att['id'], $att['manager']));
                         } catch (Exception $e) {
                             //Logger::log($e->getMessage());
                         }
                     }
                 }
                 $linked_atts .= $type == 'text/html' ? '</ul></div>' : '';
             } else {
                 $linked_atts = '';
             }
             $body .= $linked_atts;
             if (count($attachments) > 0) {
                 $i = 0;
                 $str = "";
                 /*	foreach ($attachments as $att) {
                 					$str .= "--000000000000000000000000000$i\n";
                 					$str .= "Name: ".$att['name'] .";\n";
                 					$str .= "Type: ".$att['type'] .";\n";
                 					//$str .= "Encoding: ".$att['type'] .";\n";
                 					$str .= base64_encode($att['data']) ."\n";
                 					$str .= "--000000000000000000000000000$i--\n";
                 					$i++;
                 				}
                 			*/
                 $str = "#att_ver 2\n";
                 foreach ($attachments as $att) {
                     $rep_id = $utils->saveContent($att['data']);
                     $str .= $att['name'] . "," . $att['type'] . "," . $rep_id . "\n";
                 }
                 // save attachments, when mail is sent this file is deleted and full content is saved
                 $repository_id = $utils->saveContent($str);
                 if (!$isNew) {
                     if (FileRepository::isInRepository($mail->getContentFileId())) {
                         // delete old attachments
                         $content = FileRepository::getFileContent($mail->getContentFileId());
                         if (str_starts_with($content, "#att_ver")) {
                             $lines = explode("\n", $content);
                             foreach ($lines as $line) {
                                 if (!str_starts_with($line, "#") && trim($line) !== "") {
                                     $data = explode(",", $line);
                                     if (isset($data[2]) && FileRepository::isInRepository($data[2])) {
                                         FileRepository::deleteFile($data[2]);
                                     }
                                 }
                             }
                         }
                         FileRepository::deleteFile($mail->getContentFileId());
                     }
                 }
                 $mail->setContentFileId($repository_id);
             }
             $mail->setHasAttachments(is_array($attachments) && count($attachments) > 0 ? 1 : 0);
             $mail->setAccountEmail($account->getEmailAddress());
             $mail->setSentDate(DateTimeValueLib::now());
             $mail->setReceivedDate(DateTimeValueLib::now());
             DB::beginWork();
             $msg_id = MailUtilities::generateMessageId($account->getEmailAddress());
             $conversation_id = array_var($mail_data, 'conversation_id');
             $in_reply_to_id = array_var($mail_data, 'in_reply_to_id');
             if ($conversation_id) {
                 $in_reply_to = MailContents::findById(array_var($mail_data, 'original_id'));
                 if ($in_reply_to instanceof MailContent && $in_reply_to->getSubject() && strpos(strtolower($mail->getSubject()), strtolower($in_reply_to->getSubject())) === false) {
                     $conversation_id = null;
                     $in_reply_to_id = '';
                 }
             }
             if (!$conversation_id) {
                 $conversation_id = MailContents::getNextConversationId($account->getId());
             }
             $mail->setMessageId($msg_id);
             $mail->setConversationId($conversation_id);
             $mail->setInReplyToId($in_reply_to_id);
             $mail->setUid(gen_id());
             $mail->setState($isDraft ? 2 : 200);
             $mail->setIsPrivate(false);
             set_user_config_option('last_mail_format', array_var($mail_data, 'format', 'plain'), logged_user()->getId());
             $body = utf8_safe($body);
             if (array_var($mail_data, 'format') == 'html') {
                 $mail->setBodyHtml($body);
                 $mail->setBodyPlain(utf8_safe(html_to_text($body)));
             } else {
                 $mail->setBodyPlain($body);
                 $mail->setBodyHtml('');
             }
             $mail->setFrom($account->getEmailAddress());
             $mail->setFromName(logged_user()->getDisplayName());
             $mail->save();
             $mail->setIsRead(logged_user()->getId(), true);
             $mail->setTagsFromCSV(array_var($mail_data, 'tags'));
             // autoclassify sent email
             // if replying a classified email classify on same workspace
             $classified = false;
             if (array_var($mail_data, 'original_id')) {
                 $in_reply_to = MailContents::findById(array_var($mail_data, 'original_id'));
                 if ($in_reply_to instanceof MailContent) {
                     $workspaces = $in_reply_to->getWorkspaces();
                     foreach ($workspaces as $w) {
                         if ($mail->canAdd(logged_user(), $w)) {
                             $mail->addToWorkspace($w);
                             $classified = true;
                         }
                     }
                 }
             }
             if (!$classified && $account->getWorkspace() instanceof Project) {
                 $mail->addToWorkspace($account->getWorkspace());
             }
             if (!$classified && active_project() instanceof Project) {
                 $mail->addToWorkspace(active_project());
             }
             $object_controller = new ObjectController();
             $object_controller->add_custom_properties($mail);
             $object_controller->link_to_new_object($mail);
             if (array_var($mail_data, 'link_to_objects') != '') {
                 $lto = explode('|', array_var($mail_data, 'link_to_objects'));
                 foreach ($lto as $object_string) {
                     $split_object = explode('-', $object_string);
                     $object = get_object_by_manager_and_id($split_object[1], $split_object[0]);
                     if ($object instanceof ProjectDataObject) {
                         $mail->linkObject($object);
                     }
                 }
             }
             ApplicationLogs::createLog($mail, $mail->getWorkspaces(), ApplicationLogs::ACTION_ADD);
             if (user_config_option('create_contacts_from_email_recipients') && can_manage_contacts(logged_user())) {
                 // automatically create contacts
                 foreach ($to as $recipient) {
                     $recipient_name = trim($recipient[0]);
                     $recipient_address = trim($recipient[1]);
                     if (!$recipient_address) {
                         continue;
                     }
                     $contact = Contacts::getByEmail($recipient_address);
                     if (!$contact instanceof Contact) {
                         try {
                             $contact = new Contact();
                             $contact->setEmail($recipient_address);
                             if ($recipient_name && $recipient_name != $recipient_address) {
                                 $contact->setFirstName($recipient_name);
                             } else {
                                 $index = strpos($recipient_address, "@");
                                 $recipient_name = substr($recipient_address, 0, $index);
                                 $contact->setFirstName($recipient_name);
                             }
                             $contact->save();
                         } catch (Exception $e) {
                             // TODO: show error message?
                         }
                     }
                 }
             }
             DB::commit();
             if (!$autosave) {
                 if ($isDraft) {
                     flash_success(lang('success save mail'));
                     ajx_current("empty");
                 } else {
                     evt_add("must send mails", array("account" => $mail->getAccountId()));
                     //flash_success(lang('mail is being sent'));
                     ajx_current("back");
                 }
                 evt_add("email saved", array("id" => $mail->getId(), "instance" => array_var($_POST, 'instanceName')));
             } else {
                 evt_add("draft mail autosaved", array("id" => $mail->getId(), "hf_id" => $mail_data['hf_id']));
                 flash_success(lang('success autosave draft'));
                 ajx_current("empty");
             }
         } catch (Exception $e) {
             DB::rollback();
             flash_error($e->getMessage());
             ajx_current("empty");
         }
         // try
     }
     // if
 }
Ejemplo n.º 5
0
	function display_content() {
		
		$file = ProjectFiles::findById(get_id());
		if (!$file instanceof ProjectFile) {
			die(lang("file dnx"));
		}
		if (!$file->canView(logged_user())) {
			die(lang("no access permissions"));
		}
		
		if (defined('SANDBOX_URL')) {
			$html_content = $file->getFileContentWithRealUrls();
		} else {
			$html_content = purify_html($file->getFileContentWithRealUrls());
		}
		$charset = "";
		if ($file->getTypeString() == "text/html") {
			$encoding = detect_encoding($html_content, array('UTF-8', 'ISO-8859-1', 'WINDOWS-1252'));
			$charset = ";charset=".$encoding;
		}
		
		if ($file->getTypeString() == 'text/html') {
			// Include stylesheet from FCK Editor
			$css = '<style type="text/css">';
			$css .= file_get_contents(ROOT.'/public/assets/javascript/ckeditor/contents.css');
			$css .= '</style>';
			$html_content = $css.$html_content;
		}
		
		header("Expires: " . gmdate("D, d M Y H:i:s", mktime(date("H") + 2, date("i"), date("s"), date("m"), date("d"), date("Y"))) . " GMT");
		header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
		header("Content-Type: " . $file->getTypeString() . $charset);
		header("Content-Length: " . (string) strlen($html_content));

		print($html_content);
		die();
	}
Ejemplo n.º 6
0
 static function canRead($bookId = null)
 {
     self::includeBasic();
     $file_id = self::ogBookId();
     if ($file_id == null) {
         return false;
     }
     if ($bookId != self::getGelsheetBookId($file_id)) {
         return false;
     }
     $file = ProjectFiles::findById($file_id);
     if (!$file instanceof ProjectFile) {
         return false;
     }
     return can_read(self::getCompanyWebsite()->getLoggedUser(), $file);
 }
Ejemplo n.º 7
0
 function reload_file_view()
 {
     ajx_current("reload");
     $file = ProjectFiles::findById(get_id());
     if (!$file instanceof ProjectFile) {
         flash_error(lang('file dnx'));
         return;
     }
     if (!$file->canEdit(logged_user())) {
         flash_error(lang('no access permissions'));
         return;
     }
     if (array_var($_REQUEST, 'checkout')) {
         try {
             DB::beginWork();
             $file->checkOut();
             DB::commit();
             ApplicationLogs::createLog($file, ApplicationLogs::ACTION_CHECKOUT);
         } catch (Exception $e) {
             DB::rollback();
             flash_error($e->getMessage());
         }
     }
 }
Ejemplo n.º 8
0
 function checkinFile($username, $password, $fileid)
 {
     $result = array('status' => true, 'errorid' => 0, 'message' => '');
     if ($this->loginUser($username, $password)) {
         $file = ProjectFiles::findById($fileid);
         if (!$file instanceof ProjectFile) {
             $result['message'] = lang('file dnx');
             $result['errorid'] = 1001;
             $result['status'] = false;
         }
         // if
         if ($result['status'] && !$file->canEdit(logged_user())) {
             $result['message'] = lang('no access permissions');
             $result['errorid'] = 1004;
             $result['status'] = false;
         }
         // if
         if ($result['status']) {
             $tag_names = $file->getTagNames();
             $file_data = array('description' => $file->getDescription(), 'is_private' => $file->getIsPrivate(), 'is_important' => $file->getIsImportant(), 'comments_enabled' => $file->getCommentsEnabled(), 'anonymous_comments_enabled' => $file->getAnonymousCommentsEnabled(), 'tags' => is_array($tag_names) && count($tag_names) ? implode(', ', $tag_names) : '', 'workspaces' => $file->getWorkspacesNamesCSV(logged_user()->getWorkspacesQuery()));
             // array
             try {
                 $old_is_private = $file->isPrivate();
                 $old_is_important = $file->getIsImportant();
                 $old_comments_enabled = $file->getCommentsEnabled();
                 $old_anonymous_comments_enabled = $file->getAnonymousCommentsEnabled();
                 DB::beginWork();
                 $file->setCheckedOutById(0);
                 if (!logged_user()->isMemberOfOwnerCompany()) {
                     $file->setIsPrivate($old_is_private);
                     $file->setIsImportant($old_is_important);
                     $file->setCommentsEnabled($old_comments_enabled);
                     $file->setAnonymousCommentsEnabled($old_anonymous_comments_enabled);
                 }
                 // if
                 $file->save();
                 $file->setTagsFromCSV(array_var($file_data, 'tags'));
                 $file->save_properties($file_data);
                 $ws = $file->getWorkspaces();
                 foreach ($ws as $w) {
                     ApplicationLogs::createLog($file, $w, ApplicationLogs::ACTION_EDIT);
                 }
                 DB::commit();
             } catch (Exception $e) {
                 DB::rollback();
                 $result['message'] = $e->getMessage();
                 $result['errorid'] = 1003;
                 $result['status'] = false;
             }
             // try
         }
     } else {
         $result['status'] = false;
         $result['errorid'] = 1002;
         $result['message'] = lang('invalid login data');
     }
     return $this->result_to_xml($result, 'result');
 }
 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);
                 }
             }
         }
     }
 }
Ejemplo n.º 10
0
	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);
			}
		}
	}