/**
  * 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);
     // ---------------------------------------------------
     //  Execute migration
     // ---------------------------------------------------
     $total_queries = 0;
     $executed_queries = 0;
     $upgrade_script = tpl_fetch(get_template_path('db_migration/1_0_milanga'));
     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
     $this->printMessage('Feng Office has been upgraded. You are now running Feng Office ' . $this->getVersionTo() . ' Enjoy!');
 }
Example #2
0
/**
 * Advanced pagination. Differenced between simple and advanced paginations is that 
 * advanced pagination uses template so its output can be changed in a great number of ways.
 * 
 * All variables are just passed to the template, nothing is done inside the function!
 *
 * @access public
 * @param DataPagination $pagination Pagination object
 * @param string $url_base Base URL in witch we will insert current page number
 * @param string $template Template that will be used. It can be absolute path to existing file
 *   or template name that used with get_template_path will return real template path
 * @param string $page_placeholder Short string inside of $url_base that will be replaced with
 *   current page numer
 * @return null
 */
function advanced_pagination(DataPagination $pagination, $url_base, $template = 'advanced_pagination', $page_placeholder = '#PAGE#')
{
    tpl_assign(array('advanced_pagination_object' => $pagination, 'advanced_pagination_url_base' => $url_base, 'advanced_pagination_page_placeholder' => urlencode($page_placeholder)));
    // tpl_assign
    $template_path = is_file($template) ? $template : get_template_path($template);
    return tpl_fetch($template_path);
}
/**
 * Include layout
 * 
 * Parameters:
 * 
 * - name - layout name
 * - module - module name
 *
 * @param array $params
 * @param Smarty $smarty
 * @return null
 */
function smarty_function_include_layout($params, &$smarty)
{
    $name = array_var($params, 'name');
    if (empty($name)) {
        return new InvalidParamError('name', $name, "'name' property is required for 'include_layout' helper", true);
    }
    // if
    $module = array_var($params, 'module');
    if (empty($module)) {
        return new InvalidParamError('module', $module, "'module' property is required for 'include_layout' helper", true);
    }
    // if
    return tpl_fetch(get_layout_path($name, $module));
}
Example #4
0
/**
 * Checks whether the user is logged in and if not returns an error response.
 *
 */
function ajx_check_login()
{
    if (is_ajax_request() && !logged_user() instanceof Contact && (array_var($_GET, 'c') != 'access' || array_var($_GET, 'a') != 'relogin')) {
        // error, user not logged in => return error message
        $response = AjaxResponse::instance();
        $response->setCurrentContent("empty");
        $response->setError(SESSION_EXPIRED_ERROR_CODE, lang("session expired error"));
        // display the object as json
        tpl_assign("object", $response);
        $content = tpl_fetch(Env::getTemplatePath("json"));
        tpl_assign("content_for_layout", $content);
        tpl_display(Env::getLayoutPath("json"));
        exit;
    }
}
 /**
  * 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
     // ---------------------------------------------------
     $total_queries = 0;
     $executed_queries = 0;
     $installed_version = installed_version();
     if (version_compare($installed_version, "1.1") <= 0) {
         $upgrade_script = tpl_fetch(get_template_path('db_migration/1_2_chinchulin'));
     } else {
         $upgrade_script = "DELETE FROM `" . TABLE_PREFIX . "config_options` WHERE `name` = 'time_format_use_24';\r\n\t\t\tUPDATE `" . TABLE_PREFIX . "config_options` SET `category_name` = 'modules' WHERE `name` = 'enable_email_module';\r\n\t\t\tALTER TABLE `" . TABLE_PREFIX . "mail_contents` ADD COLUMN `content_file_id` VARCHAR(40) NOT NULL default '';\r\n\t\t\t";
     }
     @unlink("../../language/de_de/._lang.js");
     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
     $this->printMessage('Feng Office has been upgraded. You are now running Feng Office ' . $this->getVersionTo() . ' Enjoy!');
 }
Example #6
0
function load_help($template){
	$dir = Localization::instance()->getLanguageDirPath().'/'.Localization::instance()->getLocale();
	$help_file = $dir.'/help/'.$template.'.html';
	if(is_file($help_file)){
		return tpl_fetch($help_file);
	}else{
		$default = Localization::instance()->getLanguageDirPath().'/en_us/help/'.$template.'.html';
		if(is_file($default)){
			return tpl_fetch($default);
		}else{
			$noHelp = Localization::instance()->getLanguageDirPath().'/en_us/help/no_help.html';
			if(is_file($noHelp)){
				return tpl_fetch($noHelp);
			}else{
				return '';
			}
		}
	}	
}
 /**
  * Set page sidebar
  *
  * @access public
  * @param string $template Path of sidebar template
  * @return null
  * @throws FileDnxError if $template file does not exists
  */
 protected function setSidebar($template)
 {
     tpl_assign('content_for_sidebar', tpl_fetch($template));
 }
Example #8
0
/**
 * Render one project's application logs
 * 
 * This helper will render array of log entries.
 *
 * @param array $project The project.
 * @param array $log_entries An array of entries for this project.
 * @return null
 */
function render_project_application_logs($project, $log_entries)
{
    tpl_assign('application_logs_project', $project);
    tpl_assign('application_logs_entries', $log_entries);
    return tpl_fetch(get_template_path('render_project_application_logs', 'application'));
}
 /**
  * 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_7_pastafrola'));
     } else {
         // upgrading from a pre-release of this version (beta, rc, etc)
         $upgrade_script = "";
         if (version_compare($installed_version, '1.7-beta') <= 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\t('system', 'notification_from_address', '', 'StringConfigHandler', 1, 0, 'Address to use as from field in email notifications. If empty, users address is used');\r\n\t\t\t\t";
         }
         if (version_compare($installed_version, '1.7-rc') <= 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\t('general', 'use_owner_company_logo_at_header', '0', 'BoolConfigHandler', 0, 0, '')\r\n\t\t\t\t\tON DUPLICATE KEY UPDATE id=id;\r\n\t\t\t\t\tDELETE FROM `" . TABLE_PREFIX . "config_options` WHERE `category_name`='general' AND `name`='detect_mime_type_from_extension';\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', 'detect_mime_type_from_extension', '0', 'BoolConfigHandler', 0, 800, '')\r\n\t\t\t\t\tON DUPLICATE KEY UPDATE id=id;\r\n\t\t\t\t";
         }
         if (version_compare($installed_version, '1.7-rc2') <= 0) {
             $upgrade_script .= "\r\n\t\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "administration_tools` ADD COLUMN `visible` BOOLEAN NOT NULL DEFAULT 1;\r\n\t\t\t\t\tUPDATE `" . TABLE_PREFIX . "administration_tools` SET `visible`=0 WHERE `name`='mass_mailer';\r\n\t\t\t\t";
         }
         if (version_compare($installed_version, '1.7') <= 0) {
             $upgrade_script .= "\r\n\t\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "mail_accounts` \r\n\t\t\t\t\t ADD COLUMN `last_error_date` DATETIME NOT NULL default '0000-00-00 00:00:00',\r\n\t\t\t\t\t ADD COLUMN `last_error_msg` VARCHAR(255) NOT NULL default '',\r\n\t\t\t\t\t ADD COLUMN `sync_addr` VARCHAR( 100 ) NOT NULL default '',\r\n\t\t\t\t\t ADD COLUMN `sync_pass` VARCHAR( 40 ) NOT NULL default '',\r\n\t\t\t\t\t ADD COLUMN `sync_server` VARCHAR( 100 ) NOT NULL default '',\r\n\t\t\t\t\t ADD COLUMN `sync_ssl` BOOL NOT NULL DEFAULT '0',\r\n\t\t\t\t\t ADD COLUMN `sync_ssl_port` INT( 11 ) NOT NULL DEFAULT '993',\r\n\t\t\t\t\t ADD COLUMN `sync_folder` VARCHAR( 100 ) NOT NULL default '';\r\n\t\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "mail_account_users` ADD COLUMN `last_error_state` INT(1) UNSIGNED NOT NULL DEFAULT 0 COMMENT '0:no error,1:err unread, 2:err read';\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 ('mails panel', 'mail_account_err_check_interval', '300', 'IntegerConfigHandler', 0, 120, NULL),\r\n\t\t\t\t\t ('mails panel', 'classify_mail_with_conversation', '1', 'BoolConfigHandler', 0, 130, NULL),\r\n\t\t\t\t\t ('task panel', 'tasksShowEmptyMilestones', '1', 'BoolConfigHandler', 1, 0, '')\r\n\t\t\t\t\tON DUPLICATE KEY UPDATE id=id;\r\n\t\t\t\t\tINSERT INTO `" . TABLE_PREFIX . "file_types` (`extension`, `icon`, `is_searchable`, `is_image`) VALUES\r\n\t\t\t\t\t\t('docx', 'doc.png', 0, 0),\r\n\t\t\t\t\t\t('xlsx', 'xls.png', 0, 0)\r\n\t\t\t\t\tON DUPLICATE KEY UPDATE id=id;\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\t('system', 'min_chars_for_match', '3', 'IntegerConfigHandler', 1, 0, 'If search criteria len is less than this, then use always LIKE'),\r\n\t\t\t\t\t\t('mailing', 'sent_mails_sync', '1', 'BoolConfigHandler', '0', '0', 'imap email accounts synchronization possibility')\r\n\t\t\t\t\tON DUPLICATE KEY UPDATE id=id;\r\n\t\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "application_logs` MODIFY COLUMN `action` enum('upload','open','close','delete','edit','add','trash','untrash','subscribe','unsubscribe','tag','untag','comment','link','unlink','login','logout','archive','unarchive','move','copy','read','download','checkin','checkout') collate utf8_unicode_ci default NULL;\r\n\t\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "mail_contents` ADD COLUMN `sync` BOOL NOT NULL DEFAULT '0';\r\n\t\t\t\t";
         }
         if (version_compare($installed_version, '1.7.2') <= 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\t('passwords', 'block_login_after_x_tries', '0', 'BoolConfigHandler', '0', '20', NULL),\r\n\t\t\t\t\t\t('mailing', 'check_spam_in_subject', '0', 'BoolConfigHandler', 0, 0, '')\r\n\t\t\t\t\tON DUPLICATE KEY UPDATE id=id;\r\n\t\t\t\t";
         }
         if (!$this->checkTableExists(TABLE_PREFIX . 'administration_logs', $this->database_connection)) {
             $upgrade_script .= "\r\n\t\t\t\t\tCREATE TABLE  `" . TABLE_PREFIX . "administration_logs` (\r\n\t\t\t\t\t  `id` int(10) unsigned NOT NULL auto_increment,\r\n\t\t\t\t\t  `created_on` datetime NOT NULL default '0000-00-00 00:00:00',\r\n\t\t\t\t\t  `title` varchar(50) NOT NULL default '',\r\n\t\t\t\t\t  `log_data` text NOT NULL,\r\n\t\t\t\t\t  `category` enum('system','security') NOT NULL,\r\n\t\t\t\t\t  PRIMARY KEY  (`id`),\r\n\t\t\t\t\t  KEY `created_on` (`created_on`),\r\n\t\t\t\t\t  KEY `category` (`category`)\r\n\t\t\t\t\t) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;\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
     $this->printMessage('Feng Office has been upgraded. You are now running Feng Office ' . $this->getVersionTo() . ' Enjoy!');
 }
 /**
  * Set content from template
  *
  * @access public
  * @param void
  * @return null
  */
 function setContentFromTemplate($template)
 {
     tpl_assign('content_for_layout', tpl_fetch(get_template_path($template)));
 }
 /**
  * Write $constants in config file
  *
  * @access public
  * @param array $constants
  * @return boolean
  */
 function writeConfigFile($constants)
 {
     tpl_assign('config_file_constants', $constants);
     return file_put_contents(INSTALLATION_PATH . '/config/config.php', tpl_fetch(get_template_path('config_file.php')));
 }
 /**
  * Render content... If template and/layout are NULL script will resolve 
  * their names based on controller name and action. 
  * 
  * PageController::index will map with:
  *  - template => views/page/index.php
  *  - layout => layouts/page.php
  *
  * @param string $template
  * @param string $layout
  * @param boolean $die
  * @return boolean
  * @throws FileDnxError
  */
 function render($template = null, $layout = null, $die = true)
 {
     trace(__FILE__, "render({$template}, {$layout}, {$die})");
     // Set template and layout...
     if (!is_null($template)) {
         $this->setTemplate($template);
     }
     // if
     if (!is_null($layout)) {
         $this->setLayout($layout);
     }
     // if
     // Get template and layout paths
     $template_path = $this->getTemplatePath();
     $layout_path = $this->getLayoutPath();
     trace(__FILE__, "tpl_fetch({$template_path})");
     // Fetch content...
     $content = tpl_fetch($template_path);
     trace(__FILE__, "renderLayout({$layout_path} <xmp>{$content}</xmp>)");
     // Assign content and render layout
     $this->renderLayout($layout_path, $content);
     // Die!
     if ($die) {
         session_write_close();
         die;
     }
     // if
     // We are done here...
     return true;
 }
Example #13
0
/**
 * 
 * Renders members vinculations for the object
 * @param ContentDataObject $object
 */
