/** * init the test frameworks * */ public function initFramework() { Setup_Core::initFramework(); //$this->getConfig(); Tinebase_Core::startCoreSession(); Tinebase_Core::set('frameworkInitialized', true); }
/** * handler for command line scripts * * @return boolean */ public function handle() { try { $opts = new Zend_Console_Getopt(array('help|h' => 'Display this help Message', 'verbose|v' => 'Output messages', 'config|c=s' => 'Path to config.inc.php file', 'setconfig' => 'Update config. To specify the key and value, append \' -- configKey="your_key" configValue="your config value"\' Examples: setup.php --setconfig -- configkey=sample1 configvalue=value11 setup.php --setconfig -- configkey=sample2 configvalue=arrayKey1:Value1,arrayKey2:value2', 'check_requirements' => 'Check if all requirements are met to install and run tine20', 'create_admin' => 'Create new admin user (or reactivate if already exists)', 'install-s' => 'Install applications [All] or comma separated list;' . ' To specify the login name and login password of the admin user that is created during installation, append \' -- adminLoginName="admin" adminPassword="******"\'' . ' To add imap or smtp settings, append (for example) \' -- imap="host:mail.example.org,port:143,dbmail_host:localhost" smtp="ssl:tls"\'', 'update-s' => 'Update applications [All] or comma separated list', 'uninstall-s' => 'Uninstall application [All] or comma separated list', 'list-s' => 'List installed applications', 'sync_accounts_from_ldap' => 'Import user and groups from ldap', 'egw14import' => 'Import user and groups from egw14 Examples: setup.php --egw14import egwdbhost egwdbuser egwdbpass egwdbname latin1 setup.php --egw14import egwdbhost egwdbuser egwdbpass egwdbname utf8')); $opts->parse(); } catch (Zend_Console_Getopt_Exception $e) { echo "Invalid usage: {$e->getMessage()}\n\n"; echo $e->getUsageMessage(); exit; } if (count($opts->toArray()) === 0 || $opts->h || empty($opts->install) && empty($opts->update) && empty($opts->uninstall) && empty($opts->list) && empty($opts->sync_accounts_from_ldap) && empty($opts->egw14import) && empty($opts->check_requirements) && empty($opts->create_admin) && empty($opts->setconfig)) { echo $opts->getUsageMessage(); exit; } if ($opts->config) { // add path to config.inc.php to include path $path = strstr($opts->config, 'config.inc.php') !== false ? dirname($opts->config) : $opts->config; set_include_path($path . PATH_SEPARATOR . get_include_path()); } Setup_Core::initFramework(); if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Is cli request. method: ' . (isset($opts->mode) ? $opts->mode : 'EMPTY')); } $setupServer = new Setup_Frontend_Cli(); #$setupServer->authenticate($opts->username, $opts->password); return $setupServer->handle($opts); }
/** * handler for JSON api requests * * @return JSON */ public function handle() { try { // init server and request first $server = new Zend_Json_Server(); $server->setClass('Setup_Frontend_Json', 'Setup'); $server->setClass('Tinebase_Frontend_Json', 'Tinebase'); $server->setAutoHandleExceptions(false); $server->setAutoEmitResponse(false); $request = new Zend_Json_Server_Request_Http(); Setup_Core::initFramework(); $method = $request->getMethod(); $jsonKey = isset($_SERVER['HTTP_X_TINE20_JSONKEY']) ? $_SERVER['HTTP_X_TINE20_JSONKEY'] : ''; Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' is JSON request. method: ' . $method); $anonymnousMethods = array('Setup.getAllRegistryData', 'Setup.login', 'Tinebase.getAvailableTranslations', 'Tinebase.getTranslations', 'Tinebase.setLocale'); if (!Setup_Core::configFileExists()) { $anonymnousMethods = array_merge($anonymnousMethods, array('Setup.envCheck')); } // check json key for all methods but some exceptoins if (!in_array($method, $anonymnousMethods) && Setup_Core::configFileExists() && (empty($jsonKey) || $jsonKey != Setup_Core::get('jsonKey') || !Setup_Core::isRegistered(Setup_Core::USER))) { if (!Setup_Core::isRegistered(Setup_Core::USER)) { Setup_Core::getLogger()->INFO(__METHOD__ . '::' . __LINE__ . ' Attempt to request a privileged Json-API method without authorisation from "' . $_SERVER['REMOTE_ADDR'] . '". (session timeout?)'); throw new Tinebase_Exception_AccessDenied('Not Authorised', 401); } else { Setup_Core::getLogger()->WARN(__METHOD__ . '::' . __LINE__ . ' Fatal: got wrong json key! (' . $jsonKey . ') Possible CSRF attempt!' . ' affected account: ' . print_r(Setup_Core::getUser(), true) . ' request: ' . print_r($_REQUEST, true)); throw new Tinebase_Exception_AccessDenied('Not Authorised', 401); } } $response = $server->handle($request); } catch (Exception $exception) { $response = $this->_handleException($server, $request, $exception); } echo $response; }
/** * get create table statement * * @param Setup_Backend_Schema_Table_Abstract $_table * @return string */ public function getCreateStatement(Setup_Backend_Schema_Table_Abstract $_table) { $statement = "CREATE TABLE IF NOT EXISTS `" . SQL_TABLE_PREFIX . $_table->name . "` (\n"; $statementSnippets = array(); foreach ($_table->fields as $field) { if (isset($field->name)) { $statementSnippets[] = $this->getFieldDeclarations($field); } } foreach ($_table->indices as $index) { if ($index->foreign) { $statementSnippets[] = $this->getForeignKeyDeclarations($index); } else { $statementSnippets[] = $this->getIndexDeclarations($index); } } $statement .= implode(",\n", $statementSnippets) . "\n)"; if (isset($_table->engine)) { $statement .= " ENGINE=" . $_table->engine . " DEFAULT CHARSET=" . $_table->charset; } else { $statement .= " ENGINE=InnoDB DEFAULT CHARSET=utf8 "; } if (isset($_table->comment)) { $statement .= " COMMENT='" . $_table->comment . "'"; } if (Setup_Core::isLogLevel(Zend_Log::TRACE)) { Setup_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' ' . $statement); } return $statement; }
/** * Call {@see _initialize} on an instance of the concrete Setup_Initialize class for the given {@param $_application} * * @param Tinebase_Model_Application $_application * @param array | optional $_options * @return void */ public static function initialize(Tinebase_Model_Application $_application, $_options = null) { $applicationName = $_application->name; $classname = "{$applicationName}_Setup_Initialize"; $instance = new $classname(); Setup_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Initializing application: ' . $applicationName); $instance->_initialize($_application, $_options); }
/** * create shared tag * * @return Tinebase_Model_Tag */ protected function _createSharedTag() { $sharedTag = new Tinebase_Model_Tag(array('type' => Tinebase_Model_Tag::TYPE_SHARED, 'name' => 'tag::shared', 'description' => 'this is a shared tag', 'color' => '#009B31')); $savedSharedTag = $this->_instance->createTag($sharedTag); $right = new Tinebase_Model_TagRight(array('tag_id' => $savedSharedTag->getId(), 'account_type' => Tinebase_Acl_Rights::ACCOUNT_TYPE_USER, 'account_id' => Setup_Core::getUser()->getId(), 'view_right' => true, 'use_right' => true)); $this->_instance->setRights($right); $this->_tagIdsToDelete[] = $savedSharedTag->getId(); $this->assertEquals($sharedTag->name, $savedSharedTag->name); return $savedSharedTag; }
/** * update to 4.1 * - drop column jpegphoto */ public function update_0() { try { $this->_backend->dropCol('addressbook', 'jpegphoto'); } catch (Zend_Db_Statement_Exception $zdse) { Setup_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' ' . $zdse->getMessage()); } $this->setTableVersion('addressbook', 12); $this->setApplicationVersion('Addressbook', '4.1'); }
/** * uninitialize application * * @param Tinebase_Model_Application $_application * @param array | optional $_options * @return void */ protected function _uninitialize(Tinebase_Model_Application $_application, $_options = null) { $reflectionClass = new ReflectionClass($this); $methods = $reflectionClass->getMethods(); foreach ($methods as $method) { $methodName = $method->name; if (strpos($methodName, '_uninitialize') === 0 && $methodName !== '_uninitialize') { Setup_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Calling uninit function ' . get_class($this) . '::' . $methodName); $this->{$methodName}($_application, $_options); } } }
/** * initialize application * * @param Tinebase_Model_Application $_application * @param array | optional $_options * @return void */ protected function _initialize(Tinebase_Model_Application $_application, $_options = null) { $this->_createInitialRights($_application); $reflectionClass = new ReflectionClass($this); $methods = $reflectionClass->getMethods(); foreach ($methods as $method) { $methodName = $method->name; if (preg_match('/^_initialize.+/', $methodName)) { Setup_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Calling init function ' . get_class($this) . '::' . $methodName); $this->{$methodName}($_application, $_options); } } }
/** * handler for HTTP api requests * @todo session expire handling * * @return HTTP */ public function handle() { Setup_Core::initFramework(); if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' is http request. method: ' . (isset($_REQUEST['method']) ? $_REQUEST['method'] : 'EMPTY')); } $server = new Tinebase_Http_Server(); $server->setClass('Setup_Frontend_Http', 'Setup'); if (empty($_REQUEST['method'])) { $_REQUEST['method'] = 'Setup.mainScreen'; } $server->handle($_REQUEST); }
/** * download config as config file * * @param array $data */ public function downloadConfig($data) { if (!Setup_Core::configFileExists() || Setup_Core::isRegistered(Setup_Core::USER)) { $data = Zend_Json::decode($data, Zend_Json::TYPE_ARRAY); $tmpFile = tempnam(Tinebase_Core::getTempDir(), 'tine20_'); Setup_Controller::getInstance()->writeConfigToFile($data, TRUE, $tmpFile); $configData = file_get_contents($tmpFile); unlink($tmpFile); header("Pragma: public"); header("Cache-Control: max-age=0"); header("Content-Disposition: attachment; filename=config.inc.php"); header("Content-Description: PHP File"); header("Content-type: text/plain"); die($configData); } }
/** * * init folders */ public function _initializeFolders(Tinebase_Model_Application $_application, $_options = null) { // initialize folders for installed apps foreach (Tinebase_Application::getInstance()->getApplications() as $app) { $reflectionClass = new ReflectionClass($app->name . '_Setup_Initialize'); $methods = $reflectionClass->getMethods(); foreach ($methods as $method) { $methodName = $method->name; if ($method->name == '_initializeFilemanagerFolder') { Setup_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Initializing filemanager folder for application: ' . $app->name); $class = $reflectionClass->newInstance(); $class->_initializeFilemanagerFolder($app); } } } }
/** * (non-PHPdoc) * @see Tinebase_Server_Interface::handle() */ public function handle(\Zend\Http\Request $request = null, $body = null) { Tinebase_Session_Abstract::setSessionEnabled('TINE20SETUPSESSID'); if (Tinebase_Session::sessionExists()) { Setup_Core::startSetupSession(); } Setup_Core::initFramework(); if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' is http request. method: ' . $this->getRequestMethod()); } $server = new Tinebase_Http_Server(); $server->setClass('Setup_Frontend_Http', 'Setup'); $server->setClass('Tinebase_Frontend_Http', 'Tinebase'); // needed for fetching translation in DEVELOPMENT mode if (empty($_REQUEST['method'])) { $_REQUEST['method'] = 'Setup.mainScreen'; } $server->handle($_REQUEST); }
/** * authenticate user * * @return Zend_Auth_Result */ public function authenticate() { if (isset(Setup_Core::getConfig()->setupuser)) { $setupConfig = Setup_Core::getConfig()->setupuser; $givenPassword = self::isMd5($setupConfig->password) ? md5($this->_password) : $this->_password; if ($setupConfig->username == $this->_username && $setupConfig->password == $givenPassword) { $code = Zend_Auth_Result::SUCCESS; $messages = array('Login successful'); } else { #Setup_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' ' . " $setupConfig->username == $this->_username && $setupConfig->password == $this->_password "); $code = Zend_Auth_Result::FAILURE; $messages = array('Login failed'); } } else { $code = Zend_Auth_Result::FAILURE; $messages = array('No setup user found in config.inc.php'); } $result = new Zend_Auth_Result($code, $this->_username, $messages); return $result; }
/** * (non-PHPdoc) * @see Tinebase_Server_Interface::handle() */ public function handle(\Zend\Http\Request $request = null, $body = null) { try { $opts = new Zend_Console_Getopt(array('help|h' => 'Display this help Message', 'verbose|v' => 'Output messages', 'config|c=s' => 'Path to config.inc.php file', 'setconfig' => 'Update config. To specify the key and value, append \' -- configkey="your_key" configValue="your config value"\' Examples: setup.php --setconfig -- configkey=sample1 configvalue=value11 setup.php --setconfig -- configkey=sample2 configvalue=arrayKey1:Value1,arrayKey2:value2 ', 'getconfig' => 'Get Config value for a specify the key \' -- configkey="your_key"\'', 'check_requirements' => 'Check if all requirements are met to install and run tine20', 'create_admin' => 'Create new admin user (or reactivate if already exists)', 'install-s' => 'Install applications [All] or comma separated list;' . ' To specify the login name and login password of the admin user that is created during installation, append \' -- adminLoginName="admin" adminPassword="******"\'' . ' To add imap or smtp settings, append (for example) \' -- imap="host:mail.example.org,port:143,dbmail_host:localhost" smtp="ssl:tls"\'', 'update-s' => 'Update applications [All] or comma separated list', 'uninstall-s' => 'Uninstall application [All] or comma separated list', 'list-s' => 'List installed applications', 'sync_accounts_from_ldap' => 'Import user and groups from ldap', 'dbmailldap' => 'Only usable with sync_accounts_from_ldap. Fetches dbmail email user data from LDAP.', 'onlyusers' => 'Only usable with sync_accounts_from_ldap. Fetches only users and no groups from LDAP.', 'syncdeletedusers' => 'Only usable with sync_accounts_from_ldap. Removes users from Tine 2.0 DB that no longer exist in LDAP', 'syncaccountstatus' => 'Only usable with sync_accounts_from_ldap. Synchronizes current account status from LDAP', 'syncontactphoto' => 'Only usable with sync_accounts_from_ldap. Always syncs contact photo from ldap', 'sync_passwords_from_ldap' => 'Synchronize user passwords from ldap', 'egw14import' => 'Import user and groups from egw14 Examples: setup.php --egw14import /path/to/config.ini', 'reset_demodata' => 'reinstall applications and install Demodata (Needs Admin user)', 'updateAllImportExportDefinitions' => 'update ImportExport definitions for all applications', 'backup' => 'backup config and data Examples: setup.php --backup -- config=1 db=1 files=1 backupDir=/backup/tine20 noTimestamp=1', 'restore' => 'restore config and data Examples: setup.php --restore -- config=1 db=1 files=1 backupDir=/backup/tine20')); $opts->parse(); } catch (Zend_Console_Getopt_Exception $e) { echo "Invalid usage: {$e->getMessage()}\n\n"; echo $e->getUsageMessage(); exit; } if (count($opts->toArray()) === 0 || $opts->h || empty($opts->install) && empty($opts->update) && empty($opts->uninstall) && empty($opts->list) && empty($opts->sync_accounts_from_ldap) && empty($opts->sync_passwords_from_ldap) && empty($opts->egw14import) && empty($opts->check_requirements) && empty($opts->reset_demodata) && empty($opts->updateAllImportExportDefinitions) && empty($opts->create_admin) && empty($opts->setconfig) && empty($opts->backup) && empty($opts->restore) && empty($opts->getconfig)) { echo $opts->getUsageMessage(); exit; } if ($opts->config) { // add path to config.inc.php to include path $path = strstr($opts->config, 'config.inc.php') !== false ? dirname($opts->config) : $opts->config; set_include_path($path . PATH_SEPARATOR . get_include_path()); } Setup_Core::initFramework(); if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Is cli request. method: ' . $this->getRequestMethod()); } $setupServer = new Setup_Frontend_Cli(); #$setupServer->authenticate($opts->username, $opts->password); return $setupServer->handle($opts); }
/** * test get users with pref function * */ public function testGetUsersWithPref() { $this->_instance->{Tinebase_Preference::TIMEZONE} = 'Europe/Nicosia'; $userIds = $this->_instance->getUsersWithPref(Tinebase_Preference::TIMEZONE, 'Europe/Berlin'); $this->assertTrue(!in_array(Setup_Core::getUser()->getId(), $userIds), 'admin user should have other timezone setting'); $this->assertGreaterThan(4, count($userIds), 'too few users found'); $this->_instance->{Tinebase_Preference::TIMEZONE} = 'Europe/Berlin'; }
/** * initializes the database connection * * @return boolean * * @todo try to write to db, if it fails: self::set(Setup_Core::CHECKDB, FALSE); */ public static function setupDatabaseConnection() { $dbcheck = FALSE; // check database first if (self::configFileExists()) { $dbConfig = Tinebase_Core::getConfig()->database; if ($dbConfig->adapter === self::PDO_MYSQL && (!defined(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY) || !defined(PDO::MYSQL_ATTR_INIT_COMMAND))) { Setup_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' MySQL PDO constants not defined.'); return FALSE; } try { parent::setupDatabaseConnection(); $serverVersion = self::getDb()->getServerVersion(); switch ($dbConfig->adapter) { case self::PDO_MYSQL: if (version_compare(self::MYSQL_MINIMAL_VERSION, $serverVersion, '<')) { $dbcheck = TRUE; } else { Setup_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' MySQL server version incompatible! ' . $serverVersion . ' < ' . self::MYSQL_MINIMAL_VERSION); } break; case self::ORACLE: if (version_compare(self::ORACLE_MINIMAL_VERSION, $serverVersion, '<')) { self::set(Setup_Core::CHECKDB, TRUE); } else { Setup_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Oracle server version incompatible! ' . $serverVersion . ' < ' . self::ORACLE_MINIMAL_VERSION); } $dbcheck = TRUE; break; case self::PDO_PGSQL: if (version_compare(self::PGSQL_MINIMAL_VERSION, $serverVersion, '<')) { $dbcheck = TRUE; } else { Setup_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' PostgreSQL server version incompatible! ' . $serverVersion . ' < ' . self::PGSQL_MINIMAL_VERSION); } break; default: // @todo check version requirements for other db adapters $dbcheck = TRUE; break; } } catch (Zend_Db_Adapter_Exception $zae) { Setup_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' ' . $zae->getMessage()); } catch (Zend_Db_Exception $zde) { Setup_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' ' . $zde->getMessage()); } } self::set(Setup_Core::CHECKDB, $dbcheck); return $dbcheck; }
/** * update to 4.3 * - add index for applications.status */ public function update_2() { if ($this->getTableVersion('applications') < 2) { $declaration = new Setup_Backend_Schema_Index_Xml(' <index> <name>status</name> <field> <name>status</name> </field> </index> '); try { $this->_backend->addIndex('applications', $declaration); } catch (Zend_Db_Statement_Exception $zdse) { Setup_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' ' . $zdse->getMessage()); } $this->setTableVersion('applications', '7'); } $this->setApplicationVersion('Tinebase', '4.3'); }
/** * restore * * @param $options array( * 'backupDir' => string // location of backup to restore * 'config' => bool // restore config * 'db' => bool // restore database * 'files' => bool // restore files * ) * * @param $options * @throws Exception */ public function restore($options) { if (!isset($options['backupDir'])) { throw new Exception("you need to specify the backupDir"); } if ($options['config']) { $configBackupFile = $options['backupDir'] . '/tine20_config.tar.bz2'; if (!file_exists($configBackupFile)) { throw new Exception("{$configBackupFile} not found"); } $configDir = isset($options['configDir']) ? $options['configDir'] : false; if (!$configDir) { $configFile = stream_resolve_include_path('config.inc.php'); if (!$configFile) { throw new Exception("can't detect configDir, please use configDir option"); } $configDir = dirname($configFile); } `cd {$configDir}; tar xf {$configBackupFile}`; } Setup_Core::setupConfig(); $config = Setup_Core::getConfig(); if ($options['db']) { $this->_backend->restore($options['backupDir']); } $filesDir = isset($config->filesdir) ? $config->filesdir : false; if ($options['files']) { $filesBackupFile = $options['backupDir'] . '/tine20_files.tar.bz2'; if (!file_exists($filesBackupFile)) { throw new Exception("{$filesBackupFile} not found"); } `cd {$filesDir}; tar xf {$filesBackupFile}`; } }
/** * import accounts from ldap * * @param Zend_Console_Getopt $_opts */ protected function _importAccounts(Zend_Console_Getopt $_opts) { // disable timelimit during import of user accounts Setup_Core::setExecutionLifeTime(0); // import groups Tinebase_Group::syncGroups(); // import users Tinebase_User::syncUsers(true); }
/** * create inital rights * * @todo make hard coded role names ('user role' and 'admin role') configurable * * @param Tinebase_Application $application * @return void */ public static function createInitialRights(Tinebase_Model_Application $_application) { Setup_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Creating initial rights for application ' . $_application->name); $allRights = Tinebase_Application::getInstance()->getAllRights($_application->getId()); $userRights = static::$_userRoleRights; if (in_array(Tinebase_Acl_Rights::USE_PERSONAL_TAGS, $allRights)) { $userRights[] = Tinebase_Acl_Rights::USE_PERSONAL_TAGS; } $roleRights = array('user role' => $userRights, 'admin role' => $allRights); foreach ($roleRights as $roleName => $rights) { try { $role = Tinebase_Acl_Roles::getInstance()->getRoleByName($roleName); } catch (Tinebase_Exception_NotFound $tenf) { Tinebase_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' ' . $tenf->getMessage()); continue; } foreach ($rights as $right) { try { Tinebase_Acl_Roles::getInstance()->addSingleRight($role->getId(), $_application->getId(), $right); } catch (Exception $e) { Tinebase_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' Cannot add right: ' . $right . ' for application: ' . $_application->name . ' - ' . $roleName . ' - ' . print_r($e->getMessage(), true)); } } } }
/** * clear the cache */ protected function _clearCache() { if (Setup_Core::isLogLevel(Zend_Log::DEBUG)) { Setup_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' clearing cache ... '); } Tinebase_Core::getCache()->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('config')); }
public function testConfigFilesExists() { $this->assertTrue(Setup_Core::configFileExists()); }
/** * import accounts from ldap * * @param Zend_Console_Getopt $_opts */ protected function _importAccounts(Zend_Console_Getopt $_opts) { // disable timelimit during import of user accounts Setup_Core::setExecutionLifeTime(0); // import groups if (!$_opts->onlyusers) { Tinebase_Group::syncGroups(); } // import users $options = array('syncContactData' => TRUE); if ($_opts->dbmailldap) { $options['ldapplugins'] = array(new Tinebase_EmailUser_Imap_LdapDbmailSchema(), new Tinebase_EmailUser_Smtp_LdapDbmailSchema()); } if ($_opts->syncdeletedusers) { $options['deleteUsers'] = true; } Tinebase_User::syncUsers($options); }
/** * identify base event via new base_event_id field instead of UID */ public function update_8() { /* find possibly broken events SELECT group_concat(id), uid, count(id) as cnt from tine20_cal_events WHERE rrule IS NOT NULL GROUP BY uid HAVING cnt > 1; */ $declaration = new Setup_Backend_Schema_Field_Xml(' <field> <name>base_event_id</name> <type>text</type> <length>40</length> </field>'); $this->_backend->addCol('cal_events', $declaration); $declaration = new Setup_Backend_Schema_Index_Xml(' <index> <name>base_event_id</name> <field> <name>base_event_id</name> </field> </index>'); $this->_backend->addIndex('cal_events', $declaration); // find all events with rrule $events = $this->_db->query("SELECT " . $this->_db->quoteIdentifier('id') . ', ' . $this->_db->quoteIdentifier('uid') . ', ' . $this->_db->quoteIdentifier('container_id') . ', ' . $this->_db->quoteIdentifier('created_by') . " FROM " . $this->_db->quoteIdentifier(SQL_TABLE_PREFIX . "cal_events") . " WHERE " . $this->_db->quoteIdentifier("rrule") . " IS NOT NULL" . " AND " . $this->_db->quoteIdentifier("is_deleted") . " = " . $this->_db->quote(0, Zend_Db::INT_TYPE))->fetchAll(Zend_Db::FETCH_ASSOC); // update all exdates in same container foreach ($events as $event) { $this->_db->query("UPDATE " . $this->_db->quoteIdentifier(SQL_TABLE_PREFIX . "cal_events") . " SET " . $this->_db->quoteIdentifier('base_event_id') . ' = ' . $this->_db->quote($event['id']) . " WHERE " . $this->_db->quoteIdentifier('uid') . ' = ' . $this->_db->quote($event['uid']) . " AND " . $this->_db->quoteIdentifier("container_id") . ' = ' . $this->_db->quote($event['container_id']) . " AND " . $this->_db->quoteIdentifier("recurid") . " IS NOT NULL" . " AND " . $this->_db->quoteIdentifier("is_deleted") . " = " . $this->_db->quote(0, Zend_Db::INT_TYPE)); } // find all container move exdates $danglingExdates = $this->_db->query("SELECT " . $this->_db->quoteIdentifier('uid') . ', ' . $this->_db->quoteIdentifier('id') . ', ' . $this->_db->quoteIdentifier('created_by') . " FROM " . $this->_db->quoteIdentifier(SQL_TABLE_PREFIX . "cal_events") . " WHERE " . $this->_db->quoteIdentifier("recurid") . " IS NOT NULL" . " AND " . $this->_db->quoteIdentifier("base_event_id") . " IS NULL" . " AND " . $this->_db->quoteIdentifier("is_deleted") . " = " . $this->_db->quote(0, Zend_Db::INT_TYPE))->fetchAll(Zend_Db::FETCH_ASSOC); // try to match by creator foreach ($danglingExdates as $exdate) { $possibleBaseEvents = array(); $matches = array_filter($events, function ($event) use($exdate, $possibleBaseEvents) { if ($event['uid'] == $exdate['uid']) { $possibleBaseEvents[] = $event; return $event['created_by'] == $exdate['created_by']; } return false; }); switch (count($matches)) { case 0: // no match :-( if (count($possibleBaseEvents) == 0) { // garbage? exdate without any base event Setup_Core::getLogger()->err(__METHOD__ . '::' . __LINE__ . " dangling exdate with id {$exdate['id']}"); continue 2; } Setup_Core::getLogger()->err(__METHOD__ . '::' . __LINE__ . " no match for exdate with id {$exdate['id']}"); $baseEvent = current($possibleBaseEvents); break; case 1: // exact match :-) $baseEvent = current($matches); break; default: // to much matches :-( Setup_Core::getLogger()->err(__METHOD__ . '::' . __LINE__ . " multiple matches for exdate with id {$exdate['id']}"); $baseEvent = current($matches); } $this->_db->query("UPDATE " . $this->_db->quoteIdentifier(SQL_TABLE_PREFIX . "cal_events") . " SET " . $this->_db->quoteIdentifier('base_event_id') . ' = ' . $this->_db->quote($baseEvent['id']) . " WHERE " . $this->_db->quoteIdentifier('id') . ' = ' . $this->_db->quote($exdate['id'])); } $this->setTableVersion('cal_events', '10'); $this->setApplicationVersion('Calendar', '8.9'); }
/** * update to 0.28 * - repair db charset for users with non default utf8 client charset */ public function update_27() { $config = Setup_Core::get(Setup_Core::CONFIG); $tableprefix = $config->database->tableprefix; // have a second db connection with default charset $orgDb = Zend_Db::factory('Pdo_Mysql', $config->database->toArray()); // fix for signed / unsigned problem $declaration = new Setup_Backend_Schema_Field_Xml(' <field> <name>id</name> <type>integer</type> <autoincrement>true</autoincrement> </field> '); $this->_backend->alterCol('addressbook', $declaration); /** addressbook: store image in separate table **/ $tableDefinition = ' <table> <name>addressbook_image</name> <version>1</version> <declaration> <field> <name>contact_id</name> <type>integer</type> <notnull>true</notnull> </field> <field> <name>image</name> <type>blob</type> </field> <index> <name>contact_id</name> <primary>true</primary> <field> <name>contact_id</name> </field> </index> <index> <name>addressbook_image::contact_id-addressbook::id</name> <field> <name>contact_id</name> </field> <foreign>true</foreign> <reference> <table>addressbook</table> <field>id</field> <ondelete>CASCADE</ondelete> </reference> </index> </declaration> </table> '; $table = Setup_Backend_Schema_Table_Factory::factory('String', $tableDefinition); $this->_backend->createTable($table); $select = $orgDb->select()->from("{$tableprefix}addressbook", array('id'))->where($orgDb->quoteIdentifier('jpegphoto') . " IS NOT NULL"); $contactIds = $orgDb->fetchAll($select); foreach ($contactIds as $contactId) { $contactId = $contactId['id']; $select = $orgDb->select()->from("{$tableprefix}addressbook", array('id', 'jpegphoto'))->where($orgDb->quoteInto($orgDb->quoteIdentifier('id') . ' = ?', $contactId)); $imageData = $orgDb->fetchRow($select); $orgDb->insert("{$tableprefix}addressbook_image", array('contact_id' => $imageData['id'], 'image' => base64_encode($imageData['jpegphoto']))); } $this->_backend->dropCol('addressbook', 'jpegphoto'); /** convert serialized object into json objects **/ $select = $orgDb->select()->from("{$tableprefix}filter", array('id', 'filters')); $filters = $orgDb->fetchAll($select); foreach ($filters as $filter) { $filterObject = unserialize($filter['filters']); $orgDb->update("{$tableprefix}filter", array('filters' => Zend_Json::encode($filterObject)), $orgDb->quoteInto($orgDb->quoteIdentifier('id') . ' = ?', $filter['id'])); } /** convert db contenets for installations which had a clientcharset != utf8 **/ $originalCharset = Tinebase_Helper::array_value('Value', Tinebase_Helper::array_value(0, $orgDb->query("SHOW VARIABLES LIKE 'character_set_client'")->fetchAll())); if (strtolower($originalCharset) != 'utf8') { $this->_db->query("SET FOREIGN_KEY_CHECKS=0"); $orgDb->query("SET FOREIGN_KEY_CHECKS=0"); // build the list of tables to convert $tables = array(); $rawTables = $this->_db->query("SHOW TABLES")->fetchAll(); foreach ($rawTables as $rawTable) { $tableName = array_values($rawTable); $tableName = $tableName[0]; if (preg_match("/^{$tableprefix}/", $tableName) && $tableName != "{$tableprefix}addressbook_image") { $tables[] = $tableName; } } // the actual charset conversion is done by the db. foreach ($tables as $tableName) { Setup_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Converting table ' . $tableName); //$this->_db->query("SET character_set_client = '$originalCharset'"); $select = $orgDb->select()->from($tableName); $result = $orgDb->fetchAll($select); $orgDb->query("TRUNCATE TABLE " . $this->_db->quoteIdentifier($tableName)); //$this->_db->query("SET character_set_client = 'utf8'"); foreach ($result as $row) { try { $this->_db->insert($tableName, $row); } catch (Zend_Db_Statement_Exception $zdse) { Setup_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' ' . $zdse->getMessage()); // try to convert strings if failure if (preg_match('/(description|title|note|old_value|org_name|adr_one_street)/', $zdse->getMessage(), $match)) { $field = $match[1]; Setup_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' Converting field ' . $field . (isset($row['id']) || array_key_exists('id', $row) ? ' of record ' . $row['id'] : '')); $row[$field] = utf8_encode($row[$field]); $this->_db->insert($tableName, $row); } else { Setup_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' Could not convert field'); throw $zdse; } } } } $this->_db->query("SET FOREIGN_KEY_CHECKS=1"); } $orgDb->closeConnection(); $this->setApplicationVersion('Tinebase', '0.28'); }
/** * checks the environment * * @return array with success/failure values for the given attributes * */ private function _check() { foreach ($this->values as $key => $value) { if ($value['tag'] == 'ENVIROMENT') { switch ($value['attributes']['NAME']) { case 'Zend': $required = $value['attributes']['VERSION']; $zend = Zend_Version::VERSION; $operator = $value['attributes']['OPERATOR'] == 'biggerThan' ? '>' : '<'; $text = $value['attributes']['NAME'] . ' ' . $operator . ' ' . $required; if (version_compare($zend, $required, $operator)) { $data[] = array($text, 'SUCCESS'); } else { $data[] = array($text . ' (version is ' . $zend . ')', 'FAILURE'); } break; case 'PHP': if (version_compare($value['attributes']['VERSION'], phpversion(), '<=')) { $data[] = array($value['attributes']['NAME'], 'SUCCESS'); } else { Setup_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' PHP version incompatible: ' . phpversion() . ' < ' . $value['attributes']['VERSION']); $data[] = array($value['attributes']['NAME'], 'FAILURE'); } break; case 'MySQL': // get setup controller for database connection if (Setup_Core::configFileExists()) { $dbConfig = Tinebase_Core::getConfig()->database; $hostnameWithPort = isset($dbConfig->port) ? $dbConfig->host . ':' . $dbConfig->port : $dbConfig->host; $link = @mysql_connect($hostnameWithPort, $dbConfig->username, $dbConfig->password); if (!$link) { //die('Could not connect to mysql database: ' . mysql_error()); Setup_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . 'Could not connect to mysql database: ' . mysql_error()); Setup_Core::set(Setup_Core::CHECKDB, FALSE); } $mysqlVersion = @mysql_get_server_info(); } else { $mysqlVersion = @mysql_get_client_info(); } // some version strings have more than just the version preg_match('/\\d+\\.\\d+\\.\\d+/', $mysqlVersion, $matches); $mysqlVersion = is_array($matches) ? $matches[0] : $mysqlVersion; $text = $value['attributes']['NAME']; if (version_compare($value['attributes']['VERSION'], $mysqlVersion, '<=')) { $data[] = array($text, 'SUCCESS'); } else { Setup_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' MySQL version incompatible: ' . $mysqlVersion . ' < ' . $value['attributes']['VERSION']); $data[] = array($text, 'FAILURE'); } break; case 'PgSQL': $pgsqlVersion = '0.0.0'; // get setup controller for database connection if (Setup_Core::configFileExists()) { $dbConfig = Tinebase_Core::getConfig()->database; $hostname = $dbConfig->host; $port = isset($dbConfig->port) ? $dbConfig->port : '5432'; $user = $dbConfig->username; $password = $dbConfig->password; $link = @pg_connect("host={$hostname} port={$port} user={$user} password={$password}"); if (PGSQL_CONNECTION_BAD === pg_connection_status($link)) { //die('Could not connect to postgresql database: ' . pg_errormessage()); Setup_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . 'Could not connect to postgresql database: ' . pg_errormessage()); Setup_Core::set(Setup_Core::CHECKDB, FALSE); } else { $pgsqlVersion = @pg_version($link); $pgsqlVersion = $pgsqlVersion['server']; } } $text = $value['attributes']['NAME']; if (version_compare($value['attributes']['VERSION'], $pgsqlVersion, '<=')) { $data[] = array($text, 'SUCCESS'); } else { Setup_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' PostgreSQL version incompatible: ' . $pgsqlVersion . ' < ' . $value['attributes']['VERSION']); $data[] = array($text, 'FAILURE'); } break; default: $data[] = array($value['attributes']['NAME'], 'FAILURE'); break; } } else { if ($value['tag'] == 'EXTENSION') { //print_r($this->loadedExtensions); foreach ($value as $extensionArray) { if (is_array($extensionArray)) { $succeeded = false; if (in_array($extensionArray['NAME'], $this->loadedExtensions)) { $passed[] = true; if ($this->values[$key + 1]['tag'] == 'INISET') { $iniSettings = ini_get_all($extensionArray['NAME']); //print_r($iniSettings); $i = 1; while ($values[$key + $i]['tag'] == 'INISET') { switch ($values[$key + $i]['attributes']['OPERATOR']) { case '<=': if (!$iniSettings[$values[$key + $i]['attributes']['NAME']][$values[$key + $i]['attributes']['SCOPE']] <= $values[$key + $i]['attributes']['VALUE']) { $passed[] = false; } break; case '==': if (!$iniSettings[$values[$key + $i]['attributes']['NAME']][$values[$key + $i]['attributes']['SCOPE']] == $values[$key + $i]['attributes']['VALUE']) { $passed[] = false; } break; case '>=': if (!$iniSettings[$values[$key + $i]['attributes']['NAME']][$values[$key + $i]['attributes']['SCOPE']] >= $values[$key + $i]['attributes']['VALUE']) { $passed[] = false; } break; default: break; } $i++; } } // end INISET if (!in_array(false, $passed)) { $succeeded = true; } unset($passed); unset($iniSettings); } if ($succeeded) { $data[] = array($extensionArray['NAME'], 'SUCCESS'); } else { $data[] = array($extensionArray['NAME'], 'FAILURE'); } } } } } // end EXTENSION } // end foreach return $data; }
/** * update to 2.7 * - rename config.inc.php parameter session.save_path to sessiondir */ public function update_6() { if (Setup_Core::configFileWritable()) { $config = Setup_Controller::getInstance()->getConfigData(); if (empty($config['sessiondir']) && !empty($config['session.save_path'])) { $config['sessiondir'] = $config['session.save_path']; } Setup_Controller::getInstance()->saveConfigData($config, FALSE); } $this->setApplicationVersion('Tinebase', '2.7'); }
/** * nagios monitoring for tine 2.0 config file * * @return integer * @see http://nagiosplug.sourceforge.net/developer-guidelines.html#PLUGOUTPUT */ public function monitoringCheckConfig() { $message = 'CONFIG FAIL'; $configcheck = FALSE; $configfile = Setup_Core::getConfigFilePath(); if ($configfile) { $configfile = escapeshellcmd($configfile); if (preg_match('/^win/i', PHP_OS)) { exec("php -l {$configfile} 2> NUL", $error, $code); } else { exec("php -l {$configfile} 2> /dev/null", $error, $code); } if ($code == 0) { $configcheck = TRUE; } else { $message .= ': CONFIG FILE SYNTAX ERROR'; } } else { $message .= ': CONFIG FILE MISSING'; } if ($configcheck) { echo "CONFIG FILE OK\n"; return 0; } else { echo $message . "\n"; return 2; } }
/** * returns one config value identified by config name and application id * -> value in config.inc.php overwrites value in db if $_fromFile is TRUE * * @deprecated * @param string $_name config name/key * @param string $_applicationId application id [optional] * @param mixed $_default the default value [optional] * @param boolean $_fromFile get from config.inc.php [optional] * @return Tinebase_Model_Config the config record * @throws Tinebase_Exception_NotFound */ public function getConfig($_name, $_applicationId = NULL, $_default = NULL, $_fromFile = TRUE) { $applicationId = $_applicationId !== NULL ? Tinebase_Model_Application::convertApplicationIdToInt($_applicationId) : Tinebase_Application::getInstance()->getApplicationByName('Tinebase')->getId(); $result = $this->_loadConfig($_name, $applicationId); if (!$result) { $result = new Tinebase_Model_Config(array('application_id' => $applicationId, 'name' => $_name, 'value' => $_default), TRUE); } // check config.inc.php and get value from there $configFileData = $this->_getConfigFileData(); if ($_fromFile && array_key_exists($_name, $configFileData)) { Setup_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Overwriting config setting "' . $_name . '" with value from config.inc.php.'); $result->value = $configFileData[$_name]; } return $result; }