/** * Execute the script * * @param void * @return boolean */ function execute() { // --------------------------------------------------- // Check MySQL version // --------------------------------------------------- $mysql_version = mysql_get_server_info($this->database_connection); if($mysql_version && version_compare($mysql_version, '4.1', '>=')) { $constants['DB_CHARSET'] = 'utf8'; @mysql_query("SET NAMES 'utf8'", $this->database_connection); tpl_assign('default_collation', $default_collation = 'collate utf8_unicode_ci'); tpl_assign('default_charset', $default_charset = 'DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci'); } else { tpl_assign('default_collation', $default_collation = ''); tpl_assign('default_charset', $default_charset = ''); } // if tpl_assign('table_prefix', TABLE_PREFIX); if (defined('DB_ENGINE')) tpl_assign('engine', DB_ENGINE); else tpl_assign('engine', 'InnoDB'); // --------------------------------------------------- // Execute migration // --------------------------------------------------- // RUN QUERIES $total_queries = 0; $executed_queries = 0; $installed_version = installed_version(); if (version_compare($installed_version, $this->getVersionFrom()) <= 0) { // upgrading from a version lower than this script's 'from' version $upgrade_script = tpl_fetch(get_template_path('db_migration/1_5_figazza')); } else { // upgrading from a pre-release of this version (beta, rc, etc) $upgrade_script = ""; if (version_compare($installed_version, "1.5-beta3") < 0) { $upgrade_script .= " ALTER TABLE `".TABLE_PREFIX."users` ADD COLUMN `can_manage_time` TINYINT(1) UNSIGNED NOT NULL DEFAULT 0; ALTER TABLE `".TABLE_PREFIX."groups` ADD COLUMN `can_manage_time` TINYINT(1) UNSIGNED NOT NULL DEFAULT 0; "; } if (version_compare($installed_version, "1.5-rc") < 0) { $upgrade_script .= " INSERT INTO `".TABLE_PREFIX."config_options` (`category_name`, `name`, `value`, `config_handler_class`, `is_system`, `option_order`, `dev_comment`) VALUES ('mailing', 'smtp_address', '', 'StringConfigHandler', 0, 0, '') ON DUPLICATE KEY UPDATE id=id; "; } $upgrade_script .= " DELETE FROM `".TABLE_PREFIX."cron_events` WHERE `name` = 'backup'; INSERT INTO `".TABLE_PREFIX."user_ws_config_options` (`category_name`, `name`, `default_value`, `config_handler_class`, `is_system`, `option_order`, `dev_comment`) VALUES ('mails panel', 'email_polling', '0', 'IntegerConfigHandler', '1', '0', NULL), ('mails panel', 'show_unread_on_title', '0', 'BoolConfigHandler', '1', '0', NULL) ON DUPLICATE KEY UPDATE id=id; "; } $upgrade_script .= " ALTER TABLE `".TABLE_PREFIX."mail_accounts` MODIFY COLUMN `del_from_server` INTEGER NOT NULL default 0; "; if (version_compare($installed_version, '1.4.4') < 0) { $upgrade_script .= " ALTER TABLE `".TABLE_PREFIX."project_tasks` ADD COLUMN `repeat_end` DATETIME NOT NULL default '0000-00-00 00:00:00', ADD COLUMN `repeat_forever` tinyint(1) NOT NULL, ADD COLUMN `repeat_num` int(10) unsigned NOT NULL default '0', ADD COLUMN `repeat_d` int(10) unsigned NOT NULL, ADD COLUMN `repeat_m` int(10) unsigned NOT NULL, ADD COLUMN `repeat_y` int(10) unsigned NOT NULL, ADD COLUMN `repeat_by` varchar(15) collate utf8_unicode_ci NOT NULL default ''; "; } if (!$this->checkColumnExists(TABLE_PREFIX.'users', 'updated_by_id', $this->database_connection)) { $upgrade_script .= " ALTER TABLE `".TABLE_PREFIX."users` ADD COLUMN `updated_by_id` int(10) unsigned default NULL; "; } if (!$this->checkColumnExists(TABLE_PREFIX.'reports', 'is_order_by_asc', $this->database_connection)) { $upgrade_script = " ALTER TABLE `".TABLE_PREFIX."reports` ADD COLUMN `is_order_by_asc` TINYINT(1) $default_collation NOT NULL DEFAULT 1; $upgrade_script "; } // rename gelsheet tables before upgrading if name is wrong and if engine is case sensitive if ($this->checkTableExists(TABLE_PREFIX.'gs_fontStyles', $this->database_connection) && !$this->checkTableExists(TABLE_PREFIX.'gs_fontstyles', $this->database_connection)) { $upgrade_script = " RENAME TABLE `" . TABLE_PREFIX . "gs_fontStyles` TO `" . TABLE_PREFIX . "gs_fontstyles`; " . $upgrade_script; } if ($this->checkTableExists(TABLE_PREFIX.'gs_mergedCells', $this->database_connection) && !$this->checkTableExists(TABLE_PREFIX.'gs_mergedcells', $this->database_connection)) { $upgrade_script = " RENAME TABLE `" . TABLE_PREFIX . "gs_mergedCells` TO `" . TABLE_PREFIX . "gs_mergedcells`; " . $upgrade_script; } if($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) { $this->printMessage("Database schema transformations executed (total queries: $total_queries)"); } else { $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true); return false; } // if // UPGRADE CUSTOM PROPERTY MULTIPLE VALUES if (version_compare($installed_version, $this->getVersionFrom()) <= 0) { $res = mysql_query("SELECT * FROM `".TABLE_PREFIX."custom_property_values` WHERE `custom_property_id` IN (SELECT `id` FROM `".TABLE_PREFIX."custom_properties` WHERE `is_multiple_values` = 1)"); while ($row = mysql_fetch_assoc($res)) { $id = $row['id']; $cid = $row['custom_property_id']; $oid = $row['object_id']; $value = $row['value']; $values = explode(",", $value); $valuestrings = array(); foreach ($values as $val) { $valuestrings[] = "($oid, $cid, '$val')"; } $valuestring = implode(",", $valuestrings); mysql_query("INSERT INTO `".TABLE_PREFIX."custom_property_values` (`object_id`, `custom_property_id`, `value`) VALUES $valuestring"); mysql_query("DELETE FROM `".TABLE_PREFIX."custom_property_values` WHERE `id` = $id"); } } // UPGRADE PUBLIC FILES if (version_compare($installed_version, $this->getVersionFrom()) <= 0) { // load FileRepository classes include_once ROOT . "/environment/library/database/adapters/AbstractDBAdapter.class.php"; include_once ROOT . "/environment/library/database/DB.class.php"; include_once ROOT . "/environment/library/database/DBResult.class.php"; include_once ROOT . "/environment/classes/Inflector.class.php"; include_once ROOT . "/library/filerepository/FileRepository.class.php"; include_once ROOT . "/library/filerepository/errors/FileNotInRepositoryError.class.php"; include_once ROOT . "/library/filerepository/errors/FileRepositoryAddError.class.php"; include_once ROOT . "/library/filerepository/errors/FileRepositoryDeleteError.class.php"; include_once ROOT . "/library/filerepository/backend/FileRepository_Backend.class.php"; DB::connect(DB_ADAPTER, array( 'host' => DB_HOST, 'user' => DB_USER, 'pass' => DB_PASS, 'name' => DB_NAME, 'persist' => DB_PERSIST )); // connect if(defined('DB_CHARSET') && trim(DB_CHARSET)) { DB::execute("SET NAMES ?", DB_CHARSET); } // if $res = mysql_query("SELECT `value` FROM `".TABLE_PREFIX."config_options` WHERE `name` = 'file_storage_adapter'"); $row = mysql_fetch_assoc($res); $adapter = $row['value']; if ($adapter == 'mysql') { include_once ROOT . "/library/filerepository/backend/FileRepository_Backend_DB.class.php"; FileRepository::setBackend(new FileRepository_Backend_DB(TABLE_PREFIX)); } else { include_once ROOT . "/library/filerepository/backend/FileRepository_Backend_FileSystem.class.php"; FileRepository::setBackend(new FileRepository_Backend_FileSystem(ROOT . "/upload", TABLE_PREFIX)); } $res = mysql_query("SELECT `id`, `avatar_file` FROM `".TABLE_PREFIX."users` WHERE `avatar_file` <> ''", $this->database_connection); $count = 0; while ($row = mysql_fetch_assoc($res)) { $avatar = $row['avatar_file']; $id = $row['id']; $path = ROOT . "/public/files/$avatar"; if (is_file($path)) { $fid = FileRepository::addFile($path, array('type' => 'image/png')); mysql_query("UPDATE `".TABLE_PREFIX."users` SET `avatar_file` = '$fid' WHERE `id` = $id", $this->database_connection); $count++; } } $res = mysql_query("SELECT `id`, `picture_file` FROM `".TABLE_PREFIX."contacts` WHERE `picture_file` <> ''", $this->database_connection); while ($row = mysql_fetch_assoc($res)) { $picture = $row['picture_file']; $id = $row['id']; $path = ROOT . "/public/files/$picture"; if (is_file($path)) { $fid = FileRepository::addFile($path, array('type' => 'image/png')); mysql_query("UPDATE `".TABLE_PREFIX."contacts` SET `picture_file` = '$fid' WHERE `id` = $id", $this->database_connection); $count++; } } $res = mysql_query("SELECT `id`, `logo_file` FROM `".TABLE_PREFIX."companies` WHERE `logo_file` <> ''", $this->database_connection); while ($row = mysql_fetch_assoc($res)) { $logo = $row['logo_file']; $id = $row['id']; $path = ROOT . "/public/files/$logo"; if (is_file($path)) { $fid = FileRepository::addFile($path, array('type' => 'image/png')); mysql_query("UPDATE `".TABLE_PREFIX."companies` SET `logo_file` = '$fid' WHERE `id` = $id", $this->database_connection); $count++; } } $this->printMessage("$count public files migrated to upload directory."); } $this->printMessage('Feng Office has been upgraded. You are now running Feng Office '.$this->getVersionTo().' Enjoy!'); } // execute
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); } }
/** * 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(); }
if (!plugin_active('i18n')) { Localization::instance()->loadSettings($language, ROOT . '/language'); } try { trace(__FILE__, 'CompanyWebsite::init()'); CompanyWebsite::init(); if (config_option('upgrade_check_enabled', false)) { VersionChecker::check(false); } // if if (config_option('file_storage_adapter', 'mysql') == FILE_STORAGE_FILE_SYSTEM) { trace(__FILE__, 'FileRepository::setBackend() - use file storage'); FileRepository::setBackend(new FileRepository_Backend_FileSystem(FILES_DIR)); } else { trace(__FILE__, 'FileRepository::setBackend() - use mysql storage'); FileRepository::setBackend(new FileRepository_Backend_MySQL(DB::connection()->getLink(), TABLE_PREFIX)); } // if PublicFiles::setRepositoryPath(ROOT . '/public/files'); if (trim(PUBLIC_FOLDER) == '') { PublicFiles::setRepositoryUrl(with_slash(ROOT_URL) . 'files'); } else { PublicFiles::setRepositoryUrl(with_slash(ROOT_URL) . PUBLIC_FOLDER . '/files'); } // if // Owner company or administrator doen't exist? Let the user create them } catch (OwnerCompanyDnxError $e) { Env::executeAction('access', 'complete_installation'); } catch (AdministratorDnxError $e) { Env::executeAction('access', 'complete_installation'); // Other type of error? We need to break here
private function build_vcard($contacts) { $vcard = ""; foreach($contacts as $contact) { $vcard .= "BEGIN:VCARD\nVERSION:3.0\n"; $vcard .= "N:" . $contact->getSurname() . ";" . $contact->getFirstname() . "\n"; $vcard .= "FN:" . $contact->getFirstname() . " " . $contact->getSurname() . "\n"; if ($contact->getCompany() instanceof Contact) $vcard .= "ORG:" . $contact->getCompany()->getObjectName() . "\n"; if ($contact->getJobTitle()) $vcard .= "TITLE:" . $contact->getJobTitle() . "\n"; if ($contact->getDepartment()) $vcard .= "X-DEPARTMENT:" . $contact->getDepartment() . "\n"; if ($contact->getBirthday() instanceof DateTimeValue) $vcard .= "BDAY:" . $contact->getBirthday()->format("Y-m-d") . "\n"; //HOME if ($contact->getPhoneNumber('home',true)) $vcard .= "TEL;TYPE=HOME,VOICE:" . $contact->getPhoneNumber('home',true) . "\n"; if ($contact->getPhoneNumber('home')) $vcard .= "TEL;TYPE=HOME,VOICE:" . $contact->getPhoneNumber('home') . "\n"; if ($contact->getPhoneNumber('fax')) $vcard .= "TEL;TYPE=HOME,FAX:" . $contact->getPhoneNumber('fax') . "\n"; if ($contact->getPhoneNumber('mobile')) $vcard .= "TEL;TYPE=CELL,VOICE:" . $contact->getPhoneNumber('mobile') . "\n"; if ($contact->getPhoneNumber('pager')) $vcard .= "TEL;TYPE=PAGER:" . $contact->getPhoneNumber('pager') . "\n"; $haddress = $contact->getAddress('home'); if ($haddress) $vcard .= "ADR;TYPE=HOME:" . $haddress->getStreet() .";". $haddress->getCity() .";". $haddress->getState() .";". $haddress->getZipcode() .";". $haddress->getCountryName() . "\n"; if ($contact->getWebpageUrl('personal')) $vcard .= "URL;TYPE=HOME:" . $contact->getWebpageUrl('personal') . "\n"; //WORK if ($contact->getPhoneNumber('work',true)) $vcard .= "TEL;TYPE=WORK,VOICE:" . $contact->getPhoneNumber('work',true) . "\n"; if ($contact->getPhoneNumber('work')) $vcard .= "TEL;TYPE=WORK,VOICE:" . $contact->getPhoneNumber('work') . "\n"; if ($contact->getPhoneNumber('fax', true)) $vcard .= "TEL;TYPE=WORK,FAX:" . $contact->getPhoneNumber('fax', true) . "\n"; $waddress = $contact->getAddress('work'); if ($waddress) $vcard .= "ADR;TYPE=WORK:" . $waddress->getStreet() .";". $waddress->getCity() .";". $waddress->getState() .";". $waddress->getZipcode() .";". $waddress->getCountryName() . "\n"; if ($contact->getPhoneNumber('assistant')) $vcard .= "TEL;TYPE=X-ASSISTANT,VOICE:" . $contact->getPhoneNumber('assistant') . "\n"; if ($contact->getPhoneNumber('callback')) $vcard .= "TEL;TYPE=X-CALLBACK,VOICE:" . $contact->getPhoneNumber('callback') . "\n"; if ($contact->getWebpageUrl('work')) $vcard .= "URL;TYPE=WORK:" . $contact->getWebpageUrl('work') . "\n"; //OTHER if ($contact->getPhoneNumber('other',true)) $vcard .= "TEL;TYPE=VOICE:" . $contact->getPhoneNumber('other',true) . "\n"; if ($contact->getPhoneNumber('other')) $vcard .= "TEL;TYPE=VOICE:" . $contact->getPhoneNumber('other') . "\n"; $oaddress = $contact->getAddress('other'); if ($oaddress) $vcard .= "ADR;TYPE=INTL:" . $oaddress->getStreet() .";". $oaddress->getCity() .";". $oaddress->getState() .";". $oaddress->getZipcode() .";". $oaddress->getCountryName() . "\n"; if ($contact->getWebpageUrl('other')) $vcard .= "URL:" . $contact->getWebpageUrl('other') . "\n"; if ($contact->getEmailAddress('personal')) $vcard .= "EMAIL;TYPE=PREF,INTERNET:" . $contact->getEmailAddress() . "\n"; $personal_emails = $contact->getContactEmails('personal'); if (!is_null($personal_emails) && isset($personal_emails[0])) $vcard .= "EMAIL;TYPE=INTERNET:" . $personal_emails[0]->getEmailAddress() . "\n"; if (!is_null($personal_emails) && isset($personal_emails[1])) $vcard .= "EMAIL;TYPE=INTERNET:" . $personal_emails[1]->getEmailAddress() . "\n"; if ($contact->hasPicture()) { $data = FileRepository::getFileContent($contact->getPictureFile()); $chunklen = 62; $pre = "PHOTO;ENCODING=BASE64;TYPE=PNG:"; $b64 = base64_encode($data); $enc_data = substr($b64, 0, $chunklen + 1 - strlen($pre)) . "\n "; $enc_data .= chunk_split(substr($b64, $chunklen + 1 - strlen($pre)), $chunklen, "\n "); $vcard .= $pre . $enc_data . "\n"; } $vcard .= "END:VCARD\n"; } return $vcard; }
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; }
private static function getLogoAttachmentData($toemail) { $logo_info = array(); try { $content = FileRepository::getBackend()->getFileContent(owner_company()->getPictureFile()); if ($content != "") { $file_path = ROOT . "/tmp/logo_empresa.png"; $handle = fopen($file_path, 'wb'); if ($handle) { fwrite($handle, $content); fclose($handle); if (!$toemail) { $toemail = "recipient@"; } $logo_info = array('cid' => gen_id() . substr($toemail, strpos($toemail, '@')), 'path' => $file_path, 'type' => 'image/png', 'disposition' => 'inline', 'name' => 'logo_empresa.png'); } } } catch (FileNotInRepositoryError $e) { Logger::log("Could not find owner company picture file: " . $e->getMessage()); } $logo_info; }
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'); }
/** * Returns the mail content. If it is in repository returns the file content, * else tries to get the content from database (if column content exists). * * @access public * @param void * @return string */ function getContent() { if (FileRepository::isInRepository($this->getContentFileId())) { return FileRepository::getFileContent($this->getContentFileId()); } else { if ($this->getMailData()->columnExists('content')) { return $this->getMailData()->getContent(); } } }
if (defined('FORCE_UPGRADE_CHECK') && FORCE_UPGRADE_CHECK) { // if two days since last upgrade check => check for upgrades $lastUpgradeCheck = config_option('upgrade_last_check_datetime', 0); if ($lastUpgradeCheck instanceof DateTimeValue) { $lastUpgradeCheck = $lastUpgradeCheck->getTimestamp(); } if ($lastUpgradeCheck < DateTimeValueLib::now()->getTimestamp() - 60 * 60 * 24 * 2) { VersionChecker::check(true); } } $locale = get_locale(); Localization::instance()->loadSettings($locale, ROOT . '/language'); if (config_option('file_storage_adapter', 'mysql') == FILE_STORAGE_FILE_SYSTEM) { FileRepository::setBackend(new FileRepository_Backend_FileSystem(FILES_DIR, TABLE_PREFIX)); } else { FileRepository::setBackend(new FileRepository_Backend_DB(TABLE_PREFIX)); } // if PublicFiles::setRepositoryPath(ROOT . '/public/files'); if (trim(PUBLIC_FOLDER) == '') { PublicFiles::setRepositoryUrl(with_slash(ROOT_URL) . 'files'); } else { PublicFiles::setRepositoryUrl(with_slash(ROOT_URL) . 'public/files'); } // if // Owner company or administrator doen't exist? Let the user create them } catch (OwnerCompanyDnxError $e) { Localization::instance()->loadSettings(DEFAULT_LOCALIZATION, ROOT . '/language'); Env::executeAction('access', 'complete_installation'); } catch (AdministratorDnxError $e) { Localization::instance()->loadSettings(DEFAULT_LOCALIZATION, ROOT . '/language');
/** * Execute the script * * @param void * @return boolean */ function execute() { // --------------------------------------------------- // Check MySQL version // --------------------------------------------------- $mysql_version = mysql_get_server_info($this->database_connection); if ($mysql_version && version_compare($mysql_version, '4.1', '>=')) { $constants['DB_CHARSET'] = 'utf8'; @mysql_query("SET NAMES 'utf8'", $this->database_connection); tpl_assign('default_collation', $default_collation = 'collate utf8_unicode_ci'); tpl_assign('default_charset', $default_charset = 'DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci'); } else { tpl_assign('default_collation', $default_collation = ''); tpl_assign('default_charset', $default_charset = ''); } // if tpl_assign('table_prefix', TABLE_PREFIX); if (defined('DB_ENGINE')) { tpl_assign('engine', DB_ENGINE); } else { tpl_assign('engine', 'InnoDB'); } // --------------------------------------------------- // Execute migration // --------------------------------------------------- // RUN QUERIES $total_queries = 0; $executed_queries = 0; $installed_version = installed_version(); if (version_compare($installed_version, $this->getVersionFrom()) <= 0) { // upgrading from a version lower than this script's 'from' version $upgrade_script = tpl_fetch(get_template_path('db_migration/1_6_chivito')); } else { // upgrading from a pre-release of this version (beta, rc, etc) $upgrade_script = ""; if (version_compare($installed_version, "1.6-beta2") < 0) { $upgrade_script .= "\r\n\t\t\t\t\tINSERT INTO `" . TABLE_PREFIX . "user_ws_config_options` (`category_name`, `name`, `default_value`, `config_handler_class`, `is_system`, `option_order`, `dev_comment`) VALUES\r\n\t\t\t\t\t\t('general', 'search_engine', 'match', 'SearchEngineConfigHandler', 0, 700, ''),\r\n\t\t\t\t\t \t('mails panel', 'mails account filter', '', 'StringConfigHandler', '1', '0', NULL),\r\n\t\t\t\t\t\t('mails panel', 'mails classification filter', 'all', 'StringConfigHandler', '1', '0', NULL),\r\n\t\t\t\t\t\t('mails panel', 'mails read filter', 'all', 'StringConfigHandler', '1', '0', NULL),\r\n\t\t \t\t\t\t('dashboard', 'show_two_weeks_calendar', '1', 'BoolConfigHandler', '0', '0', NULL)\r\n\t\t \t\t\tON DUPLICATE KEY UPDATE id=id;\r\n\t\t \t\t\tUPDATE `" . TABLE_PREFIX . "user_ws_config_options` SET `category_name` = 'general' WHERE `name` = 'work_day_start_time';\r\n\t\t \t\t\tALTER TABLE `" . TABLE_PREFIX . "mail_contents` ADD INDEX `in_reply_to_id` (`in_reply_to_id`);\r\n\t\t\t\t"; } if (version_compare($installed_version, "1.6-beta3") < 0) { $upgrade_script .= "\r\n\t\t \t\t\tALTER TABLE `" . TABLE_PREFIX . "mail_contents`\r\n\t\t \t\t\t ADD COLUMN `received_date` datetime NOT NULL default '0000-00-00 00:00:00',\r\n\t\t \t\t\t ADD INDEX `received_date` (`received_date`);\r\n\t\t \t\t\tUPDATE `" . TABLE_PREFIX . "mail_contents` SET `received_date` = `sent_date`;\r\n\t\t \t\t\tUPDATE `" . TABLE_PREFIX . "user_ws_config_options` SET `default_value` = '1' WHERE `name` = 'autodetect_time_zone';\r\n\t\t\t\t"; } if (version_compare($installed_version, "1.6-rc") < 0) { $upgrade_script .= "\r\n\t\t\t\t\tINSERT INTO `" . TABLE_PREFIX . "cron_events` (`name`, `recursive`, `delay`, `is_system`, `enabled`, `date`) VALUES\r\n\t\t\t\t\t\t('clear_tmp_folder', '1', '1440', '1', '1', '0000-00-00 00:00:00')\r\n\t\t\t\t\tON DUPLICATE KEY UPDATE id=id;\r\n\t\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "mail_contents`\r\n\t\t\t\t\t\tMODIFY COLUMN `message_id` varchar(255) {$default_collation} NOT NULL COMMENT 'Message-Id header',\r\n\t\t\t\t\t\tMODIFY COLUMN `in_reply_to_id` varchar(255) {$default_collation} NOT NULL COMMENT 'Message-Id header of the previous email in the conversation',\r\n\t\t\t\t\t\tMODIFY COLUMN `uid` varchar(255) {$default_collation} NOT NULL default '';\r\n\t\t\t\t\tINSERT INTO `" . TABLE_PREFIX . "user_ws_config_options` (`category_name`, `name`, `default_value`, `config_handler_class`, `is_system`, `option_order`, `dev_comment`) VALUES\r\n\t\t\t\t\t\t('mails panel', 'hide_quoted_text_in_emails', '1', 'BoolConfigHandler', 0, 110, NULL)\r\n\t\t \t\t\tON DUPLICATE KEY UPDATE id=id;\r\n\t\t\t\t"; } if (version_compare($installed_version, "1.6") < 0) { $upgrade_script .= "\r\n\t\t \t\t\tALTER TABLE `" . TABLE_PREFIX . "mail_contents`\r\n\t\t \t\t\t ADD INDEX `state` (`state`);\r\n\t\t\t\t"; } if (version_compare($installed_version, "1.6.1") < 0) { $upgrade_script .= "\r\n\t\t\t\t\tINSERT INTO `" . TABLE_PREFIX . "config_options` (`category_name`, `name`, `value`, `config_handler_class`, `is_system`, `option_order`, `dev_comment`) VALUES\r\n\t\t\t\t\t ('general', 'detect_mime_type_from_extension', '0', 'BoolConfigHandler', '0', '0', NULL)\r\n\t\t\t\t\tON DUPLICATE KEY UPDATE id=id;\r\n\t\t\t\t\tUPDATE `" . TABLE_PREFIX . "user_ws_config_options` SET `config_handler_class` = 'RememberGUIConfigHandler' WHERE `name` = 'rememberGUIState';\r\n\t\t\t\t"; } if (version_compare($installed_version, "1.6.2") < 0) { $upgrade_script .= "\r\n\t\t\t\t\tINSERT INTO `" . TABLE_PREFIX . "user_ws_config_options` (`category_name`, `name`, `default_value`, `config_handler_class`, `is_system`, `option_order`, `dev_comment`) VALUES\r\n\t\t\t\t\t ('task panel', 'task_display_limit', '500', 'IntegerConfigHandler', '0', '200', NULL)\r\n\t\t\t\t\tON DUPLICATE KEY UPDATE id=id;\r\n\t\t\t\t"; } } // rename gelsheet tables before upgrading if name is wrong and if engine is case sensitive if ($this->checkTableExists(TABLE_PREFIX . 'gs_fontStyles', $this->database_connection) && !$this->checkTableExists(TABLE_PREFIX . 'gs_fontstyles', $this->database_connection)) { $upgrade_script = "\r\n\t\t\t\tRENAME TABLE `" . TABLE_PREFIX . "gs_fontStyles` TO `" . TABLE_PREFIX . "gs_fontstyles`;\r\n\t\t\t" . $upgrade_script; } if ($this->checkTableExists(TABLE_PREFIX . 'gs_mergedCells', $this->database_connection) && !$this->checkTableExists(TABLE_PREFIX . 'gs_mergedcells', $this->database_connection)) { $upgrade_script = "\r\n\t\t\t\tRENAME TABLE `" . TABLE_PREFIX . "gs_mergedCells` TO `" . TABLE_PREFIX . "gs_mergedcells`;\r\n\t\t\t" . $upgrade_script; } if ($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) { $this->printMessage("Database schema transformations executed (total queries: {$total_queries})"); } else { $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true); return false; } // if // UPGRADE PUBLIC FILES (mark as public) if (version_compare($installed_version, $this->getVersionFrom()) <= 0) { // load FileRepository classes include_once ROOT . "/environment/library/database/adapters/AbstractDBAdapter.class.php"; include_once ROOT . "/environment/library/database/DB.class.php"; include_once ROOT . "/environment/library/database/DBResult.class.php"; include_once ROOT . "/environment/classes/Inflector.class.php"; include_once ROOT . "/library/filerepository/FileRepository.class.php"; include_once ROOT . "/library/filerepository/errors/FileNotInRepositoryError.class.php"; include_once ROOT . "/library/filerepository/errors/FileRepositoryAddError.class.php"; include_once ROOT . "/library/filerepository/errors/FileRepositoryDeleteError.class.php"; include_once ROOT . "/library/filerepository/backend/FileRepository_Backend.class.php"; DB::connect(DB_ADAPTER, array('host' => DB_HOST, 'user' => DB_USER, 'pass' => DB_PASS, 'name' => DB_NAME, 'persist' => DB_PERSIST)); // connect if (defined('DB_CHARSET') && trim(DB_CHARSET)) { DB::execute("SET NAMES ?", DB_CHARSET); } // if $res = mysql_query("SELECT `value` FROM `" . TABLE_PREFIX . "config_options` WHERE `name` = 'file_storage_adapter'"); $row = mysql_fetch_assoc($res); $adapter = $row['value']; if ($adapter == 'mysql') { include_once ROOT . "/library/filerepository/backend/FileRepository_Backend_DB.class.php"; FileRepository::setBackend(new FileRepository_Backend_DB(TABLE_PREFIX)); } else { include_once ROOT . "/library/filerepository/backend/FileRepository_Backend_FileSystem.class.php"; FileRepository::setBackend(new FileRepository_Backend_FileSystem(ROOT . "/upload", TABLE_PREFIX)); } $res = mysql_query("SELECT `id`, `avatar_file` FROM `" . TABLE_PREFIX . "users` WHERE `avatar_file` <> ''", $this->database_connection); $count = 0; while ($row = mysql_fetch_assoc($res)) { $fid = $row['avatar_file']; FileRepository::setFileAttribute($fid, 'public', true); $count++; } $res = mysql_query("SELECT `id`, `picture_file` FROM `" . TABLE_PREFIX . "contacts` WHERE `picture_file` <> ''", $this->database_connection); while ($row = mysql_fetch_assoc($res)) { $fid = $row['picture_file']; FileRepository::setFileAttribute($fid, 'public', true); $count++; } $res = mysql_query("SELECT `id`, `logo_file` FROM `" . TABLE_PREFIX . "companies` WHERE `logo_file` <> ''", $this->database_connection); while ($row = mysql_fetch_assoc($res)) { $fid = $row['logo_file']; FileRepository::setFileAttribute($fid, 'public', true); $count++; } $this->printMessage("{$count} public files updated."); } $this->printMessage('Feng Office has been upgraded. You are now running Feng Office ' . $this->getVersionTo() . ' Enjoy!'); }
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); } } } } }
/** * Check if this user has uploaded avatar * * @access public * @param void * @return boolean */ function hasAvatar() { return trim($this->getAvatarFile()) != '' && FileRepository::isInRepository($this->getAvatarFile()); }
function workEstimate(ProjectTask $task) { tpl_assign('task_assigned', $task); if (!$task->getAssignedTo() instanceof Contact) { return true; // not assigned to user } if (!is_valid_email($task->getAssignedTo()->getEmailAddress())) { return true; } $locale = $task->getAssignedTo()->getLocale(); Localization::instance()->loadSettings($locale, ROOT . '/language'); tpl_assign('title', $task->getObjectName()); tpl_assign('by', $task->getAssignedBy()->getObjectName()); tpl_assign('asigned', $task->getAssignedTo()->getObjectName()); $text = ""; if (config_option("wysiwyg_tasks")) { $text = purify_html(nl2br($task->getDescription())); } else { $text = escape_html_whitespace($task->getDescription()); } tpl_assign('description', $text); //descripction tpl_assign('description_title', lang("new task work estimate to you desc", $task->getObjectName(), $task->getCreatedBy()->getObjectName())); //description_title //priority if ($task->getPriority()) { if ($task->getPriority() >= ProjectTasks::PRIORITY_URGENT) { $priorityColor = "#FF0000"; $priority = lang('urgent priority'); } else { if ($task->getPriority() >= ProjectTasks::PRIORITY_HIGH) { $priorityColor = "#FF9088"; $priority = lang('high priority'); } else { if ($task->getPriority() <= ProjectTasks::PRIORITY_LOW) { $priorityColor = "white"; $priority = lang('low priority'); } else { $priorityColor = "#DAE3F0"; $priority = lang('normal priority'); } } } tpl_assign('priority', array($priority, $priorityColor)); } //context $contexts = array(); if ($task->getMembersToDisplayPath()) { $members = $task->getMembersToDisplayPath(); foreach ($members as $key => $member) { $dim = Dimensions::getDimensionById($key); if ($dim->getCode() == "customer_project") { foreach ($members[$key] as $member) { $obj_type = ObjectTypes::findById($member['ot']); $contexts[$dim->getCode()][$obj_type->getName()][] = '<span style="' . get_workspace_css_properties($member['c']) . '">' . $member['name'] . '</span>'; } } else { foreach ($members[$key] as $member) { $contexts[$dim->getCode()][] = '<span style="' . get_workspace_css_properties($member['c']) . '">' . $member['name'] . '</span>'; } } } } tpl_assign('contexts', $contexts); //workspaces //start date, due date or start if ($task->getStartDate() instanceof DateTimeValue) { $date = Localization::instance()->formatDescriptiveDate($task->getStartDate(), $task->getAssignedTo()->getTimezone()); $time = Localization::instance()->formatTime($task->getStartDate(), $task->getAssignedTo()->getTimezone()); if ($time > 0) { $date .= " " . $time; } tpl_assign('start_date', $date); //start_date } if ($task->getDueDate() instanceof DateTimeValue) { $date = Localization::instance()->formatDescriptiveDate($task->getDueDate(), $task->getAssignedTo()->getTimezone()); $time = Localization::instance()->formatTime($task->getDueDate(), $task->getAssignedTo()->getTimezone()); if ($time > 0) { $date .= " " . $time; } tpl_assign('due_date', $date); //due_date } $attachments = array(); try { $content = FileRepository::getBackend()->getFileContent(owner_company()->getPictureFile()); $file_path = ROOT . "/upload/logo_empresa.png"; $handle = fopen($file_path, 'wb'); fwrite($handle, $content); fclose($handle); if ($content != "") { $attachments['logo'] = array('cid' => gen_id() . substr($task->getAssignedBy()->getEmailAddress(), strpos($task->getAssignedBy()->getEmailAddress(), '@')), 'path' => $file_path, 'type' => 'image/png', 'disposition' => 'inline', 'name' => 'logo_empresa.png'); tpl_assign('attachments', $attachments); // attachments } } catch (FileNotInRepositoryError $e) { // If no logo is set, don't interrupt notifications. } tpl_assign('attachments', $attachments); // attachments self::queueEmail(array(self::prepareEmailAddress($task->getCreatedBy()->getEmailAddress(), $task->getCreatedBy()->getObjectName())), self::prepareEmailAddress($task->getUpdatedBy()->getEmailAddress(), $task->getUpdatedByDisplayName()), lang('work estimate title'), tpl_fetch(get_template_path('work_estimate', 'notifier')), 'text/html', '8bit', $attachments); // send $locale = logged_user() instanceof Contact ? logged_user()->getLocale() : DEFAULT_LOCALIZATION; Localization::instance()->loadSettings($locale, ROOT . '/language'); }
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 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 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 workEstimate(ProjectTask $task) { tpl_assign('task_assigned', $task); if(!($task->getAssignedTo() instanceof Contact)) { return true; // not assigned to user } if (!is_valid_email($task->getAssignedTo()->getEmailAddress())) { return true; } $locale = $task->getAssignedTo()->getLocale(); Localization::instance()->loadSettings($locale, ROOT . '/language'); tpl_assign('title', $task->getObjectName()); tpl_assign('by', $task->getAssignedBy()->getObjectName()); tpl_assign('asigned', $task->getAssignedTo()->getObjectName()); $text = ""; if(config_option("wysiwyg_tasks")){ $text = purify_html(nl2br($task->getDescription())); }else{ $text = escape_html_whitespace($task->getDescription()); } tpl_assign('description', $text);//descripction tpl_assign('description_title', lang("new task work estimate to you desc", $task->getObjectName(),$task->getAssignedBy()->getObjectName()));//description_title //priority if ($task->getPriority()) { if ($task->getPriority() >= ProjectTasks::PRIORITY_URGENT) { $priorityColor = "#FF0000"; $priority = lang('urgent priority'); }else if ($task->getPriority() >= ProjectTasks::PRIORITY_HIGH) { $priorityColor = "#FF9088"; $priority = lang('high priority'); } else if ($task->getPriority() <= ProjectTasks::PRIORITY_LOW) { $priorityColor = "white"; $priority = lang('low priority'); }else{ $priorityColor = "#DAE3F0"; $priority = lang('normal priority'); } tpl_assign('priority', array($priority,$priorityColor)); } //context $contexts = array(); $members = $task->getMembers(); if(count($members)>0){ foreach ($members as $member){ $dim = $member->getDimension(); if($dim->getIsManageable()){ if ($dim->getCode() == "customer_project"){ $obj_type = ObjectTypes::findById($member->getObjectTypeId()); if ($obj_type instanceof ObjectType) { $contexts[$dim->getCode()][$obj_type->getName()][]= '<span style="'.get_workspace_css_properties($member->getMemberColor()).'">'. $member->getName() .'</span>'; } }else{ $contexts[$dim->getCode()][]= '<span style="'.get_workspace_css_properties($member->getMemberColor()).'">'. $member->getName() .'</span>'; } } } } tpl_assign('contexts', $contexts);//workspaces //start date, due date or start if ($task->getStartDate() instanceof DateTimeValue) { $date = Localization::instance()->formatDescriptiveDate($task->getStartDate(), $task->getAssignedTo()->getTimezone()); $time = Localization::instance()->formatTime($task->getStartDate(), $task->getAssignedTo()->getTimezone()); if($time > 0) $date .= " " . $time; tpl_assign('start_date', $date);//start_date } if ($task->getDueDate() instanceof DateTimeValue) { $date = Localization::instance()->formatDescriptiveDate($task->getDueDate(), $task->getAssignedTo()->getTimezone()); $time = Localization::instance()->formatTime($task->getDueDate(), $task->getAssignedTo()->getTimezone()); if($time > 0) $date .= " " . $time; tpl_assign('due_date', $date);//due_date } $attachments = array(); try { $content = FileRepository::getBackend()->getFileContent(owner_company()->getPictureFile()); if ($content) { $file_path = ROOT . "/tmp/logo_empresa.png"; $handle = fopen($file_path, 'wb'); if ($handle) { fwrite($handle, $content); fclose($handle); $attachments['logo'] = array( 'cid' => gen_id() . substr($task->getAssignedBy()->getEmailAddress(), strpos($task->getAssignedBy()->getEmailAddress(), '@')), 'path' => $file_path, 'type' => 'image/png', 'disposition' => 'inline', 'name' => 'logo_empresa.png', ); } } } catch (FileNotInRepositoryError $e) { unset($attachments['logo']); } tpl_assign('attachments', $attachments);// attachments //ALL SUBSCRIBERS if($task->getSubscribers()){ $subscribers = $task->getSubscribers(); $string_subscriber = ''; $total_s = count($subscribers); $c = 0; foreach ($subscribers as $subscriber){ $c++; if($c == $total_s && $total_s > 1){ $string_subscriber .= lang('and'); }else if($c > 1){ $string_subscriber .= ", "; } $string_subscriber .= $subscriber->getFirstName(); if($subscriber->getSurname() != "") $string_subscriber .=" " . $subscriber->getSurname(); } tpl_assign('subscribers', $string_subscriber);// subscribers } if($task->getAssignedById() == $task->getAssignedToContactId()){ $emails[] = array( "to" => array(self::prepareEmailAddress($task->getAssignedBy()->getEmailAddress(), $task->getAssignedBy()->getObjectName())), "from" => self::prepareEmailAddress($task->getUpdatedBy()->getEmailAddress(), $task->getUpdatedByDisplayName()), "subject" => lang('work estimate title'), "body" => tpl_fetch(get_template_path('work_estimate', 'notifier')), "attachments" => $attachments ); }else{ $emails[] = array( "to" => array(self::prepareEmailAddress($task->getAssignedBy()->getEmailAddress(), $task->getAssignedBy()->getObjectName())), "from" => self::prepareEmailAddress($task->getUpdatedBy()->getEmailAddress(), $task->getUpdatedByDisplayName()), "subject" => lang('work estimate title'), "body" => tpl_fetch(get_template_path('work_estimate', 'notifier')), "attachments" => $attachments ); $emails[] = array( "to" => array(self::prepareEmailAddress($task->getAssignedTo()->getEmailAddress(), $task->getAssignedTo()->getObjectName())), "from" => self::prepareEmailAddress($task->getUpdatedBy()->getEmailAddress(), $task->getUpdatedByDisplayName()), "subject" => lang('work estimate title'), "body" => tpl_fetch(get_template_path('work_estimate', 'notifier')), "attachments" => $attachments ); } self::queueEmails($emails); $locale = logged_user() instanceof Contact ? logged_user()->getLocale() : DEFAULT_LOCALIZATION; Localization::instance()->loadSettings($locale, ROOT . '/language'); }
/** * Check if this user has uploaded picture * * @access public * @param void * @return boolean */ function hasPicture() { return trim($this->getPictureFile()) != '' && FileRepository::isInRepository($this->getPictureFile()); }
/** * This function will process uploaded file * * @param array $uploaded_file * @param boolean $create_revision Create new revision or update last one * @param string $revision_comment Revision comment, if any * @return ProjectFileRevision */ function handleUploadedFile($uploaded_file, $create_revision = true, $revision_comment = '') { $revision = null; if (!$create_revision) { $revision = $this->getLastRevision(); } // if if (!$revision instanceof ProjectFileRevision) { $revision = new ProjectFileRevision(); $revision->setFileId($this->getId()); $revision->setRevisionNumber($this->getNextRevisionNumber()); if (trim($revision_comment) == '' && $this->countRevisions() < 1) { $revision_comment = lang('initial versions'); } // if } // if $revision->deleteThumb(false); // remove thumb // We have a file to handle! if (!is_array($uploaded_file) || !isset($uploaded_file['name']) || !isset($uploaded_file['size']) || !isset($uploaded_file['type']) || !isset($uploaded_file['tmp_name']) || !is_readable($uploaded_file['tmp_name'])) { throw new InvalidUploadError($uploaded_file); } // if if (isset($uploaded_file['error']) && $uploaded_file['error'] > UPLOAD_ERR_OK) { throw new InvalidUploadError($uploaded_file); } // if $repository_id = FileRepository::addFile($uploaded_file['tmp_name'], array('name' => $uploaded_file['name'], 'type' => $uploaded_file['type'], 'size' => $uploaded_file['size'])); $revision->setRepositoryId($repository_id); $revision->deleteThumb(false); $revision->setFilesize($uploaded_file['size']); $revision->setFilename($uploaded_file['name']); $revision->setTypeString($uploaded_file['type']); $extension = get_file_extension(basename($uploaded_file['name'])); if (trim($extension)) { $file_type = FileTypes::getByExtension($extension); if ($file_type instanceof Filetype) { $revision->setFileTypeId($file_type->getId()); } // if } // if $revision->setComment($revision_comment); $revision->save(); $this->last_revision = $revision; // update last revision return $revision; }
/** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(XMCTBRequest $request, $id) { try { if ($request->hasFile('file')) { $fileInfo = $this->uploadFile($request->file('file'), 'xmctb'); // if upload success if ($fileInfo) { $ship = $this->ship->update($id, $request->only($this->dataGet), $fileInfo['name']); // update file table if isset if (isset($ship->file)) { $file = $ship->file; $file->update($id, $fileInfo); } else { //save info file $file = new FileRepository(new File()); $fileInfo['ship_id'] = $ship->id; $file->create($fileInfo); } } } else { $this->ship->update($id, $request->only($this->dataGet)); } return redirect()->back(); } catch (Exception $e) { return redirect()->back()->withInput()->with('error', 'Không thể truy vấn dữ liệu'); } }
/** * Delete from DB and from the disk * * @param void * @return boolean */ function delete() { FileRepository::deleteFile($this->getRepositoryId()); $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 }
/** * 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 }
/** * Set backend value * * @param FileRepository_Backend $value * @return null * @throws InvalidInstanceError */ static function setBackend($value, $backend_name = null) { if ($value instanceof FileRepository_Backend) { if (is_null($backend_name)) { self::$default_backend = $value; } else { self::$additional_backends[$backend_name] = $value; } // if } else { throw new InvalidInstanceError('value', $value, 'FileRepository_Backend'); } // if }
/** * Execute the script * * @param void * @return boolean */ function execute() { // --------------------------------------------------- // Check MySQL version // --------------------------------------------------- $mysql_version = mysql_get_server_info($this->database_connection); if ($mysql_version && version_compare($mysql_version, '4.1', '>=')) { $constants['DB_CHARSET'] = 'utf8'; @mysql_query("SET NAMES 'utf8'", $this->database_connection); tpl_assign('default_collation', $default_collation = 'collate utf8_unicode_ci'); tpl_assign('default_charset', $default_charset = 'DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci'); } else { tpl_assign('default_collation', $default_collation = ''); tpl_assign('default_charset', $default_charset = ''); } // if $installed_version = installed_version(); $t_prefix = TABLE_PREFIX; if (version_compare($installed_version, '1.7.5') <= 0 && TABLE_PREFIX != "fo_") { $t_prefix = "fo_"; } tpl_assign('table_prefix', $t_prefix); if (defined('DB_ENGINE')) { tpl_assign('engine', DB_ENGINE); } else { tpl_assign('engine', 'InnoDB'); } // --------------------------------------------------- // Execute migration // --------------------------------------------------- $additional_upgrade_steps = array(); // RUN QUERIES $total_queries = 0; $executed_queries = 0; $upgrade_script = ""; // upgrading from version 1.x if (version_compare($installed_version, '2.0.0.0-beta') < 0) { ini_set('memory_limit', '1024M'); @set_time_limit(0); $upgrade_script .= tpl_fetch(get_template_path('db_migration/2_0_asado')); if ($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) { $this->printMessage("Database schema transformations executed (total queries: {$total_queries})"); } else { $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true); return false; } $_SESSION['from_feng1'] = true; $upgrade_script = ""; @unlink(ROOT . '/cache/autoloader.php'); include ROOT . '/environment/classes/AutoLoader.class.php'; include ROOT . '/environment/constants.php'; if (!($callbacks = spl_autoload_functions())) { $callbacks = array(); } foreach ($callbacks as $callback) { spl_autoload_unregister($callback); } spl_autoload_register('feng_upg_autoload'); foreach ($callbacks as $callback) { spl_autoload_register($callback); } @(include ROOT . '/cache/autoloader.php'); define('DONT_LOG', true); define('FORCED_TABLE_PREFIX', 'fo_'); if (!defined('FILE_STORAGE_FILE_SYSTEM')) { define('FILE_STORAGE_FILE_SYSTEM', 'fs'); } if (!defined('FILE_STORAGE_MYSQL')) { define('FILE_STORAGE_MYSQL', 'mysql'); } if (!defined('MAX_SEARCHABLE_FILE_SIZE')) { define('MAX_SEARCHABLE_FILE_SIZE', 1048576); } try { DB::connect(DB_ADAPTER, array('host' => DB_HOST, 'user' => DB_USER, 'pass' => DB_PASS, 'name' => DB_NAME, 'persist' => DB_PERSIST)); if (defined('DB_CHARSET') && trim(DB_CHARSET)) { DB::execute("SET NAMES ?", DB_CHARSET); } } catch (Exception $e) { $this->printMessage("Error connecting to database: " . $e->getMessage() . "\n" . $e->getTraceAsString()); } try { $db_result = DB::execute("SELECT value FROM " . $t_prefix . "config_options WHERE name = 'file_storage_adapter'"); $db_result_row = $db_result->fetchRow(); if ($db_result_row['value'] == FILE_STORAGE_FILE_SYSTEM) { if (!defined('FILES_DIR')) { define('FILES_DIR', ROOT . '/upload'); } FileRepository::setBackend(new FileRepository_Backend_FileSystem(FILES_DIR, TABLE_PREFIX)); } else { FileRepository::setBackend(new FileRepository_Backend_DB(TABLE_PREFIX)); } PublicFiles::setRepositoryPath(ROOT . '/public/files'); if (!defined('PUBLIC_FOLDER')) { define('PUBLIC_FOLDER', 'public'); } if (trim(PUBLIC_FOLDER) == '') { PublicFiles::setRepositoryUrl(with_slash(ROOT_URL) . 'files'); } else { PublicFiles::setRepositoryUrl(with_slash(ROOT_URL) . 'public/files'); } $member_parents = array(); $members = Members::findAll(); foreach ($members as $member) { $member_parents[$member->getId()] = $member->getAllParentMembersInHierarchy(false, false); } $object_members = DB::executeAll('SELECT * FROM ' . $t_prefix . 'object_members WHERE is_optimization=0 and not exists (SELECT x.object_id FROM ' . $t_prefix . 'object_members x where x.object_id=fo_object_members.object_id and x.is_optimization=1)'); foreach ($object_members as $om) { $parents = isset($member_parents[$om['member_id']]) ? $member_parents[$om['member_id']] : array(); if (count($parents) > 0) { $sql_values = ""; foreach ($parents as $p) { $sql_values .= ($sql_values == "" ? "" : ",") . "(" . $om['object_id'] . "," . $p->getId() . ",1)"; } $sql = "INSERT INTO " . $t_prefix . "object_members (object_id, member_id, is_optimization) VALUES {$sql_values} ON DUPLICATE KEY UPDATE is_optimization=1;"; DB::execute($sql); } } $this->printMessage("Finished generating Object Members"); foreach ($members as $m) { if ($m->getParentMember() instanceof Member && $m->getDimensionId() != $m->getParentMember()->getDimensionId()) { $m->setDimensionId($m->getParentMember()->getDimensionId()); $m->save(); } } $app_move_logs = ApplicationLogs::findAll(array("conditions" => "action = 'move'")); foreach ($app_move_logs as &$app_log) { /* @var $app_log ApplicationLog */ $exp_log_data = explode(";", $app_log->getLogData()); if (count($exp_log_data) > 1) { $old_to = array_var($exp_log_data, 1); $old_from = array_var($exp_log_data, 0); } else { $old_to = array_var($exp_log_data, 0); $old_from = ""; } $to_id = str_replace("to:", "", $old_to); $new_to_id = Members::instance()->findOne(array("id" => true, "conditions" => "ws_id = '{$to_id}'")); if (count($new_to_id) > 0) { $new_to_id = $new_to_id[0]; } $new_from_ids = ""; $from_ids = str_replace("from:", "", $old_from); if ($from_ids != "") { $new_from_ids_array = Members::instance()->findAll(array("id" => true, "conditions" => "ws_id IN ({$from_ids})")); $new_from_ids = implode(",", $new_from_ids_array); } if ($new_to_id) { if ($new_from_ids) { $log_data = "from:{$new_from_ids};to:{$new_to_id}"; } else { $log_data = "to:{$new_to_id}"; } $app_log->setLogData($log_data); $app_log->save(); } } } catch (Exception $e) { die("\nError occurred:\n-----------------\n" . $e->getMessage() . "\n" . $e->getTraceAsString()); } //tpl_assign('install_inv_dw', true); $additional_upgrade_steps[] = array('url' => 'complete_migration.php?out=file', 'name' => 'Fill searchable objects and sharing table', 'filename' => dirname(__FILE__) . "/../complete_migration.php"); } else { // upgrading from a pre-release of this version (beta, rc, etc) if (version_compare($installed_version, '2.0.0.4') <= 0) { if (!$this->checkTableExists($t_prefix . 'role_object_type_permissions', $this->database_connection)) { $upgrade_script .= "\r\n\t\t\t\t\t\tCREATE TABLE `" . $t_prefix . "role_object_type_permissions` (\r\n\t\t\t\t\t\t `role_id` INTEGER UNSIGNED NOT NULL,\r\n\t\t\t\t\t\t `object_type_id` INTEGER UNSIGNED NOT NULL,\r\n\t\t\t\t\t\t `can_delete` BOOLEAN NOT NULL,\r\n\t\t\t\t\t\t `can_write` BOOLEAN NOT NULL,\r\n\t\t\t\t\t\t PRIMARY KEY (`role_id`, `object_type_id`)\r\n\t\t\t\t\t\t) ENGINE = InnoDB;\r\n\t\t\t\t\t\tINSERT INTO " . $t_prefix . "role_object_type_permissions (role_id, object_type_id, can_delete, can_write)\r\n\t\t\t\t\t\t SELECT p.id, o.id, 1, 1\r\n\t\t\t\t\t\t FROM `" . $t_prefix . "object_types` o JOIN `" . $t_prefix . "permission_groups` p\r\n\t\t\t\t\t\t WHERE o.`name` IN ('message','weblink','file','task','milestone','event','contact','mail','timeslot','report','comment')\r\n\t\t\t\t\t\t AND p.`name` IN ('Super Administrator','Administrator','Manager','Executive');\r\n\t\t\t\t\t\tINSERT INTO " . $t_prefix . "role_object_type_permissions (role_id, object_type_id, can_delete, can_write)\r\n\t\t\t\t\t\t SELECT p.id, o.id, 0, 1\r\n\t\t\t\t\t\t FROM `" . $t_prefix . "object_types` o JOIN `" . $t_prefix . "permission_groups` p\r\n\t\t\t\t\t\t WHERE o.`name` IN ('message','weblink','file','task','milestone','event','contact','timeslot','report','comment')\r\n\t\t\t\t\t\t AND p.`name` IN ('Collaborator Customer');\r\n\t\t\t\t\t\tINSERT INTO " . $t_prefix . "role_object_type_permissions (role_id, object_type_id, can_delete, can_write)\r\n\t\t\t\t\t\t SELECT p.id, o.id, 0, 1\r\n\t\t\t\t\t\t FROM `" . $t_prefix . "object_types` o JOIN `" . $t_prefix . "permission_groups` p\r\n\t\t\t\t\t\t WHERE o.`name` IN ('message','weblink','file','task','milestone','event','timeslot','comment')\r\n\t\t\t\t\t\t AND p.`name` IN ('Internal Collaborator','External Collaborator');\r\n\t\t\t\t\t\tINSERT INTO " . $t_prefix . "role_object_type_permissions (role_id, object_type_id, can_delete, can_write)\r\n\t\t\t\t\t\t SELECT p.id, o.id, 0, 0\r\n\t\t\t\t\t\t FROM `" . $t_prefix . "object_types` o JOIN `" . $t_prefix . "permission_groups` p\r\n\t\t\t\t\t\t WHERE o.`name` IN ('message','weblink','file','event','comment')\r\n\t\t\t\t\t\t AND p.`name` IN ('Guest Customer');\r\n\t\t\t\t\t\tINSERT INTO " . $t_prefix . "role_object_type_permissions (role_id, object_type_id, can_delete, can_write)\r\n\t\t\t\t\t\t SELECT p.id, o.id, 0, 0\r\n\t\t\t\t\t\t FROM `" . $t_prefix . "object_types` o JOIN `" . $t_prefix . "permission_groups` p\r\n\t\t\t\t\t\t WHERE o.`name` IN ('message','weblink','event','comment')\r\n\t\t\t\t\t\t AND p.`name` IN ('Guest');\r\n\t\t\t\t\t\tINSERT INTO " . $t_prefix . "role_object_type_permissions (role_id, object_type_id, can_delete, can_write)\r\n\t\t\t\t\t\t SELECT p.id, o.id, 0, 0\r\n\t\t\t\t\t\t FROM `" . $t_prefix . "object_types` o JOIN `" . $t_prefix . "permission_groups` p\r\n\t\t\t\t\t\t WHERE o.`name` IN ('message','weblink','file','task','milestone','event','contact','timeslot','report','comment')\r\n\t\t\t\t\t\t AND p.`name` IN ('Non-Exec Director');\r\n\t\t\t\t\t\tUPDATE " . $t_prefix . "role_object_type_permissions SET can_write = 1 WHERE object_type_id = (SELECT id FROM " . $t_prefix . "object_types WHERE name='comment');\r\n\t\t\t\t\t"; } if (!$this->checkTableExists($t_prefix . 'widgets', $this->database_connection)) { $upgrade_script .= "\r\n\t\t\t\t\t\tCREATE TABLE `" . $t_prefix . "widgets` (\r\n\t\t\t\t\t\t `name` varchar(64) NOT NULL,\r\n\t\t\t\t\t\t `title` varchar(255) NOT NULL,\r\n\t\t\t\t\t\t `plugin_id` int(10) unsigned NOT NULL,\r\n\t\t\t\t\t\t `path` varchar(512) NOT NULL,\r\n\t\t\t\t\t\t `default_options` text NOT NULL,\r\n\t\t\t\t\t\t `default_section` varchar(64) NOT NULL,\r\n\t\t\t\t\t\t `default_order` int(10) NOT NULL,\r\n\t\t\t\t\t\t PRIMARY KEY (`name`)\r\n\t\t\t\t\t\t) ENGINE = InnoDB;\r\n\t\t\t\t\t"; } if ($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) { $this->printMessage("Database schema transformations executed (total queries: {$total_queries})"); } else { $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true); return false; } } if (version_compare($installed_version, '2.0.0.5') <= 0) { if (!$this->checkColumnExists($t_prefix . 'contacts', 'default_billing_id', $this->database_connection)) { $upgrade_script = "\r\n\t\t\t\t\t\tALTER TABLE `" . $t_prefix . "contacts` ADD COLUMN `default_billing_id` INTEGER NOT NULL DEFAULT 0;\r\n\t\t\t\t\t\tALTER TABLE `" . $t_prefix . "project_tasks`\r\n\t\t\t\t\t\t ADD COLUMN `use_due_time` BOOLEAN DEFAULT 0,\r\n\t\t\t\t\t\t ADD COLUMN `use_start_time` BOOLEAN DEFAULT 0;\r\n\t\t\t\t\t\tUPDATE " . $t_prefix . "project_tasks t SET\r\n\t\t\t\t\t\t t.due_date = ADDTIME(t.due_date, CONCAT(SUBSTRING_INDEX((SELECT c.timezone FROM " . $t_prefix . "contacts c WHERE c.object_id=(SELECT o.updated_by_id FROM " . $t_prefix . "objects o WHERE o.id=t.object_id)), '.', 1), ':', SUBSTRING_INDEX(abs((SELECT c.timezone FROM " . $t_prefix . "contacts c WHERE c.object_id=(SELECT o.updated_by_id FROM " . $t_prefix . "objects o WHERE o.id=t.object_id)) % 1)*60, '.', 1)))\r\n\t\t\t\t\t\t WHERE t.due_date > 0;\r\n\t\t\t\t\t\tUPDATE " . $t_prefix . "project_tasks t SET\r\n\t\t\t\t\t\t t.start_date = ADDTIME(t.start_date, CONCAT(SUBSTRING_INDEX((SELECT c.timezone FROM " . $t_prefix . "contacts c WHERE c.object_id=(SELECT o.updated_by_id FROM " . $t_prefix . "objects o WHERE o.id=t.object_id)), '.', 1), ':', SUBSTRING_INDEX(abs((SELECT c.timezone FROM " . $t_prefix . "contacts c WHERE c.object_id=(SELECT o.updated_by_id FROM " . $t_prefix . "objects o WHERE o.id=t.object_id)) % 1)*60, '.', 1)))\r\n\t\t\t\t\t\t WHERE t.start_date > 0;\r\n\t\t\t\t\t\tINSERT INTO `" . $t_prefix . "contact_config_options` (`category_name`, `name`, `default_value`, `config_handler_class`, `is_system`, `option_order`, `dev_comment`) VALUES\r\n\t\t\t\t\t\t ('general', 'work_day_end_time', '18:00', 'TimeConfigHandler', 0, 410, 'Work day end time');\t\t\t\t\t\t\r\n\t\t\t\t\t"; } if ($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) { $this->printMessage("Database schema transformations executed (total queries: {$total_queries})"); } else { $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true); return false; } } if (version_compare($installed_version, '2.0.0.6') <= 0) { //WS Widgets $upgrade_script = "\r\n\t\t\t\t\tUPDATE `" . $t_prefix . "contact_config_options` SET `default_value` = '15' WHERE `" . $t_prefix . "contact_config_options`.`name` = 'noOfTasks' LIMIT 1 ;\r\n\t\t\t\t\tUPDATE " . $t_prefix . "widgets SET default_section = 'none' WHERE name = 'people' AND NOT EXISTS (SELECT id from " . $t_prefix . "plugins WHERE name = 'crpm');\r\n\t\t\t\t\tUPDATE " . $t_prefix . "dimensions SET options = '{\"defaultAjax\":{\"controller\":\"dashboard\", \"action\": \"main_dashboard\"}, \"quickAdd\":true,\"showInPaths\":true}' \r\n\t\t\t\t\t\tWHERE code='workspaces';\r\n\t\t\t\t\tUPDATE `" . $t_prefix . "tab_panels` SET default_action = 'main_dashboard', initial_action = 'main_dashboard'\r\n\t\t\t\t\t\tWHERE id = 'overview-panel' ;\r\n\t\t\t\t\tUPDATE " . $t_prefix . "object_types SET type = 'dimension_object', handler_class='Workspaces', table_name = 'workpaces' WHERE name = 'workspace' ;\r\n\t\t\t\t\tUPDATE " . $t_prefix . "dimension_object_types SET OPTIONS = '{\"defaultAjax\":{\"controller\":\"dashboard\", \"action\": \"main_dashboard\"}}' \r\n\t\t\t\t\t\tWHERE dimension_id = (SELECT id FROM " . $t_prefix . "dimensions WHERE code = 'workspaces');\r\n\t\t\t\t\tCREATE TABLE IF NOT EXISTS `" . $t_prefix . "contact_widgets` (\r\n\t\t\t\t\t `widget_name` varchar(40) NOT NULL,\r\n\t\t\t\t\t `contact_id` int(11) NOT NULL,\r\n\t\t\t\t\t `section` varchar(40) NOT NULL,\r\n\t\t\t\t\t `order` int(11) NOT NULL,\r\n\t\t\t\t\t `options` varchar(255) NOT NULL,\r\n\t\t\t\t\t PRIMARY KEY (`widget_name`,`contact_id`) USING BTREE\r\n\t\t\t\t\t) ENGINE=InnoDB;\r\n\t\t\t\t\tINSERT INTO " . $t_prefix . "widgets(name, title, plugin_id, default_section,default_order) \r\n\t\t\t\t\t VALUES ('messages','notes',0,'none',1000)\r\n\t\t\t\t\t ON DUPLICATE KEY update name = name;\r\n\t\t\t\t\tINSERT INTO " . $t_prefix . "dimension_object_type_contents (dimension_id, dimension_object_type_id, content_object_type_id, is_required, is_multiple)\r\n\t\t\t\t\t SELECT d.id, ot.id, (SELECT tmp.id FROM " . $t_prefix . "object_types tmp WHERE tmp.name='contact'), 0, 1\r\n\t\t\t\t\t FROM " . $t_prefix . "dimensions d JOIN " . $t_prefix . "object_types ot\r\n\t\t\t\t\t WHERE d.code = 'customer_project' AND ot.name IN ('customer', 'project', 'folder', 'customer_folder', 'project_folder')\r\n\t\t\t\t\tON DUPLICATE KEY UPDATE dimension_id=dimension_id;\r\n\t\t\t\t\tUPDATE " . $t_prefix . "dimension_object_type_contents SET is_multiple = 1 WHERE content_object_type_id = (SELECT id FROM " . $t_prefix . "object_types WHERE name='mail');\r\n\t\t\t\t"; if (@mysql_fetch_row(@mysql_query("SELECT id from " . $t_prefix . "plugins WHERE name = 'workspaces'"))) { $upgrade_script .= "INSERT INTO " . $t_prefix . "widgets(name, title, plugin_id, default_section,default_order) \r\n\t\t\t\t\t\tVALUES ('ws_description', 'workspace description',(SELECT id from " . $t_prefix . "plugins WHERE name = 'workspaces'), 'left',-100)\r\n\t\t\t\t\t\tON DUPLICATE KEY update name = name ;"; } if ($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) { $this->printMessage("Database schema transformations executed (total queries: {$total_queries})"); } else { $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true); return false; } if ($obj = @mysql_fetch_object(@mysql_query("SELECT id FROM " . $t_prefix . "object_types WHERE name = 'workspace' "))) { $wsTypeId = $obj->id; $res = @mysql_query("SELECT * FROM " . $t_prefix . "members WHERE dimension_id = (SELECT id FROM " . $t_prefix . "dimensions WHERE code='workspaces')"); while ($m = @mysql_fetch_object($res)) { @mysql_query("INSERT INTO " . $t_prefix . "objects (object_type_id, name) VALUES ({$wsTypeId}, '" . $m->name . "' )"); if ($id = @mysql_insert_id()) { @mysql_query("INSERT INTO " . $t_prefix . "workspaces (object_id) VALUES ({$id})"); @mysql_query("UPDATE " . $t_prefix . "members SET object_id={$id} WHERE id = {$m->id} "); } } } } if (version_compare($installed_version, '2.0.0.7') <= 0) { $upgrade_script = ""; if (!$this->checkTableExists($t_prefix . 'mail_spam_filters', $this->database_connection)) { $upgrade_script .= "\r\n CREATE TABLE IF NOT EXISTS `" . $t_prefix . "mail_spam_filters` (\r\n `id` int(10) unsigned NOT NULL AUTO_INCREMENT,\r\n `account_id` int(10) unsigned NOT NULL,\r\n `text_type` enum('email_address','subject') COLLATE utf8_unicode_ci NOT NULL,\r\n `text` text COLLATE utf8_unicode_ci NOT NULL,\r\n `spam_state` enum('no spam','spam') COLLATE utf8_unicode_ci NOT NULL,\r\n PRIMARY KEY (`id`)\r\n ) ENGINE=InnoDB;\r\n "; } $upgrade_script .= "INSERT INTO `" . $t_prefix . "config_options` (`category_name`, `name`, `value`, `config_handler_class`, `is_system`, `option_order`, `dev_comment`) \r\n\t\t\t\t\tVALUES ('general', 'untitled_notes', '0', 'BoolConfigHandler', '0', '0', NULL) ON DUPLICATE KEY UPDATE name=name;"; if ($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) { $this->printMessage("Database schema transformations executed (total queries: {$total_queries})"); } else { $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true); return false; } } if (version_compare($installed_version, '2.0.0.8') < 0) { $upgrade_script = ""; if (!$this->checkTableExists($t_prefix . 'external_calendar_users', $this->database_connection)) { $upgrade_script .= "\r\n CREATE TABLE IF NOT EXISTS `" . $t_prefix . "external_calendar_users` (\r\n `id` int(10) unsigned NOT NULL AUTO_INCREMENT,\r\n `contact_id` int(10) unsigned NOT NULL,\r\n `auth_user` varchar(100) COLLATE utf8_unicode_ci NOT NULL,\r\n `auth_pass` varchar(100) COLLATE utf8_unicode_ci NOT NULL,\r\n `type` text COLLATE utf8_unicode_ci NOT NULL,\r\n `sync` TINYINT( 1 ) NULL DEFAULT '0',\r\n PRIMARY KEY (`id`)\r\n ) ENGINE = InnoDB;\r\n\t\t\t\t\t"; } if (!$this->checkTableExists($t_prefix . 'external_calendars', $this->database_connection)) { $upgrade_script .= "\r\n CREATE TABLE IF NOT EXISTS `" . $t_prefix . "external_calendars` (\r\n `id` int(10) unsigned NOT NULL AUTO_INCREMENT,\r\n `ext_cal_user_id` int(10) unsigned NOT NULL,\r\n `calendar_user` varchar(255) COLLATE utf8_unicode_ci NOT NULL,\r\n `calendar_visibility` varchar(255) COLLATE utf8_unicode_ci NOT NULL,\r\n `calendar_name` text COLLATE utf8_unicode_ci NOT NULL,\r\n `calendar_feng` TINYINT( 1 ) NOT NULL DEFAULT '0',\r\n PRIMARY KEY (`id`)\r\n ) ENGINE = InnoDB;\r\n\t\t\t\t\t"; } if (!$this->checkColumnExists($t_prefix . 'project_events', 'ext_cal_id', $this->database_connection)) { $upgrade_script .= "\r\n\t\t\t\t\t\tALTER TABLE `" . $t_prefix . "project_events` ADD `ext_cal_id` INT(10) UNSIGNED NOT NULL;\r\n\t\t\t\t\t"; } $upgrade_script .= "\r\n\t\t\t\t\tALTER TABLE `" . $t_prefix . "project_events` CHANGE `special_id` `special_id` VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL;\r\n\t\t\t\t\tUPDATE `" . $t_prefix . "file_types` SET `is_searchable` = '1' WHERE `extension` = 'docx';\r\n\t\t\t\t\tUPDATE `" . $t_prefix . "file_types` SET `is_searchable` = '1' WHERE `extension` = 'pdf';\r\n\t\t\t\t\tINSERT INTO `" . $t_prefix . "config_options` (`category_name`, `name`, `value`, `config_handler_class`, `is_system`, `option_order`, `dev_comment`)\r\n\t\t\t\t\t\tVALUES ('general', 'repeating_task', '0', 'BoolConfigHandler', '0', '0', '')\r\n\t\t\t\t\tON DUPLICATE KEY UPDATE name=name;\r\n\t\t\t\t\tINSERT INTO `" . $t_prefix . "contact_config_options` (`category_name`, `name`, `default_value`, `config_handler_class`, `is_system`, `option_order`, `dev_comment`)\r\n\t\t\t\t\t\tVALUES ('calendar panel', 'calendar task filter', 'pending', 'StringConfigHandler', '1', '0', NULL),\r\n\t\t\t\t\t\t\t('task panel', 'close timeslot open', '1', 'BoolConfigHandler', '0', '0', NULL),\r\n\t\t\t\t\t\t\t('calendar panel', 'reminders_events', 'reminder_email,1,60', 'StringConfigHandler', '0', '0', NULL)\r\n\t\t\t\t\tON DUPLICATE KEY UPDATE name=name;\r\n\t\t\t\t\tINSERT INTO `" . $t_prefix . "cron_events` (`name`, `recursive`, `delay`, `is_system`, `enabled`, `date`)\r\n\t\t\t\t\t\tVALUES ('import_google_calendar', '1', '10', '0', '0', '0000-00-00 00:00:00'),\r\n\t\t\t\t\t\t\t('export_google_calendar', '1', '10', '0', '0', '0000-00-00 00:00:00')\r\n\t\t\t\t\tON DUPLICATE KEY UPDATE name=name;\r\n\t\t\t\t\t"; $upgrade_script .= "\r\n\t\t\t\t\tDELETE FROM `" . $t_prefix . "config_options` WHERE `name`='use_time_in_task_dates' AND NOT EXISTS (SELECT id FROM `" . $t_prefix . "plugins` WHERE `name`='crpm' AND is_activated=1);\r\n\t\t\t\t\tINSERT INTO " . $t_prefix . "contact_config_options (category_name, name, default_value, config_handler_class, is_system, option_order) VALUES\r\n\t\t\t\t\t\t('general','show_object_direct_url',0,'BoolConfigHandler',0,0),\r\n\t\t\t\t\t\t('general','drag_drop_prompt','prompt','DragDropPromptConfigHandler',0,0)\r\n\t\t\t\t\t ON DUPLICATE KEY UPDATE name = name;\r\n\t\t\t\t"; $upgrade_script .= "\r\n\t\t\t\t\tINSERT INTO `" . $t_prefix . "tab_panels` (`id`,`title`,`icon_cls`,`refresh_on_context_change`,`default_controller`,`default_action`,`initial_controller`,`initial_action`,`enabled`,`type`,`ordering`,`plugin_id`,`object_type_id`) VALUES \r\n\t\t\t\t\t('contacts-panel','contacts','ico-contacts',1,'contact','init','','',0,'system',7,0,16) ON DUPLICATE KEY UPDATE title=title;\r\n\t\t\t\t"; if ($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) { $this->printMessage("Database schema transformations executed (total queries: {$total_queries})"); } else { $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true); return false; } } if (version_compare($installed_version, '2.0.1') < 0) { $upgrade_script = ""; $upgrade_script .= "INSERT INTO `" . $t_prefix . "config_options` (`category_name`, `name`, `value`, `config_handler_class`, `is_system`, `option_order`, `dev_comment`)\r\n\t\t\t\t\tVALUES ('general', 'working_days', '1,2,3,4,5,6,7', 'StringConfigHandler', '0', '0', NULL);\r\n\t\t\t\t\tALTER TABLE `" . $t_prefix . "project_tasks` ADD `original_task_id` INT( 10 ) UNSIGNED NULL DEFAULT '0';\r\n\t\t\t\t\tALTER TABLE `" . $t_prefix . "project_tasks` ADD `type_content` ENUM( 'text', 'html' ) NOT NULL DEFAULT 'text';\r\n\t\t\t\t\tALTER TABLE `" . $t_prefix . "project_events` ADD `original_event_id` INT( 10 ) UNSIGNED NULL DEFAULT '0';\r\n\t\t\t\t\tALTER TABLE `" . $t_prefix . "project_messages` ADD `type_content` ENUM( 'text', 'html' ) NOT NULL DEFAULT 'text';\r\n\t\t\t\t"; $upgrade_script .= "INSERT INTO `" . $t_prefix . "config_options` (`category_name`, `name`, `value`, `config_handler_class`, `is_system`, `option_order`, `dev_comment`)\r\n\t\t\t\t\tVALUES ('general', 'wysiwyg_tasks', '0', 'BoolConfigHandler', '0', '0', NULL),\r\n\t\t\t\t\t('general', 'wysiwyg_messages', '0', 'BoolConfigHandler', '0', '0', NULL),\r\n\t\t\t\t\t('task panel', 'tasksShowTimeEstimates', '1', 'BoolConfigHandler', '1', '0', NULL)\r\n\t\t\t\tON DUPLICATE KEY UPDATE name=name;\r\n\t\t\t\t"; $upgrade_script .= "UPDATE `" . $t_prefix . "widgets` SET plugin_id = (SELECT id FROM `" . $t_prefix . "plugins` WHERE name='workspaces') WHERE name='workspaces';\r\n\t\t\t\t"; // clean old users dimension $upgrade_script .= "DELETE FROM `" . $t_prefix . "object_members` WHERE member_id IN (SELECT `id` FROM `" . $t_prefix . "members` WHERE `dimension_id` IN (SELECT `id` FROM `" . $t_prefix . "dimensions` WHERE `code`='feng_users'));\r\n\t\t\t\t\tDELETE FROM `" . $t_prefix . "contact_dimension_permissions` WHERE dimension_id IN (SELECT `id` FROM `" . $t_prefix . "dimensions` WHERE `code`='feng_users');\r\n\t\t\t\t\tDELETE FROM `" . $t_prefix . "members` WHERE dimension_id IN (SELECT `id` FROM `" . $t_prefix . "dimensions` WHERE `code`='feng_users');\r\n\t\t\t\t\tDELETE FROM `" . $t_prefix . "dimension_object_type_contents` WHERE dimension_id IN (SELECT `id` FROM `" . $t_prefix . "dimensions` WHERE `code`='feng_users');\r\n\t\t\t\t\tDELETE FROM `" . $t_prefix . "dimension_object_type_hierarchies` WHERE dimension_id IN (SELECT `id` FROM `" . $t_prefix . "dimensions` WHERE `code`='feng_users');\r\n\t\t\t\t\tDELETE FROM `" . $t_prefix . "dimension_object_types` WHERE dimension_id IN (SELECT `id` FROM `" . $t_prefix . "dimensions` WHERE `code`='feng_users');\r\n\t\t\t\t\tDELETE FROM `" . $t_prefix . "dimensions` WHERE code='feng_users';\r\n\t\t\t\t\tDELETE FROM `" . $t_prefix . "object_types` WHERE name='user';\r\n\t\t\t\t\tUPDATE " . $t_prefix . "contacts c SET c.personal_member_id = 0 WHERE c.user_type>0 AND NOT (SELECT count(m2.id) FROM " . $t_prefix . "members m2 WHERE m2.object_id=c.personal_member_id)=0;\r\n\t\t\t\t"; if ($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) { $this->printMessage("Database schema transformations executed (total queries: {$total_queries})"); } else { $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true); return false; } } // Plugin Version Support $upgrade_script = ''; if (!$this->checkColumnExists($t_prefix . "plugins", 'version', $this->database_connection)) { $upgrade_script = 'ALTER TABLE ' . $t_prefix . 'plugins ADD COLUMN `version` INTEGER NOT NULL DEFAULT 1 AFTER `name` '; if ($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) { $this->printMessage("Database schema transformations executed (total queries: {$total_queries})"); } else { $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true); return false; } } } $this->printMessage('Feng Office has been upgraded. You are now running Feng Office ' . $this->getVersionTo() . ' Enjoy!'); tpl_assign('additional_steps', $additional_upgrade_steps); }
/** * Returns the mail content. If it is in repository returns the file content, * else tries to get the content from database (if column content exists). * @access public * @param void * @return string */ function getContent() { if (FileRepository::isInRepository($this->getContentFileId())) { return FileRepository::getFileContent($this->getContentFileId()); //return FileRepository::getFileContent($this->getContentFileId(), config_option('file_storage_adapter')); } else if ($this->getMailData()->columnExists('content')) { return $this->getMailData()->getContent(); } }
/** * Download a file from the file repository. * * @param string $id * @param string $type * @param string $name * @param boolean $force_download * @return boolean */ function download_from_repository($id, $type, $name, $force_download = false) { if (FileRepository::getBackend() instanceof FileRepository_Backend_FileSystem) { $path = FileRepository::getBackend()->getFilePath($id); if (is_file($path)) { // this method allows downloading big files without exhausting php's memory return download_file($path, $type, $name, $force_download); } } $content = FileRepository::getBackend()->getFileContent($id); return download_contents($content, $type, $name, strlen($content), $force_download); }
/** * This function will process uploaded file * * @param array $uploaded_file * @param boolean $create_revision Create new revision or update last one * @param string $revision_comment Revision comment, if any * @return ProjectFileRevision */ function handleUploadedFile($uploaded_file, $create_revision = true, $revision_comment = '') { $revision = null; if (!$create_revision) { $revision = $this->getLastRevision(); } // if if (!$revision instanceof ProjectFileRevision) { $revision = new ProjectFileRevision(); $revision->setFileId($this->getId()); $revision->setRevisionNumber($this->getNextRevisionNumber()); if (trim($revision_comment) == '' && $this->countRevisions() < 1) { $revision_comment = lang('initial versions'); } // if } // if $revision->deleteThumb(false); // remove thumb // We have a file to handle! //executes only while uploading files if (!is_array($uploaded_file) || !isset($uploaded_file['name']) || !isset($uploaded_file['size']) || !isset($uploaded_file['type']) || (!isset($uploaded_file['tmp_name']) || !is_readable($uploaded_file['tmp_name']))) { throw new InvalidUploadError($uploaded_file); } // if if (isset($uploaded_file['error']) && $uploaded_file['error'] > UPLOAD_ERR_OK) { throw new InvalidUploadError($uploaded_file); } // if //eyedoc MOD $extension = get_file_extension(basename($uploaded_file['name'])); if ($uploaded_file['type'] == 'application/octet-stream' && $extension == 'eyedoc') { $uploaded_file['type'] = 'text/html'; } //eyedoc MOD // calculate hash if ($revision->columnExists('hash')) { $hash = hash_file("sha256", $uploaded_file['tmp_name']); $revision->setColumnValue('hash', $hash); } $repository_id = FileRepository::addFile($uploaded_file['tmp_name'], array('name' => $uploaded_file['name'], 'type' => $uploaded_file['type'], 'size' => $uploaded_file['size'])); $revision->setRepositoryId($repository_id); $revision->deleteThumb(false); $revision->setFilesize($uploaded_file['size']); if (config_option('detect_mime_type_from_extension')) { $type = Mime_Types::instance()->get_type($extension); if ($type) { $revision->setTypeString($type); } else { $revision->setTypeString($uploaded_file['type']); } } else { $revision->setTypeString($uploaded_file['type']); } if (trim($extension)) { $file_type = FileTypes::getByExtension($extension); if ($file_type instanceof Filetype) { $revision->setFileTypeId($file_type->getId()); } // if } // if $revision->setComment($revision_comment); $revision->save(); $this->last_revision = $revision; // update last revision return $revision; }
/** * Check if this user has uploaded picture * * @access public * @param void * @return boolean */ function hasPicture() { return (trim($this->getPictureFile()) <> '') && FileRepository::isInRepository($this->getPictureFile()); } // hasPicture