function render_co_view_member_path(ContentDataObject $object) {
	tpl_assign('object', $object);
	return tpl_fetch(get_template_path('member_path', 'co'));
}
 /**
  * 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);
 }
 /**
  * Execute upgrade script that is responsible for upgrade process from installed version to target version
  *
  * @param string $version_from
  * @param string $to_version
  * @return null
  */
 function upgrade($version_from, $version_to)
 {
     $scripts = $this->getScripts();
     // check if version_to exists and there's a path from current version to version_to.
     if (is_array($scripts)) {
         // scripts are sorted according to the "to" upgrade version
         $exists = false;
         $current = $version_from;
         foreach ($scripts as $script) {
             if ($script->worksFor($current)) {
                 $current = $script->getVersionTo();
                 if (version_compare($current, $version_to) == 0) {
                     $exists = true;
                     break;
                 }
             }
         }
         // foreach
         if (!$exists) {
             $this->printMessage("There is no upgrade path from version {$version_from} to {$version_to}.");
             return;
         }
         // include config file
         $config_is_set = @(include_once INSTALLATION_PATH . '/config/config.php');
         if (!$config_is_set) {
             $this->printMessage('Valid config file was not found!', true);
             return false;
         } else {
             $this->printMessage('Config file found and loaded.');
         }
         // if
         // check preconditions
         $write_checks = array();
         $ext_checks = array();
         foreach ($scripts as $script) {
             if (version_compare($script->getVersionTo(), $version_from) > 0 && version_compare($script->getVersionTo(), $version_to) <= 0) {
                 $write_checks = array_merge($write_checks, $script->getCheckIsWritable());
                 $ext_checks = array_merge($ext_checks, $script->getCheckExtensions());
             }
             // if
         }
         // foreach
         $write_checks = array_unique($write_checks);
         $ext_checks = array_unique($ext_checks);
         // check for writable files and folders
         foreach ($write_checks as $relative_path) {
             $path = INSTALLATION_PATH . $relative_path;
             if (is_file($path)) {
                 if (file_is_writable($path)) {
                     $this->printMessage("File '{$relative_path}' exists and is writable");
                 } else {
                     $this->printMessage("File '{$relative_path}' is not writable", true);
                     return false;
                 }
                 // if
             } else {
                 if (is_dir($path)) {
                     if (folder_is_writable($path)) {
                         $this->printMessage("Folder '{$relative_path}' exists and is writable");
                     } else {
                         $this->printMessage("Folder '{$relative_path}' is not writable", true);
                         return false;
                     }
                     // if
                 } else {
                     $this->printMessage("'{$relative_path}' does not exists on the system", true);
                     return false;
                 }
             }
             // if
         }
         // foreach
         // check for loaded extensions
         foreach ($ext_checks as $extension_name) {
             if (extension_loaded($extension_name)) {
                 $this->printMessage("Extension '{$extension_name}' is loaded");
             } else {
                 $this->printMessage("Extension '{$extension_name}' is not loaded", true);
                 return false;
             }
             // if
         }
         // foreach
         // connect to database
         if ($dbc = mysql_connect(DB_HOST, DB_USER, DB_PASS)) {
             if (mysql_select_db(DB_NAME, $dbc)) {
                 $this->printMessage('Upgrade script has connected to the database.');
             } else {
                 $this->printMessage('Failed to select database ' . DB_NAME);
                 return false;
             }
             // if
         } else {
             $this->printMessage('Failed to connect to database');
             return false;
         }
         // if
         // check MySQL version
         $mysql_version = mysql_get_server_info($dbc);
         if ($mysql_version && version_compare($mysql_version, "4.1", '>=')) {
             $constants['DB_CHARSET'] = 'utf8';
             @mysql_query("SET NAMES 'utf8'", $dbc);
             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');
         }
         // check test query
         $test_table_name = TABLE_PREFIX . 'test_table';
         $test_table_sql = "CREATE TABLE `{$test_table_name}` (\n\t\t\t\t`id` int(10) unsigned NOT NULL auto_increment,\n\t\t\t\t`name` varchar(50) {$default_collation} NOT NULL default '',\n\t\t\t\tPRIMARY KEY  (`id`)\n\t\t\t\t) ENGINE=InnoDB {$default_charset};";
         if (@mysql_query($test_table_sql, $dbc)) {
             $this->printMessage('Test query has been executed. Its safe to proceed with database migration.');
             @mysql_query("DROP TABLE `{$test_table_name}`", $dbc);
         } else {
             $this->printMessage('Failed to executed test query. MySQL said: ' . mysql_error($dbc), true);
             return false;
         }
         // if
         // execute scripts
         foreach ($scripts as $script) {
             if (version_compare($script->getVersionTo(), $version_from) > 0 && version_compare($script->getVersionTo(), $version_to) <= 0) {
                 $script->setDatabaseConnection($dbc);
                 if ($script->execute() === false) {
                     $this->printMessage("Error upgrading to version " . $script->getVersionTo());
                     break;
                 }
                 $last_correct_version = $script->getVersionTo();
                 tpl_assign('version', $last_correct_version);
                 file_put_contents(INSTALLATION_PATH . '/config/installed_version.php', tpl_fetch(get_template_path('installed_version')));
             }
             // if
         }
         // foreach
         if (isset($last_correct_version)) {
             @mysql_query("UPDATE `" . TABLE_PREFIX . "config_options` SET `value` = 0 WHERE `name` = 'upgrade_last_check_new_version'");
             tpl_assign('version', $last_correct_version);
             return file_put_contents(INSTALLATION_PATH . '/config/installed_version.php', tpl_fetch(get_template_path('installed_version')));
         }
     }
     // if
 }
 /**
  * When a task is completed, sends a notification to the assigned users of all the 
  * dependant tasks of the completed task to inform that the previous task has been completed.
  * @param $object The task that has been completed
  */
 static function notifyDependantTaskAssignedUsersOfTaskCompletion($object)
 {
     /* @var $object ProjectTask */
     $emails = array();
     // get dependant tasks
     $dependant_tasks = ProjectTaskDependencies::getDependantTasks($object->getId());
     // set sender user as the one who completed the task
     $sender = $object->getCompletedBy();
     if ($sender instanceof Contact) {
         $sendername = $sender->getObjectName();
         $senderemail = $sender->getEmailAddress();
     } else {
         return;
     }
     foreach ($dependant_tasks as $dep_task) {
         /* @var $dep_task ProjectTask */
         $assigned_user = $dep_task->getAssignedTo();
         // check that dependant task is assigned to a valid user
         if ($assigned_user instanceof Contact && $assigned_user->isUser()) {
             // check that all previous tasks are completed
             $all_previous_completed = true;
             $previous_tasks = ProjectTaskDependencies::getPreviousTasks($dep_task->getId());
             foreach ($previous_tasks as $pt) {
                 if ($pt->getId() == $object->getId()) {
                     continue;
                 }
                 if ($pt->getCompletedById() == 0) {
                     $all_previous_completed = false;
                     break;
                 }
             }
             // send the notification only if all previous tasks of this task are completed
             if ($all_previous_completed) {
                 // set notificated user localization
                 Localization::instance()->loadSettings($assigned_user->getLocale(), ROOT . '/language');
                 // format notification data
                 $assigned_by_name = $dep_task->getAssignedBy() instanceof Contact ? $dep_task->getAssignedBy()->getObjectName() : "";
                 $assigned_to_name = $dep_task->getAssignedToName();
                 tpl_assign('object', $dep_task);
                 tpl_assign('title', lang('task x can be started', $dep_task->getObjectName()));
                 tpl_assign('by', $assigned_by_name);
                 tpl_assign('asigned', $assigned_to_name);
                 tpl_assign('description', $dep_task->getDescription());
                 $contexts = self::buildContextObjectForNotification($dep_task);
                 tpl_assign('contexts', $contexts);
                 $priority_data = self::getTaskPriorityData($dep_task);
                 tpl_assign('priority', $priority_data);
                 $start_date = self::getTaskDateFormatted($dep_task, 'start_date', $assigned_user->getTimezone());
                 tpl_assign('start_date', $start_date);
                 $due_date = self::getTaskDateFormatted($dep_task, 'due_date', $assigned_user->getTimezone());
                 tpl_assign('due_date', $due_date);
                 $attachments = array();
                 $attachments['logo'] = self::getLogoAttachmentData($assigned_user->getEmailAddress());
                 tpl_assign('attachments', $attachments);
                 // send notification
                 $to_addresses = array();
                 $to_addresses[$assigned_user->getId()] = self::prepareEmailAddress($assigned_user->getEmailAddress(), $assigned_user->getObjectName());
                 $subject = lang('all previous tasks have been completed', $dep_task->getObjectName());
                 $recipients_field = config_option('notification_recipients_field', 'to');
                 $emails[] = array("{$recipients_field}" => $to_addresses, "from" => self::prepareEmailAddress($senderemail, $sendername), "subject" => $subject, "body" => tpl_fetch(get_template_path('previous_task_completed', 'notifier')), "attachments" => $attachments);
             }
         }
     }
     if (count($emails) > 0) {
         self::queueEmails($emails);
         $locale = logged_user() instanceof Contact ? logged_user()->getLocale() : DEFAULT_LOCALIZATION;
         Localization::instance()->loadSettings($locale, ROOT . '/language');
     }
 }
 /**
  * @author Ignacio Vazquez - elpepe.uy@gmail.com
  * @param array of string $pluginNames
  */
 function installPlugins($pluginNames)
 {
     if (count($pluginNames)) {
         foreach ($pluginNames as $name) {
             $path = INSTALLATION_PATH . "/plugins/{$name}/info.php";
             if (file_exists($path)) {
                 //1. Insert into PLUGIN TABLE
                 $pluginInfo = (include_once $path);
                 $cols = "name, is_installed, is_activated, version";
                 $values = "'{$name}', 1, 1, " . array_var($pluginInfo, 'version');
                 if (is_numeric(array_var($pluginInfo, 'id'))) {
                     $cols = "id, " . $cols;
                     $values = array_var($pluginInfo, 'id') . ", " . $values;
                 }
                 $sql = "INSERT INTO " . $this->table_prefix . "plugins ({$cols}) VALUES ({$values}) ";
                 if (@mysql_query($sql)) {
                     $id = @mysql_insert_id();
                     $pluginInfo['id'] = $id;
                 } else {
                     return false;
                 }
                 //2. IF Plugin defines types, INSERT INTO ITS TABLE
                 if (count(array_var($pluginInfo, 'types'))) {
                     foreach ($pluginInfo['types'] as $k => $type) {
                         if (isset($type['name'])) {
                             $sql = "\n\t\t\t\t\t\t\t\t\tINSERT INTO " . $this->table_prefix . "object_types (name, handler_class, table_name, type, icon, plugin_id)\n\t\t\t\t\t\t\t\t\t \tVALUES (\n\t\t\t\t\t\t\t\t\t \t'" . array_var($type, "name") . "', \n\t\t\t\t\t\t\t\t\t \t'" . array_var($type, "handler_class") . "', \n\t\t\t\t\t\t\t\t\t \t'" . array_var($type, "table_name") . "', \n\t\t\t\t\t\t\t\t\t \t'" . array_var($type, "type") . "', \n\t\t\t\t\t\t\t\t\t \t'" . array_var($type, "icon") . "', \n\t\t\t\t\t\t\t\t\t\t{$id}\n\t\t\t\t\t\t\t\t\t)";
                             if (@mysql_query($sql)) {
                                 $pluginInfo['types'][$k]['id'] = @mysql_insert_id();
                                 $type['id'] = @mysql_insert_id();
                             } else {
                                 echo "FAIL INSTALLING TYPES <br>";
                                 echo mysql_error() . "<br/>";
                                 echo $sql . "<br/>";
                             }
                         }
                     }
                 }
                 //2. IF Plugin defines tabs, INSERT INTO ITS TABLE
                 if (count(array_var($pluginInfo, 'tabs'))) {
                     foreach ($pluginInfo['tabs'] as $k => $tab) {
                         if (isset($tab['title'])) {
                             $type_id = array_var($type, "id");
                             $sql = "\n\t\t\t\t\t\t\t\t\tINSERT INTO " . $this->table_prefix . "tab_panels (\n\t\t\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\t\t\ttitle, \n\t\t\t\t\t\t\t\t\t\ticon_cls, \n\t\t\t\t\t\t\t\t\t\trefresh_on_context_change, \n\t\t\t\t\t\t\t\t\t\tdefault_controller, \n\t\t\t\t\t\t\t\t\t\tdefault_action, \n\t\t\t\t\t\t\t\t\t\tinitial_controller, \n\t\t\t\t\t\t\t\t\t\tinitial_action, \n\t\t\t\t\t\t\t\t\t\tenabled, \n\t\t\t\t\t\t\t\t\t\ttype,  \n\t\t\t\t\t\t\t\t\t\tplugin_id, \n\t\t\t\t\t\t\t\t\t\tobject_type_id )\n\t\t\t\t\t\t\t\t \tVALUES (\n\t\t\t\t\t\t\t\t \t\t'" . array_var($tab, 'id') . "', \n\t\t\t\t\t\t\t\t \t\t'" . array_var($tab, 'title') . "', \n\t\t\t\t\t\t\t\t \t\t'" . array_var($tab, 'icon_cls') . "',\n\t\t\t\t\t\t\t\t \t\t'" . array_var($tab, 'refresh_on_context_change') . "',\n\t\t\t\t\t\t\t\t \t\t'" . array_var($tab, 'default_controller') . "',\n\t\t\t\t\t\t\t\t \t\t'" . array_var($tab, 'default_action') . "',\n\t\t\t\t\t\t\t\t\t\t'" . array_var($tab, 'initial_controller') . "',\n\t\t\t\t\t\t\t\t\t\t'" . array_var($tab, 'initial_action') . "',\n\t\t\t\t\t\t\t\t\t\t'" . array_var($tab, 'enabled', 1) . "',\n\t\t\t\t\t\t\t\t\t\t'" . array_var($tab, 'type') . "',\n\t\t\t\t\t\t\t\t\t\t{$id},\n\t\t\t\t\t\t\t\t\t\t" . array_var($tab, 'object_type_id') . "\n\t\t\t\t\t\t\t\t\t)";
                             if (!@mysql_query($sql)) {
                                 echo $sql;
                                 echo mysql_error();
                             }
                         }
                     }
                 }
                 // Create schema sql query
                 $schema_creation = INSTALLATION_PATH . "/plugins/{$name}/install/sql/mysql_schema.php";
                 if (file_exists($schema_creation)) {
                     $total_queries = 0;
                     $executed_queries = 0;
                     if ($this->executeMultipleQueries(tpl_fetch($schema_creation), $total_queries, $executed_queries)) {
                         $this->printMessage("Schema created for plugin {$name} ");
                     } else {
                         $this->breakExecution("Error while creating schema for plugin {$name}" . mysql_error());
                         //$this->printMessage("Error while creating schema for plugin $name".mysql_error());
                     }
                 }
                 // Create schema sql query
                 $schema_query = INSTALLATION_PATH . "/plugins/{$name}/install/sql/mysql_initial_data.php";
                 if (file_exists($schema_query)) {
                     $total_queries = 0;
                     $executed_queries = 0;
                     if ($this->executeMultipleQueries(tpl_fetch($schema_query), $total_queries, $executed_queries)) {
                         $this->printMessage("Initial data loaded for plugin  '{$name}'." . mysql_error());
                     } else {
                         $this->breakExecution("Error while loading inital data for plugin '{$name}'." . mysql_error());
                     }
                 }
                 $install_script = INSTALLATION_PATH . "/plugins/{$name}/install/install.php";
                 if (file_exists($install_script)) {
                     include_once $install_script;
                 }
             }
         }
     }
 }
 /**
  * This function will fix configuration file
  *
  * @param void
  * @return null
  */
 function fixConfigFile()
 {
     $this->printMessage('Updating configuration file');
     $constants = array('DB_ADAPTER' => DB_ADAPTER, 'DB_HOST' => DB_HOST, 'DB_USER' => DB_USER, 'DB_PASS' => DB_PASS, 'DB_NAME' => DB_NAME, 'DB_PERSIST' => false, 'DB_CHARSET' => DB_CHARSET);
     // array
     tpl_assign('config_file_constants', $constants);
     if (file_put_contents(INSTALLATION_PATH . '/config/config.php', tpl_fetch(get_template_path('config_file')))) {
         $this->printMessage('Configuration file updated');
         return true;
     } else {
         $this->printMessage('Failed to update configuration file', true);
         return false;
     }
     // if
 }
Example #19
0
 /**
  * Milestone has been assigned to the user
  *
  * @param ProjectMilestone $milestone
  * @return boolean
  * @throws NotifierConnectionError
  */
 function milestoneAssigned(ProjectMilestone $milestone)
 {
     if ($milestone->isCompleted()) {
         return true;
         // milestone has been already completed...
     }
     // if
     if (!$milestone->getAssignedTo() instanceof User) {
         return true;
         // not assigned to user
     }
     // if
     tpl_assign('milestone_assigned', $milestone);
     return self::sendEmail(self::prepareEmailAddress($milestone->getAssignedTo()->getEmail(), $milestone->getAssignedTo()->getDisplayName()), self::prepareEmailAddress($milestone->getCreatedBy()->getEmail(), $milestone->getCreatedByDisplayName()), $milestone->getProject()->getName() . ' - ' . lang('milestone assigned to you') . " - " . $milestone->getName(), tpl_fetch(get_template_path('milestone_assigned', 'notifier')));
     // send
 }
 /**
  * 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
     // ---------------------------------------------------
     $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_4_nutria'));
     } else {
         // upgrading from a pre-release of this version (beta, rc, etc)
         $upgrade_script = "";
         if (version_compare($installed_version, '1.4-beta') == 0) {
             $upgrade_script .= "\r\n\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', 'noOfTasks', '8', 'IntegerConfigHandler', '0', '100', NULL),\r\n\t\t\t\t\t('calendar panel', 'start_monday', '', 'BoolConfigHandler', 0, 0, ''),\r\n\t\t\t\t\t('calendar panel', 'show_week_numbers', '', 'BoolConfigHandler', 0, 0, ''),\r\n\t\t\t\t\t('context help', 'show_reporting_panel_context_help', '1', 'BoolConfigHandler', '1', '0', NULL)\r\n\t\t\t\tON DUPLICATE KEY UPDATE id=id;\r\n\t\t\t\tUPDATE `" . TABLE_PREFIX . "user_ws_config_options`\r\n\t\t\t\t\tSET `is_system` = 0 WHERE `name` IN ('start_monday', 'show_week_numbers');\r\n\t\t\t\tUPDATE `" . TABLE_PREFIX . "user_ws_config_categories`\r\n\t\t\t\t\tSET `is_system` = 0 WHERE `name` = 'calendar panel';\r\n\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', 'show_feed_links', '0', 'BoolConfigHandler', '0', '0', NULL),\r\n\t\t\t\t\t('mailing', 'user_email_fetch_count', '10', 'IntegerConfigHandler', 0, 0, 'How many emails to fetch when checking for email')\r\n\t\t\t\tON DUPLICATE KEY UPDATE id=id;\r\n\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "custom_properties` ADD COLUMN `visible_by_default` TINYINT(1) NOT NULL DEFAULT 0 AFTER `property_order`;\r\n\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "custom_property_values` MODIFY COLUMN `value` text {$default_collation} NOT NULL;\r\n\t\t\t\t-- larger contact fields\r\n\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "contacts` MODIFY COLUMN `firstname` varchar(50) {$default_collation} default NULL;\r\n\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "contacts` MODIFY COLUMN `lastname` varchar(50) {$default_collation} default NULL;\r\n\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "contacts` MODIFY COLUMN `middlename` varchar(50) {$default_collation} default NULL;\r\n\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "contacts` MODIFY COLUMN `department` varchar(50) {$default_collation} default NULL;\r\n\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "contacts` MODIFY COLUMN `job_title` varchar(50) {$default_collation} default NULL;\r\n\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "contacts` MODIFY COLUMN `w_city` varchar(50) {$default_collation} default NULL;\r\n\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "contacts` MODIFY COLUMN `w_state` varchar(50) {$default_collation} default NULL;\r\n\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "contacts` MODIFY COLUMN `w_zipcode` varchar(50) {$default_collation} default NULL;\r\n\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "contacts` MODIFY COLUMN `w_country` varchar(50) {$default_collation} default NULL;\r\n\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "contacts` MODIFY COLUMN `w_phone_number` varchar(50) {$default_collation} default NULL;\r\n\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "contacts` MODIFY COLUMN `w_phone_number2` varchar(50) {$default_collation} default NULL;\r\n\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "contacts` MODIFY COLUMN `w_fax_number` varchar(50) {$default_collation} default NULL;\r\n\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "contacts` MODIFY COLUMN `w_assistant_number` varchar(50) {$default_collation} default NULL;\r\n\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "contacts` MODIFY COLUMN `w_callback_number` varchar(50) {$default_collation} default NULL;\r\n\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "contacts` MODIFY COLUMN `h_city` varchar(50) {$default_collation} default NULL;\r\n\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "contacts` MODIFY COLUMN `h_state` varchar(50) {$default_collation} default NULL;\r\n\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "contacts` MODIFY COLUMN `h_zipcode` varchar(50) {$default_collation} default NULL;\r\n\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "contacts` MODIFY COLUMN `h_country` varchar(50) {$default_collation} default NULL;\r\n\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "contacts` MODIFY COLUMN `h_phone_number` varchar(50) {$default_collation} default NULL;\r\n\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "contacts` MODIFY COLUMN `h_phone_number2` varchar(50) {$default_collation} default NULL;\r\n\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "contacts` MODIFY COLUMN `h_fax_number` varchar(50) {$default_collation} default NULL;\r\n\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "contacts` MODIFY COLUMN `h_mobile_number` varchar(50) {$default_collation} default NULL;\r\n\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "contacts` MODIFY COLUMN `h_pager_number` varchar(50) {$default_collation} default NULL;\r\n\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "contacts` MODIFY COLUMN `o_city` varchar(50) {$default_collation} default NULL;\r\n\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "contacts` MODIFY COLUMN `o_state` varchar(50) {$default_collation} default NULL;\r\n\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "contacts` MODIFY COLUMN `o_zipcode` varchar(50) {$default_collation} default NULL;\r\n\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "contacts` MODIFY COLUMN `o_country` varchar(50) {$default_collation} default NULL;\r\n\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "contacts` MODIFY COLUMN `o_phone_number` varchar(50) {$default_collation} default NULL;\r\n\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "contacts` MODIFY COLUMN `o_phone_number2` varchar(50) {$default_collation} default NULL;\r\n\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "contacts` MODIFY COLUMN `o_fax_number` varchar(50) {$default_collation} default NULL;\r\n\t\t\t\t\r\n\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "companies` MODIFY COLUMN `phone_number` varchar(50) {$default_collation} default NULL;\r\n\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "companies` MODIFY COLUMN `fax_number` varchar(50) {$default_collation} default NULL;\r\n\t\t\t\t";
         }
         if (version_compare($installed_version, '1.4-rc') <= 0) {
             $upgrade_script .= "\r\n\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 ('context help', 'show_administration_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_member_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_add_contact_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_add_company_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_upload_file_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_upload_file_workspace_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_upload_file_tags_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_upload_file_description_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_upload_file_custom_properties_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_upload_file_subscribers_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_upload_file_linked_objects_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_add_note_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_add_note_workspace_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_add_note_tags_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_add_note_custom_properties_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_add_note_subscribers_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_add_note_linked_object_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_add_milestone_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_add_milestone_workspace_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_add_milestone_tags_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_add_milestone_description_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_add_milestone_reminders_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_add_milestone_custom_properties_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_add_milestone_linked_object_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_add_milestone_subscribers_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_add_workspace_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_print_report_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_add_task_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_add_task_workspace_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_add_task_tags_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_add_task_reminders_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_add_task_custom_properties_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_add_task_linked_objects_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_add_task_subscribers_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_list_task_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_time_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_add_webpage_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_add_webpage_workspace_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_add_webpage_tags_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_add_webpage_description_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_add_webpage_custom_properties_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_add_webpage_subscribers_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_add_webpage_linked_objects_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('dashboard', 'show calendar widget', '1', 'BoolConfigHandler', 0, 80, ''),\r\n\t\t\t\t ('dashboard', 'show late tasks and milestones widget', '1', 'BoolConfigHandler', 0, 100, ''),\r\n\t\t\t\t ('dashboard', 'show pending tasks widget', '1', 'BoolConfigHandler', 0, 200, ''),\r\n\t\t\t\t ('dashboard', 'pending tasks widget assigned to filter', '0:0', 'UserCompanyConfigHandler', 0, 210, ''),\r\n\t\t\t\t ('dashboard', 'show emails widget', '1', 'BoolConfigHandler', 0, 300, ''),\r\n\t\t\t\t ('dashboard', 'show messages widget', '1', 'BoolConfigHandler', 0, 400, ''),\r\n\t\t\t\t ('dashboard', 'show documents widget', '1', 'BoolConfigHandler', 0, 500, ''),\r\n\t\t\t\t ('dashboard', 'show charts widget', '1', 'BoolConfigHandler', 0, 600, ''),\r\n\t\t\t\t ('dashboard', 'show tasks in progress widget', '1', 'BoolConfigHandler', 0, 700, ''),\r\n\t\t\t\t ('dashboard', 'show comments widget', '1', 'BoolConfigHandler', 0, 800, ''),\r\n\t\t\t\t ('dashboard', 'show dashboard info widget', '1', 'BoolConfigHandler', 0, 900, ''),\r\n\t\t\t\t ('dashboard', 'always show unread mail in dashboard', '0', 'BoolConfigHandler', 0, 10, 'when false, active workspace email is shown'),\r\n\t\t\t\t ('dashboard', 'calendar_widget_expanded', '1', 'BoolConfigHandler', 1, 0, ''),\r\n\t\t\t\t ('dashboard', 'emails_widget_expanded', '1', 'BoolConfigHandler', 1, 0, ''),\r\n\t\t\t\t ('dashboard', 'messages_widget_expanded', '1', 'BoolConfigHandler', 1, 0, ''),\r\n\t\t\t\t ('dashboard', 'active_tasks_widget_expanded', '1', 'BoolConfigHandler', 1, 0, ''),\r\n\t\t\t\t ('dashboard', 'pending_tasks_widget_expanded', '1', 'BoolConfigHandler', 1, 0, ''),\r\n\t\t\t\t ('dashboard', 'late_tasks_widget_expanded', '1', 'BoolConfigHandler', 1, 0, ''),\r\n\t\t\t\t ('dashboard', 'comments_widget_expanded', '1', 'BoolConfigHandler', 1, 0, ''),\r\n\t\t\t\t ('dashboard', 'documents_widget_expanded', '1', 'BoolConfigHandler', 1, 0, ''),\r\n\t\t\t\t ('dashboard', 'charts_widget_expanded', '1', 'BoolConfigHandler', 1, 0, ''),\r\n\t\t\t\t ('dashboard', 'dashboard_info_widget_expanded', '1', 'BoolConfigHandler', 1, 0, ''),\r\n\t\t\t\t ('task panel', 'can notify from quick add', '1', 'BoolConfigHandler', 0, 0, ''),\r\n\t\t\t\t ('task panel', 'tasksShowWorkspaces', '1', 'BoolConfigHandler', 1, 0, ''),\r\n\t\t\t\t ('task panel', 'tasksShowTime', '1', 'BoolConfigHandler', 1, 0, ''),\r\n\t\t\t\t ('task panel', 'tasksShowDates', '1', 'BoolConfigHandler', 1, 0, ''),\r\n\t\t\t\t ('task panel', 'tasksShowTags', '1', 'BoolConfigHandler', 1, 0, ''),\r\n\t\t\t\t ('task panel', 'tasksGroupBy', 'milestone', 'StringConfigHandler', 1, 0, ''),\r\n\t\t\t\t ('task panel', 'tasksOrderBy', 'priority', 'StringConfigHandler', 1, 0, ''),\r\n\t\t\t\t ('task panel', 'task panel status', '1', 'IntegerConfigHandler', 1, 0, ''),\r\n\t\t\t\t ('task panel', 'task panel filter', 'assigned_to', 'StringConfigHandler', 1, 0, ''),\r\n\t\t\t\t ('task panel', 'task panel filter value', '0:0', 'UserCompanyConfigHandler', 1, 0, ''),\r\n\t\t\t\t ('time panel', 'TM show time type', '0', 'IntegerConfigHandler', 1, 0, ''),\r\n\t\t\t\t ('time panel', 'TM report show time type', '0', 'IntegerConfigHandler', 1, 0, ''),\r\n\t\t\t\t ('time panel', 'TM user filter', '0', 'IntegerConfigHandler', 1, 0, ''),\r\n\t\t\t\t ('time panel', 'TM tasks user filter', '0', 'IntegerConfigHandler', 1, 0, ''),\r\n\t\t\t\t ('general', 'localization', '', 'LocalizationConfigHandler', 0, 100, ''),\r\n\t\t\t\t ('general', 'initialWorkspace', '0', 'InitialWorkspaceConfigHandler', 0, 200, ''),\r\n\t\t\t\t ('general', 'lastAccessedWorkspace', '0', 'IntegerConfigHandler', 1, 0, ''),\r\n\t\t\t\t ('general', 'rememberGUIState', '0', 'BoolConfigHandler', 0, 300, ''),\r\n\t\t\t\t ('general', 'work_day_start_time', '9:00', 'TimeConfigHandler', 0, 400, 'Work day start time'),\r\n\t\t\t\t ('general', 'time_format_use_24', '0', 'BoolConfigHandler', 0, 500, 'Use 24 hours time format'),\r\n\t\t\t\t ('general', 'date_format', 'd/m/Y', 'StringConfigHandler', 0, 600, 'Date objects will be displayed using this format.'),\r\n\t\t\t\t ('general', 'descriptive_date_format', 'l, j F', 'StringConfigHandler', 0, 700, 'Descriptive dates will be displayed using this format.'),\r\n\t\t\t\t ('calendar panel', 'calendar view type', 'viewweek', 'StringConfigHandler', 1, 0, ''),\r\n\t\t\t\t ('calendar panel', 'calendar user filter', '0', 'IntegerConfigHandler', 1, 0, ''),\r\n\t\t\t\t ('calendar panel', 'calendar status filter', '', 'StringConfigHandler', 1, 0, ''),\r\n\t\t\t\t ('calendar panel', 'start_monday', '', 'BoolConfigHandler', 0, 0, ''),\r\n\t\t\t\t ('calendar panel', 'show_week_numbers', '', 'BoolConfigHandler', 0, 0, ''),\r\n\t\t\t\t ('dashboard', 'show getting started widget', '1', 'BoolConfigHandler', '0', '1000', NULL),\r\n\t\t\t\t ('dashboard', 'getting_started_widget_expanded', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_tasks_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_account_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_active_tasks_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_general_timeslots_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_late_tasks_widget_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_pending_tasks_widget_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_documents_widget_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_active_tasks_widget_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_calendar_widget_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_messages_widget_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_dashboard_info_widget_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_comments_widget_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_emails_widget_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_reporting_panel_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('context help', 'show_add_file_context_help', '1', 'BoolConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('general', 'custom_report_tab', 'tasks', 'StringConfigHandler', '1', '0', NULL),\r\n\t\t\t\t ('general', 'show_context_help', 'until_close', 'ShowContextHelpConfigHandler', '0', '0', NULL),\r\n\t\t\t\t ('task panel', 'noOfTasks', '8', 'IntegerConfigHandler', '0', '100', NULL)\r\n\t\t\t\t ON DUPLICATE KEY UPDATE id=id;\r\n\t\t\t\tUPDATE `" . TABLE_PREFIX . "user_ws_config_options`\r\n\t\t\t\t\tSET `is_system` = 1, `category_name` = 'context help' WHERE `name` = 'show_tasks_context_help';\r\n\t\t\t\tDELETE FROM `" . TABLE_PREFIX . "config_options` where name='upgrade_check_enabled';\r\n\t\t\t\t";
         }
         if (!$this->checkColumnExists(TABLE_PREFIX . 'reports', 'is_order_by_asc', $this->database_connection)) {
             $upgrade_script .= "\r\n\t\t\t\t\tALTER TABLE `" . TABLE_PREFIX . "reports` ADD COLUMN `is_order_by_asc` TINYINT(1) {$default_collation} NOT NULL DEFAULT 1;\r\n\t\t\t\t";
         }
     }
     $upgrade_script .= "\r\n\t\t\tUPDATE `" . TABLE_PREFIX . "user_ws_config_categories` SET `is_system` = 0 WHERE `name` = 'calendar_panel';\r\n\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
     // ---------------------------------------------------
     //  Add SEED to config file
     // ---------------------------------------------------
     $config_file = INSTALLATION_PATH . '/config/config.php';
     $config_lines = file($config_file);
     $new_config = array();
     // Check SEED definition existence
     $add_seed = true;
     foreach ($config_lines as $line) {
         if (str_starts_with(trim($line), "define('SEED'")) {
             $add_seed = false;
             break;
         }
     }
     foreach ($config_lines as $line) {
         $new_config[] = $line;
         if ($add_seed && trim($line) == "<?php") {
             $new_config[] = "  define('SEED', '" . DB_USER . DB_PASS . rand(0, 10000000000.0) . "');\n";
         }
     }
     if (!$add_seed) {
         //remove repeated SEED definitions
         $i = 0;
         $lines_to_remove = array();
         while ($i < count($config_lines)) {
             $line = $new_config[$i];
             if (str_starts_with(trim($line), "define('SEED'")) {
                 $lines_to_remove[] = $i;
             }
             $i++;
         }
         // remove SEED lines except the last one
         unset($lines_to_remove[count($lines_to_remove) - 1]);
         foreach ($lines_to_remove as $index) {
             $new_config[$index] = '';
         }
     }
     $new_content = join('', $new_config);
     $fp = fopen($config_file, 'w');
     fwrite($fp, $new_content);
     $this->printMessage('Feng Office has been upgraded. You are now running Feng Office ' . $this->getVersionTo() . ' Enjoy!');
 }
 /**
  * @author Ignacio Vazquez - elpepe.uy@gmail.com
  * @param array of string $pluginNames
  * TODO avoid using mysql functions - (copied from installer)
  */
 static function executeInstaller($name)
 {
     $table_prefix = TABLE_PREFIX;
     tpl_assign('table_prefix', $table_prefix);
     $default_charset = 'DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci';
     tpl_assign('default_charset', $default_charset);
     $default_collation = 'collate utf8_unicode_ci';
     tpl_assign('default_collation', $default_collation);
     $engine = DB_ENGINE;
     tpl_assign('engine', $engine);
     $path = ROOT . "/plugins/{$name}/info.php";
     if (file_exists($path)) {
         DB::beginWork();
         $pluginInfo = (include_once $path);
         //0. Check if exists in plg table
         $sql = "SELECT id FROM " . TABLE_PREFIX . "plugins WHERE name = '{$name}' ";
         $res = @mysql_query($sql);
         if (!$res) {
             DB::rollback();
             return false;
         }
         $plg_obj = mysql_fetch_object($res);
         if (!$plg_obj) {
             //1. Insert into PLUGIN TABLE
             $cols = "name, is_installed, is_activated, version";
             $values = "'{$name}', 1, 1 ,'" . array_var($pluginInfo, 'version') . "'";
             if (is_numeric(array_var($pluginInfo, 'id'))) {
                 $cols = "id, " . $cols;
                 $values = array_var($pluginInfo, 'id') . ", " . $values;
             }
             $sql = "INSERT INTO " . TABLE_PREFIX . "plugins ({$cols}) VALUES ({$values}) ";
             if (@mysql_query($sql)) {
                 $id = @mysql_insert_id();
                 $pluginInfo['id'] = $id;
             } else {
                 echo "ERROR: " . mysql_error();
                 @mysql_query('ROLLBACK');
                 return false;
             }
         } else {
             $id = $plg_obj->id;
             $pluginInfo['id'] = $id;
         }
         //2. IF Plugin defines types, INSERT INTO ITS TABLE
         if (count(array_var($pluginInfo, 'types'))) {
             foreach ($pluginInfo['types'] as $k => $type) {
                 if (isset($type['name'])) {
                     $sql = "\n\t\t\t\t\t\t\tINSERT INTO " . TABLE_PREFIX . "object_types (name, handler_class, table_name, type, icon, plugin_id)\n\t\t\t\t\t\t\t \tVALUES (\n\t\t\t\t\t\t\t \t'" . array_var($type, "name") . "', \n\t\t\t\t\t\t\t \t'" . array_var($type, "handler_class") . "', \n\t\t\t\t\t\t\t \t'" . array_var($type, "table_name") . "', \n\t\t\t\t\t\t\t \t'" . array_var($type, "type") . "', \n\t\t\t\t\t\t\t \t'" . array_var($type, "icon") . "', \n\t\t\t\t\t\t\t\t{$id}\n\t\t\t\t\t\t\t)";
                     if (@mysql_query($sql)) {
                         $pluginInfo['types'][$k]['id'] = @mysql_insert_id();
                         $type['id'] = @mysql_insert_id();
                     } else {
                         echo $sql . "<br/>";
                         echo mysql_error() . "<br/>";
                         DB::rollback();
                         return false;
                     }
                 }
             }
         }
         //2. IF Plugin defines tabs, INSERT INTO ITS TABLE
         if (count(array_var($pluginInfo, 'tabs'))) {
             foreach ($pluginInfo['tabs'] as $k => $tab) {
                 if (isset($tab['title'])) {
                     $type_id = array_var($type, "id");
                     $sql = "\n\t\t\t\t\t\t\tINSERT INTO " . TABLE_PREFIX . "tab_panels (\n\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\ttitle, \n\t\t\t\t\t\t\t\ticon_cls, \n\t\t\t\t\t\t\t\trefresh_on_context_change, \n\t\t\t\t\t\t\t\tdefault_controller, \n\t\t\t\t\t\t\t\tdefault_action, \n\t\t\t\t\t\t\t\tinitial_controller, \n\t\t\t\t\t\t\t\tinitial_action, \n\t\t\t\t\t\t\t\tenabled, \n\t\t\t\t\t\t\t\ttype,  \n\t\t\t\t\t\t\t\tplugin_id, \n\t\t\t\t\t\t\t\tobject_type_id )\n\t\t\t\t\t\t \tVALUES (\n\t\t\t\t\t\t \t\t'" . array_var($tab, 'id') . "', \n\t\t\t\t\t\t \t\t'" . array_var($tab, 'title') . "', \n\t\t\t\t\t\t \t\t'" . array_var($tab, 'icon_cls') . "',\n\t\t\t\t\t\t \t\t'" . array_var($tab, 'refresh_on_context_change') . "',\n\t\t\t\t\t\t \t\t'" . array_var($tab, 'default_controller') . "',\n\t\t\t\t\t\t \t\t'" . array_var($tab, 'default_action') . "',\n\t\t\t\t\t\t\t\t'" . array_var($tab, 'initial_controller') . "',\n\t\t\t\t\t\t\t\t'" . array_var($tab, 'initial_action') . "',\n\t\t\t\t\t\t\t\t'" . array_var($tab, 'enabled', 1) . "',\n\t\t\t\t\t\t\t\t'" . array_var($tab, 'type') . "',\n\t\t\t\t\t\t\t\t{$id},\n\t\t\t\t\t\t\t\t" . array_var($tab, 'object_type_id') . "\n\t\t\t\t\t\t\t)";
                     if (!@mysql_query($sql)) {
                         echo $sql;
                         echo mysql_error();
                         DB::rollback();
                         return false;
                     }
                     // INSERT INTO TAB PANEL PERMISSSION
                     $sql = "\n\t\t\t\t\t\t\tINSERT INTO " . TABLE_PREFIX . "tab_panel_permissions (\n\t\t\t\t\t\t\t\tpermission_group_id,\n\t\t\t\t\t\t\t\ttab_panel_id \n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t \tVALUES ( 1,'" . array_var($tab, 'id') . "' ),  ( 2,'" . array_var($tab, 'id') . "' )  ON DUPLICATE KEY UPDATE permission_group_id = permission_group_id ";
                     if (!@mysql_query($sql)) {
                         echo $sql;
                         echo mysql_error();
                         @mysql_query('ROLLBACK');
                         DB::rollback();
                         return false;
                     }
                 }
             }
         }
         // Create schema sql query
         $schema_creation = ROOT . "/plugins/{$name}/install/sql/mysql_schema.php";
         if (file_exists($schema_creation)) {
             $total_queries = 0;
             $executed_queries = 0;
             if (executeMultipleQueries(tpl_fetch($schema_creation), $total_queries, $executed_queries)) {
                 logger::log("Schema created for plugin {$name} ");
             } else {
                 //echo tpl_fetch ( $schema_creation );
                 echo mysql_error();
                 echo "llega <br>";
                 DB::rollback();
                 return false;
             }
         }
         // Create schema sql query
         $schema_query = ROOT . "/plugins/{$name}/install/sql/mysql_initial_data.php";
         if (file_exists($schema_query)) {
             $total_queries = 0;
             $executed_queries = 0;
             if (executeMultipleQueries(tpl_fetch($schema_query), $total_queries, $executed_queries)) {
                 logger::log("Initial data loaded for plugin  '{$name}'." . mysql_error());
             } else {
                 echo mysql_error();
                 DB::rollback();
                 return false;
             }
         }
         $install_script = ROOT . "/plugins/{$name}/install/install.php";
         if (file_exists($install_script)) {
             include_once $install_script;
         }
         DB::commit();
         return true;
     }
     return false;
 }
 /**
  * This function will configuration file
  *
  * @param void
  * @return null
  */
 function fixConfigFile()
 {
     $this->printMessage('Updating configuration file');
     $constants = array('DB_ADAPTER' => DB_ADAPTER, 'DB_HOST' => DB_HOST, 'DB_USER' => DB_USER, 'DB_PASS' => DB_PASS, 'DB_NAME' => DB_NAME, 'DB_PERSIST' => true, 'TABLE_PREFIX' => TABLE_PREFIX, 'ROOT_URL' => ROOT_URL, 'DEFAULT_LOCALIZATION' => DEFAULT_LOCALIZATION, 'DEBUG' => false, 'PRODUCT_VERSION' => $this->getVersionTo());
     // array
     tpl_assign('config_file_constants', $constants);
     if (file_put_contents(INSTALLATION_PATH . '/config/config.php', tpl_fetch(get_template_path('config_file')))) {
         $this->printMessage('Configuration file updated');
         return true;
     } else {
         $this->printMessage('Failed to update configuration file', true);
         return false;
     }
     // if
 }
Example #23
0
 /* 初始化页面信息 */
 $tpl['_body'] = 'list';
 /* ------------------------------------------------------ */
 // - 异步 - 列表页,列表查询
 /* ------------------------------------------------------ */
 if ($_REQUEST['act'] == 'list') {
     /* 列表查询 */
     if ($_REQUEST['actsub'] == 'query') {
         /* 排序图片 */
         $flag = order_img($tpl['list']['filter']);
         $tpl[$flag['var']] = $flag['img'];
         /* 初始化页面信息 */
         $tpl['_bodysub'] = 'query';
     }
     /* 返回JSON */
     make_json_ok('', tpl_fetch('admin.html', $tpl));
 } else {
     /* 初始化页面信息 */
     $tpl['_header'] = 'title';
     /* 取得管理员的增加操作 */
     $m_ab = filter_module_acts($m_aa, array('add'), true);
     $m_ab[] = array('module_act_name' => $_LANG['act_export'], 'module_act_code' => 'export');
     /* 操作属性 */
     $attribs = array();
     $attribs['add'] = array('onclick' => "wnd_admin_fill(this,'add')");
     $attribs['export']['icon'] = 'xls';
     $attribs['export']['type'] = 'cddl';
     $attribs['export']['title'] = $_LANG['act_export_choice'];
     $attribs['export']['onclick'] = "deal_list_export('listtable-admin','modules/admin/admin.php?act=exportdo','choice')";
     $attribs['export']['ddlwidth'] = '120';
     /* 构建管理员的导出操作 */
 /**
  * Execute the script
  *
  * @param void
  * @return boolean
  */
 function execute()
 {
     if (!@mysql_ping($this->database_connection)) {
         if ($dbc = mysql_connect(DB_HOST, DB_USER, DB_PASS)) {
             if (mysql_select_db(DB_NAME, $dbc)) {
                 $this->printMessage('Upgrade script has connected to the database.');
             } else {
                 $this->printMessage('Failed to select database ' . DB_NAME);
                 return false;
             }
             $this->setDatabaseConnection($dbc);
         } else {
             $this->printMessage('Failed to connect to database');
             return false;
         }
     }
     // ---------------------------------------------------
     //  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;
     $additional_upgrade_steps = array();
     // RUN QUERIES
     $total_queries = 0;
     $executed_queries = 0;
     $upgrade_script = "";
     $upgrade_loop_script = "";
     $upgrade_after_loop_script = "";
     $multi_assignment_create = "";
     $multi_assignment = "";
     if ($this->checkColumnExists($t_prefix . 'project_tasks', 'multi_assignment', $this->database_connection)) {
         $multi_assignment_create .= "ALTER TABLE `" . $t_prefix . "template_tasks` ADD `multi_assignment` TINYINT( 1 ) NULL DEFAULT 0;";
         $multi_assignment .= ", `multi_assignment`";
     }
     $v_from = array_var($_POST, 'form_data');
     $original_version_from = array_var($v_from, 'upgrade_from', $installed_version);
     if (false && version_compare($installed_version, $this->getVersionFrom()) <= 0 && version_compare($original_version_from, '2.0.0.0-beta') > 0 && (!isset($_SESSION['from_feng1']) || !$_SESSION['from_feng1'])) {
         // upgrading from a version lower than this script's 'from' version
         $upgrade_script = tpl_fetch(get_template_path('db_migration/2_4_morcilla'));
     } else {
         if (version_compare($installed_version, '2.4-beta') < 0) {
             $upgrade_script .= "\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`) VALUES \r\n\t\t\t\t\t\t('general', 'timeReportDate', '4', 'IntegerConfigHandler', 1, 0, ''),\r\n\t\t\t\t\t\t('general', 'timeReportDateStart', '0000-00-00 00:00:00', 'DateTimeConfigHandler', 1, 0, ''),\r\n\t\t\t\t\t\t('general', 'timeReportDateEnd', '0000-00-00 00:00:00', 'DateTimeConfigHandler', 1, 0, ''),\r\n\t\t\t\t\t\t('general', 'timeReportPerson', '0', 'IntegerConfigHandler', 1, 0, ''),\r\n\t\t\t\t\t\t('general', 'timeReportTimeslotType', '2', 'IntegerConfigHandler', 1, 0, ''),\r\n\t\t\t\t\t\t('general', 'timeReportGroupBy', '0,0,0', 'StringConfigHandler', 1, 0, ''),\r\n\t\t\t\t\t\t('general', 'timeReportAltGroupBy', '0,0,0', 'StringConfigHandler', 1, 0, ''),\r\n\t\t\t\t\t\t('general', 'timeReportShowBilling', '0', 'BoolConfigHandler', 1, 0, '')\r\n\t\t\t\t\tON DUPLICATE KEY UPDATE name=name;\r\n\t\t\t\t";
             if (!$this->checkColumnExists($t_prefix . "contact_addresses", "street", $this->database_connection)) {
                 $upgrade_script .= "\r\n\t\t\t\t\t\tALTER TABLE `" . $t_prefix . "contact_addresses` MODIFY COLUMN `street` TEXT CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL;\r\n\t\t\t\t\t";
             }
             if (!$this->checkColumnExists($t_prefix . "system_permissions", "can_manage_contacts", $this->database_connection)) {
                 $upgrade_script .= "\r\n\t\t\t\t\t\tALTER TABLE `" . $t_prefix . "system_permissions` ADD COLUMN `can_manage_contacts` BOOLEAN NOT NULL DEFAULT 0;\r\n\t\t\t\t\t";
             }
             $upgrade_script .= "\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`) VALUES \r\n\t\t\t\t\t\t('listing preferences', 'breadcrumb_member_count', '5', 'IntegerConfigHandler', '0', '5', NULL)\r\n\t\t\t\t\tON DUPLICATE KEY UPDATE name=name;\r\n\t\t\t\t\t\r\n\t\t\t\t\tINSERT INTO `" . $t_prefix . "object_types` (`name`,`handler_class`,`table_name`,`type`,`icon`,`plugin_id`) VALUES\r\n \t\t\t\t\t\t('template_task', 'TemplateTasks', 'template_tasks', 'content_object', 'task', null),\r\n\t\t\t\t\t\t('template_milestone', 'TemplateMilestones', 'template_milestones', 'content_object', 'milestone', null)\r\n\t\t\t\t\tON DUPLICATE KEY UPDATE name=name;\r\n\t\t\t\t";
             if (!$this->checkColumnExists($t_prefix . "project_tasks", "from_template_object_id", $this->database_connection)) {
                 $upgrade_script .= "\r\n\t\t\t\t\t\tALTER TABLE `" . $t_prefix . "project_tasks` ADD `from_template_object_id` int(10) unsigned DEFAULT '0' AFTER from_template_id;\r\n\t\t\t\t\t\t/* from template object id queda en 0 para todos los objetos instanciados de templates ya que no se puede obtener */\r\n\t\t\t\t\t";
             }
             if (!$this->checkColumnExists($t_prefix . "project_milestones", "from_template_object_id", $this->database_connection)) {
                 $upgrade_script .= "\r\n\t\t\t\t\t\tALTER TABLE `" . $t_prefix . "project_milestones` ADD `from_template_object_id` int(10) unsigned DEFAULT '0' AFTER from_template_id;\r\n\t\t\t\t\t\t/* from template object id queda en 0 para todos los objetos instanciados de templates ya que no se puede obtener */\r\n\t\t\t\t\t";
             }
             $upgrade_script .= "\r\n\t\t\t\t\tCREATE TABLE IF NOT EXISTS `" . $t_prefix . "template_tasks` (\r\n\t\t\t\t\t  `template_id` int(10) unsigned DEFAULT NULL,\r\n\t\t\t\t\t  `session_id` int(10) DEFAULT NULL,\r\n\t\t\t\t\t  `object_id` int(10) unsigned NOT NULL,\r\n\t\t\t\t\t  `parent_id` int(10) unsigned DEFAULT NULL,\r\n\t\t\t\t\t  `text` text COLLATE utf8_unicode_ci NOT NULL,\r\n\t\t\t\t\t  `due_date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',\r\n\t\t\t\t\t  `start_date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',\r\n\t\t\t\t\t  `assigned_to_contact_id` int(10) unsigned DEFAULT NULL,\r\n\t\t\t\t\t  `assigned_on` datetime DEFAULT NULL,\r\n\t\t\t\t\t  `assigned_by_id` int(10) unsigned DEFAULT NULL,\r\n\t\t\t\t\t  `time_estimate` int(10) unsigned NOT NULL DEFAULT '0',\r\n\t\t\t\t\t  `completed_on` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',\r\n\t\t\t\t\t  `completed_by_id` int(10) unsigned DEFAULT NULL,\r\n\t\t\t\t\t  `started_on` datetime DEFAULT NULL,\r\n\t\t\t\t\t  `started_by_id` int(10) unsigned NOT NULL,\r\n\t\t\t\t\t  `priority` int(10) unsigned DEFAULT '200',\r\n\t\t\t\t\t  `state` int(10) unsigned DEFAULT NULL,\r\n\t\t\t\t\t  `order` int(10) unsigned DEFAULT '0',\r\n\t\t\t\t\t  `milestone_id` int(10) unsigned DEFAULT NULL,\r\n\t\t\t\t\t  `is_template` tinyint(1) NOT NULL DEFAULT '0',\r\n\t\t\t\t\t  `from_template_id` int(10) NOT NULL DEFAULT '0',\r\n\t\t\t\t\t  `from_template_object_id` int(10) unsigned DEFAULT '0',\r\n\t\t\t\t\t  `repeat_end` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',\r\n\t\t\t\t\t  `repeat_forever` tinyint(1) NOT NULL,\r\n\t\t\t\t\t  `repeat_num` int(10) unsigned NOT NULL DEFAULT '0',\r\n\t\t\t\t\t  `repeat_d` int(10) unsigned NOT NULL,\r\n\t\t\t\t\t  `repeat_m` int(10) unsigned NOT NULL,\r\n\t\t\t\t\t  `repeat_y` int(10) unsigned NOT NULL,\r\n\t\t\t\t\t  `repeat_by` varchar(15) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '',\r\n\t\t\t\t\t  `object_subtype` int(10) unsigned NOT NULL DEFAULT '0',\r\n\t\t\t\t\t  `percent_completed` int(10) unsigned NOT NULL DEFAULT '0',\r\n\t\t\t\t\t  `use_due_time` tinyint(1) DEFAULT '0',\r\n\t\t\t\t\t  `use_start_time` tinyint(1) DEFAULT '0',\r\n\t\t\t\t\t  `original_task_id` int(10) unsigned DEFAULT '0',\r\n\t\t\t\t\t  `type_content` enum('text','html') NOT NULL DEFAULT 'text',\r\n\t\t\t\t\t  PRIMARY KEY (`object_id`),\r\n\t\t\t\t\t  KEY `parent_id` (`parent_id`),\r\n\t\t\t\t\t  KEY `completed_on` (`completed_on`),\r\n\t\t\t\t\t  KEY `order` (`order`),\r\n\t\t\t\t\t  KEY `milestone_id` (`milestone_id`),\r\n\t\t\t\t\t  KEY `priority` (`priority`),\r\n\t\t\t\t\t  KEY `assigned_to` USING HASH (`assigned_to_contact_id`)\r\n\t\t\t\t\t) ENGINE= InnoDB;\r\n\t\t\t\t\t\r\n\t\t\t\t\tCREATE TABLE IF NOT EXISTS `" . $t_prefix . "template_milestones` (\r\n\t\t\t\t\t  `template_id` int(10) unsigned DEFAULT NULL,\r\n\t\t\t\t\t  `session_id` int(10) DEFAULT NULL,\r\n\t\t\t\t\t  `object_id` int(10) unsigned NOT NULL,\r\n\t\t\t\t\t  `description` text COLLATE utf8_unicode_ci NOT NULL,\r\n\t\t\t\t\t  `due_date` datetime NOT NULL default '0000-00-00 00:00:00',\r\n\t\t\t\t\t  `is_urgent` BOOLEAN NOT NULL default '0',\r\n\t\t\t\t\t  `completed_on` datetime NOT NULL default '0000-00-00 00:00:00',\r\n\t\t\t\t\t  `completed_by_id` int(10) unsigned default NULL,\r\n\t\t\t\t\t  `is_template` BOOLEAN NOT NULL default '0',\r\n\t\t\t\t\t  `from_template_id` int(10) NOT NULL default '0',\r\n\t\t\t\t\t  `from_template_object_id` int(10) unsigned DEFAULT '0',\r\n\t\t\t\t\t  PRIMARY KEY  (`object_id`),\r\n\t\t\t\t\t  KEY `due_date` (`due_date`),\r\n\t\t\t\t\t  KEY `completed_on` (`completed_on`)\r\n\t\t\t\t\t) ENGINE= InnoDB;\r\n\t\t\t\t\t\r\n\t\t\t\t\t/* copy milestones */\r\n\t\t\t\t\tINSERT INTO `" . $t_prefix . "template_milestones`(`template_id`, `session_id`, `object_id`, `description`, `due_date`, `is_urgent`, `completed_on`, `completed_by_id`, `is_template`, `from_template_id`, `from_template_object_id`)\r\n\t\t\t\t\tSELECT " . $t_prefix . "template_objects.template_id,'0' AS `session_id` ," . $t_prefix . "project_milestones.`object_id`, `description`, `due_date`, `is_urgent`, `completed_on`, `completed_by_id`, `is_template`, `from_template_id`, `from_template_object_id`\r\n\t\t\t\t\tFROM `" . $t_prefix . "template_objects` \r\n\t\t\t\t\tINNER JOIN `" . $t_prefix . "project_milestones` \r\n\t\t\t\t\tON " . $t_prefix . "template_objects.object_id = " . $t_prefix . "project_milestones.object_id\r\n\t\t\t\t\tAND " . $t_prefix . "project_milestones.is_template =1\r\n\t\t\t\t\tON DUPLICATE KEY UPDATE " . $t_prefix . "template_milestones.template_id=" . $t_prefix . "template_milestones.template_id;\r\n\t\t\t\t\t\r\n\t\t\t\t\t/* delete from project milestones, milestones that are template milestones */\r\n\t\t\t\t\tDELETE FROM `" . $t_prefix . "project_milestones` WHERE `is_template` = 1;\r\n\t\t\t\t\t\r\n\t\t\t\t\t/* change the object type from project milestone to template milestone */\r\n\t\t\t\t\tUPDATE `" . $t_prefix . "objects` SET object_type_id = (SELECT id FROM `" . $t_prefix . "object_types` WHERE name = 'template_milestone')\r\n\t\t\t\t\tWHERE id IN (SELECT object_id FROM `" . $t_prefix . "template_milestones`);\r\n\t\t\t\t\t\r\n\t\t\t\t\tUPDATE `" . $t_prefix . "cron_events` set enabled=0, is_system=1 WHERE name='check_upgrade';\r\n\t\t\t\t\tupdate " . $t_prefix . "project_tasks set percent_completed=100 where completed_on <> '0000-00-00 00:00:00';\r\n\t\t\t\t";
         }
         if (version_compare($installed_version, '2.4.1-beta') <= 0) {
             $upgrade_script .= "\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\tVALUES ('mails panel', 'attach_to_notification', '1', 'BoolConfigHandler', '0', '0', NULL)\r\n\t\t\t\t\tON DUPLICATE KEY UPDATE name=name;\r\n\t\t\t\t";
             if (!$this->checkColumnExists($t_prefix . "project_files", "attach_to_notification", $this->database_connection)) {
                 $upgrade_script .= "\r\n\t\t\t\t\t\tALTER TABLE `" . $t_prefix . "project_files` ADD `attach_to_notification` TINYINT( 1 ) NOT NULL DEFAULT 0;\r\n\t\t\t\t\t";
             }
             if (!$this->checkColumnExists($t_prefix . "project_files", "default_subject", $this->database_connection)) {
                 $upgrade_script .= "\r\n\t\t\t\t\t\tALTER TABLE `" . $t_prefix . "project_files` ADD `default_subject` TEXT;\r\n\t\t\t\t\t";
             }
             $upgrade_script .= "\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\tVALUES ('general', 'notify_myself_too', 0, 'BoolConfigHandler', '0', '100', '')\r\n\t\t\t\t\tON DUPLICATE KEY UPDATE name=name;\r\n\t\t\t\t";
             $upgrade_script .= "\r\n\t\t\t\t\tALTER TABLE `" . $t_prefix . "contact_member_permissions` ADD INDEX (`member_id`);\r\n\t\t\t\t";
         }
     }
     if ($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) {
         if (version_compare($installed_version, '2.4-beta') < 0) {
             $while_condition = true;
             //add multi_assignment to template tasks table
             $upgrade_before_loop_script = $multi_assignment_create;
             //copy tasks
             $upgrade_before_loop_script .= "\r\n\t\t\t\t\t/* Copy tasks that are in templates objects */\r\n\t\t\t\t\tINSERT INTO `" . $t_prefix . "template_tasks`(`template_id`, `session_id`, `object_id`, `parent_id`, `text`, `due_date`, `start_date`, `assigned_to_contact_id`, `assigned_on`, `assigned_by_id`, `time_estimate`, `completed_on`, `completed_by_id`, `started_on`, `started_by_id`, `priority`, `state`, `order`, `milestone_id`, `is_template`, `from_template_id`, `from_template_object_id`, `repeat_end`, `repeat_forever`, `repeat_num`, `repeat_d`, `repeat_m`, `repeat_y`, `repeat_by`, `object_subtype`, `percent_completed`, `use_due_time`, `use_start_time`, `original_task_id`, `type_content`" . $multi_assignment . ")\r\n\t\t\t\t\tSELECT " . $t_prefix . "template_objects.template_id,'0' AS `session_id` ," . $t_prefix . "project_tasks.`object_id`, `parent_id`, `text`, `due_date`, `start_date`, `assigned_to_contact_id`, `assigned_on`, `assigned_by_id`, `time_estimate`, `completed_on`, `completed_by_id`, `started_on`, `started_by_id`, `priority`, `state`, `order`, `milestone_id`, `is_template`, `from_template_id`, `from_template_object_id`, `repeat_end`, `repeat_forever`, `repeat_num`, `repeat_d`, `repeat_m`, `repeat_y`, `repeat_by`, `object_subtype`, `percent_completed`, `use_due_time`, `use_start_time`, `original_task_id`, `type_content`" . $multi_assignment . "\r\n\t\t\t\t\tFROM `" . $t_prefix . "template_objects` \r\n\t\t\t\t\tINNER JOIN `" . $t_prefix . "project_tasks` \r\n\t\t\t\t\tON " . $t_prefix . "template_objects.object_id = " . $t_prefix . "project_tasks.object_id\r\n\t\t\t\t\tAND " . $t_prefix . "project_tasks.is_template =1\r\n\t\t\t\t\tON DUPLICATE KEY UPDATE session_id = 0;\r\n\t\t\t\t";
             // Copy subtasks for tasks that are in template tasks.
             $upgrade_loop_script = "\n\t\t\t\t\tINSERT INTO `" . $t_prefix . "template_tasks`(`template_id`, `session_id`, `object_id`, `parent_id`, `text`, `due_date`, `start_date`, `assigned_to_contact_id`, `assigned_on`, `assigned_by_id`, `time_estimate`, `completed_on`, `completed_by_id`, `started_on`, `started_by_id`, `priority`, `state`, `order`, `milestone_id`, `is_template`, `from_template_id`, `from_template_object_id`, `repeat_end`, `repeat_forever`, `repeat_num`, `repeat_d`, `repeat_m`, `repeat_y`, `repeat_by`, `object_subtype`, `percent_completed`, `use_due_time`, `use_start_time`, `original_task_id`, `type_content`" . $multi_assignment . ")\n\t\t\t\t\tSELECT '0' AS `template_id`,'0' AS `session_id`, pt.`object_id`, pt.`parent_id`, pt.`text`, pt.`due_date`, pt.`start_date`, pt.`assigned_to_contact_id`, pt.`assigned_on`, pt.`assigned_by_id`, pt.`time_estimate`, pt.`completed_on`, pt.`completed_by_id`, pt.`started_on`, pt.`started_by_id`, pt.`priority`, pt.`state`, pt.`order`, pt.`milestone_id`, pt.`is_template`, pt.`from_template_id`, pt.`from_template_object_id`, pt.`repeat_end`, pt.`repeat_forever`, pt.`repeat_num`, pt.`repeat_d`, pt.`repeat_m`, pt.`repeat_y`, pt.`repeat_by`, pt.`object_subtype`, pt.`percent_completed`, pt.`use_due_time`, pt.`use_start_time`, pt.`original_task_id`, pt.`type_content`" . $multi_assignment . "\r\n\t\t\t\t\tFROM `" . $t_prefix . "project_tasks` AS pt\n\t\t\t\t\tWHERE pt.parent_id IN\n\t\t\t\t\t(SELECT pt2.`object_id`\n\t\t\t\t\tFROM `" . $t_prefix . "template_tasks` AS pt2)\n\t\t\t\t\tON DUPLICATE KEY UPDATE " . $t_prefix . "template_tasks.parent_id = pt.parent_id;\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t/* copy template id from task to subtask */\r\n\t\t\t\t\tUPDATE " . $t_prefix . "template_tasks AS t1, " . $t_prefix . "template_tasks AS t2 SET t1.template_id=t2.template_id\r\n\t\t\t\t\tWHERE t1.parent_id=t2.object_id;\r\n\t\t\t\t";
             $check_continue_condition = "\n\t\t\t\t\tSELECT object_id\n\t\t\t\t\tFROM `" . $t_prefix . "project_tasks` AS pt\n\t\t\t\t\tWHERE pt.parent_id IN (SELECT pt2.object_id\n\t\t\t\t\t\tFROM `" . $t_prefix . "template_tasks` AS pt2)\n\t\t\t\t\tAND NOT EXISTS (SELECT * FROM `" . $t_prefix . "template_tasks` AS pt3\n\t\t\t\t\t\tWHERE pt3.object_id = pt.object_id);\n\t\t\t\t\t";
             $upgrade_after_loop_script .= "\n\t\t\t\t\t/* insert into template objects subtasks */\r\n\t\t\t\t\tINSERT INTO `" . $t_prefix . "template_objects`(`template_id`, `object_id`)\r\n\t\t\t\t\tSELECT tt.template_id, tt.object_id\r\n\t\t\t\t\tFROM `" . $t_prefix . "template_tasks` AS tt\r\n\t\t\t\t\tWHERE NOT EXISTS (SELECT * FROM `" . $t_prefix . "template_objects` AS to1 WHERE tt.object_id = to1.object_id);\r\n\t\t\t\t\tUPDATE `" . $t_prefix . "template_objects` t1, `" . $t_prefix . "template_objects` t2\r\n\t\t\t\t\tSET t1.created_by_id = t2.created_by_id, t1.created_on = t2.created_on\r\n\t\t\t\t\tWHERE t1.template_id = t2.template_id AND t2.created_by_id IS NOT NULL;\r\n\t\t\t\t\t\r\n\t\t\t\t\t/* delete from project task, tasks that are template tasks */\n\t\t\t\t\tDELETE FROM `" . $t_prefix . "project_tasks` WHERE `is_template` = 1;\n\n\t\t\t\t\t/* change the object type from project task to template task */\n\t\t\t\t\tUPDATE `" . $t_prefix . "objects` SET object_type_id = (SELECT id FROM `" . $t_prefix . "object_types` WHERE name = 'template_task')\n\t\t\t\t\tWHERE id IN (SELECT object_id FROM `" . $t_prefix . "template_tasks`);\r\n\t\t\t\t";
             // Copy tasks
             if (!$this->executeMultipleQueries($upgrade_before_loop_script, $total_queries, $executed_queries, $this->database_connection)) {
                 $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true);
                 return false;
             }
             while ($while_condition) {
                 // Copy subtasks
                 if ($this->executeMultipleQueries($upgrade_loop_script, $total_queries, $executed_queries, $this->database_connection)) {
                     // Check if continue
                     $res = mysql_query($check_continue_condition, $this->database_connection);
                     $rows = array();
                     while ($row = mysql_fetch_array($res)) {
                         $rows[] = $row;
                     }
                     // is empty?
                     if (!is_array($rows) || count($rows) < 1) {
                         $while_condition = false;
                     }
                 } else {
                     $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true);
                     return false;
                 }
             }
         }
         if (version_compare($installed_version, '2.4-rc') < 0) {
             $upgrade_after_loop_script .= "\r\n\t\t\t\t\tDELETE FROM `" . $t_prefix . "object_members` where object_id IN (SELECT object_id FROM  `" . TABLE_PREFIX . "template_tasks`);\r\n\t\t\t\t\tDELETE FROM `" . $t_prefix . "sharing_table` where object_id IN (SELECT object_id FROM  `" . TABLE_PREFIX . "template_tasks`);\r\n\t\t\t\t\tINSERT INTO `" . $t_prefix . "config_options` (`category_name`,`name`,`value`,`config_handler_class`,`is_system`) VALUES\r\n\t\t\t\t\t\t('general', 'add_default_permissions_for_users', '0', 'BoolConfigHandler', '0')\r\n\t\t\t\t\tON DUPLICATE KEY UPDATE name=name;\r\n\t\t\t\t";
         }
         // after loop
         if (!$this->executeMultipleQueries($upgrade_after_loop_script, $total_queries, $executed_queries, $this->database_connection)) {
             $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true);
             return false;
         }
         $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.5.0.4') < 0) {
         if (!$this->checkColumnExists("queued_emails", "attachments", $this->database_connection)) {
             $sqls = "\r\n\t\t\t\t\tALTER TABLE " . $t_prefix . "queued_emails` ADD COLUMN `attachments` TEXT;\r\n\t\t\t\t";
             $this->executeMultipleQueries($sqls, $t_queries, $e_queries, $this->database_connection);
         }
     }
     $this->printMessage('Feng Office has been upgraded. You are now running Feng Office ' . $this->getVersionTo() . ' Enjoy!');
     tpl_assign('additional_steps', $additional_upgrade_steps);
 }
/**
 * Render one project's application logs
 * 
 * This helper will render array of log entries.
 *
 * @param array $project The project.
 * @param array $log_entries An array of entries for this project.
 * @return null
 */
function render_project_application_logs($project, $log_entries)
{
    if (config_option('display_application_logs', true)) {
        tpl_assign('application_logs_project', $project);
        tpl_assign('application_logs_entries', $log_entries);
        return tpl_fetch(get_template_path('render_project_application_logs', 'application'));
    }
    return '';
}
	/**
	 * Execute the script
	 *
	 * @param void
	 * @return boolean
	 */
	function execute() {
		if (!@mysql_ping($this->database_connection)) {
			if ($dbc = mysql_connect(DB_HOST, DB_USER, DB_PASS)) {
				if (mysql_select_db(DB_NAME, $dbc)) {
					$this->printMessage('Upgrade script has connected to the database.');
				} else {
					$this->printMessage('Failed to select database ' . DB_NAME);
					return false;
				}
				$this->setDatabaseConnection($dbc);
			} else {
				$this->printMessage('Failed to connect to database');
				return false;
			}
		}
		
		// ---------------------------------------------------
		//  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;
		$additional_upgrade_steps = array();
		
		// RUN QUERIES
		$total_queries = 0;
		$executed_queries = 0;

		$upgrade_script = "";

		$original_version_from = array_var(array_var($_POST, 'form_data'), 'upgrade_from', $installed_version);
		if (version_compare($installed_version, $this->getVersionFrom()) <= 0 && version_compare($original_version_from, '2.0.0.0-beta') > 0
			 && (!isset($_SESSION['from_feng1']) || !$_SESSION['from_feng1'])) {
			// upgrading from a version lower than this script's 'from' version
			$upgrade_script = tpl_fetch(get_template_path('db_migration/2_2_pamplona'));
		} else {
			
			//UPDATE VERSION 2.2-beta
			if (version_compare($installed_version, '2.2-beta') < 0) {
				//ACTIVITY FEED
				$upgrade_script .= "
					INSERT INTO `".$t_prefix."widgets` (`name`, `title`, `plugin_id`, `path`, `default_options`, `default_section`, `default_order`)
						VALUES ('activity_feed', 'activity_feed', 0, '', '', 'left', 0)
					ON DUPLICATE KEY UPDATE name=name;
					INSERT INTO `".$t_prefix."contact_config_options` (`category_name`, `name`, `default_value`, `config_handler_class`, `is_system`, `option_order`, `dev_comment`)
						VALUES ('dashboard', 'filters_dashboard', '0,0,10,0', 'StringConfigHandler', '0', '0', 'first position: entry to see the dimension, second position: view timeslot, third position: recent activities to show, fourth position: view views and downloads')
					ON DUPLICATE KEY UPDATE name=name;
				";
				if (!$this->checkColumnExists($t_prefix."contact_config_option_values", "member_id", $this->database_connection)) {
					$upgrade_script .= "
						ALTER TABLE `".$t_prefix."contact_config_option_values` ADD `member_id` INT( 10 ) UNSIGNED NULL DEFAULT '0';
						ALTER TABLE `".$t_prefix."contact_config_option_values` drop PRIMARY KEY;
						ALTER TABLE `".$t_prefix."contact_config_option_values` ADD PRIMARY KEY ( `option_id` , `contact_id` , `member_id` );
					";
				}
				
				// color config options
				$upgrade_script .= "
					INSERT INTO `".$t_prefix."config_categories` (`name`, `is_system`) VALUES ('brand_colors', 1) ON DUPLICATE KEY UPDATE name=name;
					INSERT INTO `".$t_prefix."config_options` (`category_name`,`name`,`value`,`config_handler_class`,`is_system`) VALUES
						('brand_colors', 'brand_colors_head_back', '', 'StringConfigHandler', 1),
						('brand_colors', 'brand_colors_head_font', '', 'StringConfigHandler', 1),
						('brand_colors', 'brand_colors_tabs_back', '', 'StringConfigHandler', 1),
						('brand_colors', 'brand_colors_tabs_font', '', 'StringConfigHandler', 1)
					ON DUPLICATE KEY UPDATE name=name;
				";
				
				//SYNC GOOGLE CALENDARS
				$upgrade_script .= "
					ALTER TABLE `".$t_prefix."project_events` CHANGE `special_id` `special_id` TEXT CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL;
				";
				//CLASSIFY EMAILS
				if (!$this->checkColumnExists($t_prefix."project_file_revisions", "hash", $this->database_connection)) {
					$upgrade_script .= "
						ALTER TABLE `".$t_prefix."project_file_revisions` ADD `hash` TEXT CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL;
					";
				}
				
				//SCRIPT UPDATE OLD NOTES SEARCH BY NAME
				$upgrade_script .= "
					INSERT INTO `".$t_prefix."searchable_objects` (`rel_object_id`, `column_name`, `content`, `contact_id`)
						SELECT id,'name',name,'0' FROM `".$t_prefix."objects` WHERE `object_type_id` = (SELECT id FROM ".$t_prefix."object_types WHERE name='message')
					ON DUPLICATE KEY UPDATE rel_object_id=id,column_name='name';
				";

				//add the contact tab to the database if it does not exist
				if (!$this->checkValueExists($t_prefix."tab_panels", 'id', 'contacts-panel', $this->database_connection)) {
					$upgrade_script .= "
						INSERT 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 
						 ('contacts-panel','contacts','ico-contacts',1,'contact','init','','',0,'system',7,0, (SELECT id FROM ".$t_prefix."object_types WHERE name='contact'))
						ON DUPLICATE KEY UPDATE name=name;
						INSERT INTO `".$t_prefix."tab_panel_permissions` (`permission_group_id`, `tab_panel_id`) VALUES 
						 ((SELECT id FROM ".$t_prefix."permission_groups WHERE name = 'Super Administrator'),	'contacts-panel'),
						 ((SELECT id FROM ".$t_prefix."permission_groups WHERE name = 'Administrator'), 'contacts-panel'),  
						 ((SELECT id FROM ".$t_prefix."permission_groups WHERE name = 'Manager'), 'contacts-panel'),  
						 ((SELECT id FROM ".$t_prefix."permission_groups WHERE name = 'Executive'), 'contacts-panel'),  
						 ((SELECT id FROM ".$t_prefix."permission_groups WHERE name = 'Collaborator Customer'), 'contacts-panel'),  
						 ((SELECT id FROM ".$t_prefix."permission_groups WHERE name = 'Non-Exec Director'), 'contacts-panel')
						ON DUPLICATE KEY UPDATE tab_panel_id=tab_panel_id;
					";
				}
				
				//change tasks and notes to WYSIWYG text
				$upgrade_script .="
					UPDATE `".$t_prefix."config_options` SET `value` = '1' WHERE `".$t_prefix."config_options`.`name` = 'wysiwyg_messages' OR `".$t_prefix."config_options`.`name` = 'wysiwyg_tasks';
				";
			}
			
			if (version_compare($installed_version, '2.2.0.1') < 0) {
				if (!$this->checkColumnExists($t_prefix."dimensions", 'permission_query_method', $this->database_connection)) {
					$upgrade_script .= "
						ALTER TABLE `".$t_prefix."dimensions` ADD COLUMN `permission_query_method` ENUM('mandatory','not_mandatory') NOT NULL DEFAULT 'mandatory';
					";
				}
			}
			
			if (version_compare($installed_version, '2.2.1-beta') < 0) {
				$upgrade_script .= "
					UPDATE ".$t_prefix."contact_config_options SET default_value='due_date' WHERE name='tasksGroupBy';
					INSERT INTO `".$t_prefix."config_options` (`category_name`,`name`,`value`,`config_handler_class`,`is_system`) VALUES
						('general', 'use_milestones', (SELECT count(*) FROM ".$t_prefix."project_milestones)>0, 'BoolConfigHandler', 0),
						('general', 'show_tab_icons', '1', 'BoolConfigHandler', '0')
					ON DUPLICATE KEY UPDATE name=name;
				";
			}
			
			if (version_compare($installed_version, '2.2.2-beta') < 0 ) {
				if (!$this->checkColumnExists($t_prefix."system_permissions", "can_see_assigned_to_other_tasks", $this->database_connection)) {
					$upgrade_script .= "
						ALTER TABLE `".$t_prefix."system_permissions` ADD COLUMN `can_see_assigned_to_other_tasks` TINYINT(1) UNSIGNED NOT NULL DEFAULT 1;
					";
				}
				$upgrade_script .= "
					UPDATE `".$t_prefix."system_permissions` SET can_see_assigned_to_other_tasks = 1;
					INSERT INTO ".$t_prefix."widgets (name, title, plugin_id, path, default_options, default_section, default_order) VALUES
					 ('completed_tasks_list', 'completed tasks list', 0, '', '', 'right', 150)
					ON DUPLICATE KEY UPDATE name=name;
				";
			}
			
			if (version_compare($installed_version, '2.2.3-beta') < 0 ) {
				if (!$this->checkColumnExists($t_prefix."reports", "ignore_context", $this->database_connection)) {
					$upgrade_script .= "
						ALTER TABLE `".$t_prefix."reports`
						 ADD COLUMN `ignore_context` BOOLEAN NOT NULL DEFAULT 1,
						 ADD INDEX `object_type`(`report_object_type_id`);
					";
				}
			}
			
			if (version_compare($installed_version, '2.2.4.1') < 0 ) {
				if (!$this->checkColumnExists($t_prefix."dimensions", "is_required", $this->database_connection)) {
					$upgrade_script .= "
						ALTER TABLE `".$t_prefix."dimensions` ADD COLUMN `is_required` BOOLEAN NOT NULL DEFAULT 0;
						INSERT INTO `".$t_prefix."contact_config_categories` (`name`, `is_system`, `type`, `category_order`) VALUES
						 ('listing preferences', 0, 0, 10)
						ON DUPLICATE KEY UPDATE name=name;
						INSERT INTO ".$t_prefix."searchable_objects (rel_object_id, column_name, content, contact_id)
						 SELECT id, 'object_id', id, 0 FROM ".$t_prefix."objects
						ON DUPLICATE KEY UPDATE rel_object_id=rel_object_id;
					";
				}
			}
		}
		
		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.2-beta') < 0) {
			// drop brand_colors column and use config options
			if ($this->checkColumnExists($t_prefix."contacts", 'brand_colors', $this->database_connection)) {
				$db_res = mysql_query("SELECT brand_colors FROM ".$t_prefix."contacts WHERE is_company=1 LIMIT 1", $this->database_connection);
				$row = mysql_fetch_assoc($db_res);
				$colors = explode("#", $row['brand_colors']);
				$head_back = (isset($colors[1]) && $colors[1] != "" ? $colors[1] : "000000");
				$tabs_back = (isset($colors[2]) && $colors[2] != "" ? $colors[2] : "14780e");
				$tabs_font = (isset($colors[3]) && $colors[3] != "" ? $colors[3] : "ffffff");
				$head_font = (isset($colors[4]) && $colors[4] != "" ? $colors[4] : "ffffff");
				
				$sqls = "
					UPDATE ".$t_prefix."config_options SET value='$head_back' WHERE name='brand_colors_head_back';
					UPDATE ".$t_prefix."config_options SET value='$head_font' WHERE name='brand_colors_head_font';
					UPDATE ".$t_prefix."config_options SET value='$tabs_back' WHERE name='brand_colors_tabs_back';
					UPDATE ".$t_prefix."config_options SET value='$tabs_font' WHERE name='brand_colors_tabs_font';
					ALTER TABLE ".$t_prefix."contacts DROP COLUMN brand_colors;
				";
				$this->executeMultipleQueries($sqls, $t_queries, $e_queries, $this->database_connection);
			}
		}
		
		$this->printMessage('Feng Office has been upgraded. You are now running Feng Office '.$this->getVersionTo().' Enjoy!');

		tpl_assign('additional_steps', $additional_upgrade_steps);

	} // execute
Example #27
0
	/**
	 * Contruct controller and execute specific action
	 *
	 * @access public
	 * @param string $controller_name
	 * @param string $action
	 * @return null
	 */
	static function executeAction($controller_name, $action) {
   		$max_users = config_option('max_users');
		if ($max_users && Contacts::count() > $max_users) {
	        echo lang("error").": ".lang("maximum number of users exceeded error");
	        return;
    	}
		ajx_check_login();
		
		Env::useController($controller_name);

		$controller_class = Env::getControllerClass($controller_name);
		if(!class_exists($controller_class, false)) {
			throw new ControllerDnxError($controller_name);
		} // if

		$controller = new $controller_class();
		if(!instance_of($controller, 'Controller')) {
			throw new ControllerDnxError($controller_name);
		} // if

		if (is_ajax_request()) {
			// if request is an ajax request return a json response
			
			// execute the action
			$controller->setAutoRender(false);
			$controller->execute($action);
			
			// fill the response
			$response = AjaxResponse::instance();
			if (!$response->hasCurrent()) {
				// set the current content
				$response->setCurrentContent("html", $controller->getContent(), page_actions(), ajx_get_panel());
			}
			$response->setEvents(evt_pop());
			$error = flash_pop('error');
			$success = flash_pop('success');
			if (!is_null($error)) {
				$response->setError(1, clean($error));
			} else if (!is_null($success)) {
				$response->setError(0, clean($success));
			}
			
			// display the object as json

			tpl_assign("object", $response);
			$content = tpl_fetch(Env::getTemplatePath("json"));
			tpl_assign("content_for_layout", $content);
			TimeIt::start("Transfer");
			if (is_iframe_request()) {
				tpl_display(Env::getLayoutPath("iframe"));
			} else {
				tpl_display(Env::getLayoutPath("json"));
			}
			TimeIt::stop();
		} else {
			return $controller->execute($action);
		}
	} // executeAction
 /**
  * Execute the script
  *
  * @param void
  * @return boolean
  */
 function execute()
 {
     if (!@mysql_ping($this->database_connection)) {
         if ($dbc = mysql_connect(DB_HOST, DB_USER, DB_PASS)) {
             if (mysql_select_db(DB_NAME, $dbc)) {
                 $this->printMessage('Upgrade script has connected to the database.');
             } else {
                 $this->printMessage('Failed to select database ' . DB_NAME);
                 return false;
             }
             $this->setDatabaseConnection($dbc);
         } else {
             $this->printMessage('Failed to connect to database');
             return false;
         }
     }
     // ---------------------------------------------------
     //  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;
     $additional_upgrade_steps = array();
     // RUN QUERIES
     $total_queries = 0;
     $executed_queries = 0;
     $upgrade_script = "";
     $original_version_from = array_var(array_var($_POST, 'form_data'), 'upgrade_from', $installed_version);
     if (version_compare($installed_version, $this->getVersionFrom()) <= 0 && version_compare($original_version_from, '2.0.0.0-beta') > 0 && (!isset($_SESSION['from_feng1']) || !$_SESSION['from_feng1'])) {
         // upgrading from a version lower than this script's 'from' version
         $upgrade_script = tpl_fetch(get_template_path('db_migration/2_1_molleja'));
     } else {
         // UPDATE VERSION 2.1-beta
         if (version_compare($installed_version, '2.1-beta') < 0) {
             if (!$this->checkColumnExists($t_prefix . "members", 'archived_on', $this->database_connection)) {
                 $upgrade_script .= "ALTER TABLE `" . $t_prefix . "members`\r\n\t\t\t\t\t\t ADD COLUMN `archived_by_id` INTEGER UNSIGNED NOT NULL,\r\n\t\t\t\t\t\t ADD COLUMN `archived_on` DATETIME NOT NULL,\r\n\t\t\t\t\t\t ADD INDEX `archived_on`(`archived_on`);";
             }
             // INDEXED ODT AND FODT
             $upgrade_script .= "\r\n\t\t\t\t\tINSERT INTO `" . $t_prefix . "file_types` (`id` ,`extension` ,`icon` ,`is_searchable` ,`is_image`) VALUES\r\n\t\t\t\t\t ('34', 'odt', 'doc.png', '1', '0'), ('35', 'fodt', 'doc.png', '1', '0')\r\n\t\t\t\t\tON DUPLICATE KEY UPDATE id=id;";
         }
         // UPDATE VERSION 2.1-rc
         if (version_compare($installed_version, '2.1-rc') < 0) {
             //TYPES IN PERMISSION GROUPS
             if (!$this->checkColumnExists($t_prefix . "permission_groups", 'type', $this->database_connection)) {
                 $upgrade_script .= "\r\n\t\t\t\t\t\tALTER TABLE  `" . $t_prefix . "permission_groups` ADD `type` ENUM(  'roles',  'permission_groups',  'user_groups' ) NOT NULL;";
             }
             $upgrade_script .= "\r\n\t\t\t\t\tUPDATE `" . $t_prefix . "permission_groups` SET `type` = 'roles' WHERE `id` <= 13;\r\n\t\t\t\t\tUPDATE `" . $t_prefix . "permission_groups` SET `type` = 'permission_groups' WHERE `contact_id` > 0;\r\n\t\t\t\t\tUPDATE `" . $t_prefix . "permission_groups` SET `type` = 'user_groups' WHERE `contact_id` = 0 AND `id` > 13;";
         }
         //UPDATE VERSION 2.1
         if (version_compare($installed_version, '2.1') < 0) {
             // FILE EXTENSION PREVENTION UPLOADING
             if (!$this->checkColumnExists($t_prefix . "file_types", 'is_allow', $this->database_connection)) {
                 $upgrade_script .= "\r\n\t\t\t\t\t\tALTER TABLE `" . $t_prefix . "file_types` ADD COLUMN `is_allow` TINYINT(1) NOT NULL DEFAULT '1';";
             }
             //CLASIFFY EVENTS
             if (!$this->checkColumnExists($t_prefix . "external_calendar_users", 'related_to', $this->database_connection)) {
                 $upgrade_script .= "\r\n\t\t\t\t\t\tALTER TABLE `" . $t_prefix . "external_calendar_users` ADD `related_to` VARCHAR( 255 ) NOT NULL;";
             }
             //PERFORMANCE SYNC EVENTS
             if (!$this->checkColumnExists($t_prefix . "project_events", 'update_sync', $this->database_connection)) {
                 $upgrade_script .= "\r\n\t\t\t\t\t\tALTER TABLE `" . $t_prefix . "project_events` ADD `update_sync` DATETIME NOT NULL AFTER `special_id`;";
             }
         }
     }
     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);
 }
Example #29
0
 }
 /* 格式化数据量大小 */
 $tpl['stat']['size'] = bitunit($tpl['stat']['size']);
 /* 初始化页面信息 */
 $tpl['_body'] = 'list';
 /* ------------------------------------------------------ */
 // - 异步 - 列表页,列表查询
 /* ------------------------------------------------------ */
 if ($_REQUEST['act'] == 'list') {
     /* 列表查询 */
     if ($_REQUEST['actsub'] == 'query') {
         /* 初始化页面信息 */
         $tpl['_bodysub'] = 'query';
     }
     /* 返回JSON */
     make_json_ok('', tpl_fetch('db_optimize.html', $tpl));
 } else {
     /* 初始化页面信息 */
     $tpl['_header'] = 'title';
     /* 取得管理员的优化操作 */
     $m_aa = admin_module_acts('db_optimize.php');
     $m_ab = filter_module_acts($m_aa, array('optimize'), true);
     /* 操作属性 */
     $attribs = array();
     $attribs['optimize']['icon'] = 'optimize';
     $attribs['optimize']['onclick'] = 'deal_dboptimize()';
     /* 初始化页面信息 */
     $tpl['title'] = admin_privilege_name_fk('db_optimize.php', 'optimize');
     //权限名称
     $tpl['titleacts'] = format_module_acts($m_ab, $attribs, 'btn');
     //格式化模块的操作(非内嵌)
/**
 * @param array of string $pluginNames
 */
static function executeInstaller($name) {
	
	$table_prefix = TABLE_PREFIX;
	tpl_assign('table_prefix', $table_prefix);
	
	$default_charset = 'DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci';
	tpl_assign('default_charset', $default_charset);
	
	$default_collation = 'collate utf8_unicode_ci';
	tpl_assign('default_collation', $default_collation);
	
	$engine = DB_ENGINE;
	tpl_assign('engine', $engine);
		
	try {
		$path = ROOT . "/plugins/$name/info.php";
		if (file_exists ( $path )) {
			DB::beginWork ();
			$pluginInfo = include_once $path;
			
			//0. Check if exists in plg table
			$sql = "SELECT id FROM " . TABLE_PREFIX . "plugins WHERE name = '$name' ";
			$plg_obj = DB::executeOne($sql);
			if (! $plg_obj) {
				//1. Insert into PLUGIN TABLE
				$cols = "name, is_installed, is_activated, version";
				$values = "'$name', 1, 1 ,'".array_var ( $pluginInfo, 'version' )."'";
				if (is_numeric ( array_var ( $pluginInfo, 'id' ) )) {
					$cols = "id, " . $cols;
					$values = array_var ( $pluginInfo, 'id' ) . ", " . $values;
				}
				$sql = "INSERT INTO " . TABLE_PREFIX . "plugins ($cols) VALUES ($values) ON DUPLICATE KEY UPDATE name=name";
				DB::executeOne($sql);
				$id = DB::lastInsertId();
				$pluginInfo ['id'] = $id;
				
			} else {
				$id = $plg_obj['id'];
				$pluginInfo ['id'] = $id;
			}
			
			//2. IF Plugin defines types, INSERT INTO ITS TABLE
			if (count ( array_var ( $pluginInfo, 'types' ) )) {
				foreach ( $pluginInfo ['types'] as $k => $type ) {
					if (isset ( $type ['name'] )) {
						$sql = "
							INSERT INTO " . TABLE_PREFIX . "object_types (name, handler_class, table_name, type, icon, plugin_id)
							 	VALUES (
							 	'" . array_var ( $type, "name" ) . "', 
							 	'" . array_var ( $type, "handler_class" ) . "', 
							 	'" . array_var ( $type, "table_name" ) . "', 
							 	'" . array_var ( $type, "type" ) . "', 
							 	'" . array_var ( $type, "icon" ) . "', 
								$id
							) ON DUPLICATE KEY UPDATE name=name";
						
						DB::executeOne($sql);
						$last_id = DB::lastInsertId();
						$pluginInfo['types'][$k]['id'] = $last_id;
						$type['id'] = $last_id;
					}
				}
			}
			
			//2. IF Plugin defines tabs, INSERT INTO ITS TABLE
			if (count ( array_var ( $pluginInfo, 'tabs' ) )) {
				foreach ( $pluginInfo ['tabs'] as $k => $tab ) {
					if (isset ( $tab ['title'] )) {
						$type_id = array_var ( $type, "id" );
						$sql = "
							INSERT INTO " . TABLE_PREFIX . "tab_panels (
								id,
								title, 
								icon_cls, 
								refresh_on_context_change, 
								default_controller, 
								default_action, 
								initial_controller, 
								initial_action, 
								enabled, 
								type,  
								plugin_id, 
								object_type_id )
						 	VALUES (
						 		'" . array_var ( $tab, 'id' ) . "', 
						 		'" . array_var ( $tab, 'title' ) . "', 
						 		'" . array_var ( $tab, 'icon_cls' ) . "',
						 		'" . array_var ( $tab, 'refresh_on_context_change' ) . "',
						 		'" . array_var ( $tab, 'default_controller' ) . "',
						 		'" . array_var ( $tab, 'default_action' ) . "',
								'" . array_var ( $tab, 'initial_controller' ) . "',
								'" . array_var ( $tab, 'initial_action' ) . "',
								'" . array_var ( $tab, 'enabled', 1 ) . "',
								'" . array_var ( $tab, 'type' ) . "',
								$id,
								" . array_var ( $tab, 'object_type_id' ) . "
							) ON DUPLICATE KEY UPDATE name=name";
						
						DB::executeOne($sql);
						
						// INSERT INTO TAB PANEL PERMISSSION
						$sql = "
							INSERT INTO " . TABLE_PREFIX . "tab_panel_permissions (
								permission_group_id,
								tab_panel_id 
							)
						 	VALUES ( 1,'" . array_var ( $tab, 'id' ) . "' ),  ( 2,'" . array_var ( $tab, 'id' ) . "' )  ON DUPLICATE KEY UPDATE permission_group_id = permission_group_id ";
						
						DB::executeOne($sql);
					}
				}
			}
			
			// Create schema sql query
			
			$schema_creation = ROOT . "/plugins/$name/install/sql/mysql_schema.php";
			if (file_exists ( $schema_creation )) {
				$total_queries = 0;
				$executed_queries = 0;
				executeMultipleQueries ( tpl_fetch ( $schema_creation ), $total_queries, $executed_queries );
				Logger::log("Schema created for plugin $name");
			}
			// Create schema sql query
			$schema_query = ROOT . "/plugins/$name/install/sql/mysql_initial_data.php";
			if (file_exists ( $schema_query )) {
				$total_queries = 0;
				$executed_queries = 0;
				executeMultipleQueries ( tpl_fetch ( $schema_query ), $total_queries, $executed_queries );
				Logger::log ( "Initial data loaded for plugin  '$name'." . mysql_error () );
			}
			
			$install_script = ROOT . "/plugins/$name/install/install.php";
			if (file_exists ( $install_script )) {
				include_once $install_script;
			}
			DB::commit ();
			return true;
		}
		
	} catch (Exception $e) {
		//echo $e->getMessage();
		DB::rollback();
		throw $e;
	}
	
	return false;
}