diff --git a/core/AppController.php b/core/AppController.php index 36cc6360b..bad231838 100644 --- a/core/AppController.php +++ b/core/AppController.php @@ -67,10 +67,8 @@ public function preDispatch() $this->view->metaDescription = Zend_Registry::get('configGlobal')->application->description; // Set the version - $this->view->version = '3.2.8'; - if (isset(Zend_Registry::get('configDatabase')->version)) { - $this->view->version = Zend_Registry::get('configDatabase')->version; - } + $version = UtilityComponent::getCurrentModuleVersion('core'); + $this->view->version = $version !== false ? $version : '3.4.x'; require_once BASE_PATH.'/core/models/dao/UserDao.php'; require_once BASE_PATH.'/core/models/dao/ItemDao.php'; @@ -127,7 +125,10 @@ public function preDispatch() if ($userDao != false) { // authenticate valid users in the appropriate method for the // current application version - if (version_compare(Zend_Registry::get('configDatabase')->version, '3.2.12', '>=')) { + if ($version === false) { + throw new Zend_Exception('Core version is undefined.'); + } + if (version_compare($version, '3.2.12', '>=')) { $auth = $userModel->hashExists($tmp[1]); } else { $auth = $userModel->legacyAuthenticate($userDao, '', '', $tmp[1]); @@ -604,6 +605,9 @@ protected function t($text) /** @var MetadataModel */ public $Metadata; + /** @var ModuleModel */ + public $Module; + /** @var NewUserInvitationModel */ public $NewUserInvitation; diff --git a/core/Bootstrap.php b/core/Bootstrap.php index 7a45aed73..557741dd4 100644 --- a/core/Bootstrap.php +++ b/core/Bootstrap.php @@ -180,7 +180,7 @@ protected function _initConfig() /** Display the debug toolbar, if enabled. */ protected function _initZFDebug() { - $this->bootstrap('config'); + $this->bootstrap(array('Config', 'FrontController')); $zfDebugPath = BASE_PATH.'/vendor/jokkedk/zfdebug/library'; if (Zend_Registry::get('configGlobal')->debug_toolbar === '1' && file_exists($zfDebugPath)) { @@ -196,21 +196,24 @@ protected function _initZFDebug() ); $debug = new ZFDebug_Controller_Plugin_Debug($options); - - $this->bootstrap('frontController'); - $frontController = $this->getResource('frontController'); + $frontController = $this->getResource('FrontController'); $frontController->registerPlugin($debug); + + return $debug; } + + return false; } /** Register the module directories. */ protected function _initFrontModules() { - $this->bootstrap('frontController'); - $front = $this->getResource('frontController'); - $front->addModuleDirectory(BASE_PATH.'/modules'); + $this->bootstrap('FrontController'); + $frontController = $this->getResource('FrontController'); + $frontController->addModuleDirectory(BASE_PATH.'/modules'); + if (file_exists(BASE_PATH.'/privateModules')) { - $front->addModuleDirectory(BASE_PATH.'/privateModules'); + $frontController->addModuleDirectory(BASE_PATH.'/privateModules'); } } @@ -272,124 +275,94 @@ protected function _initSass() * Initialize the router. * * @return Zend_Controller_Router_Interface + * @throws Zend_Exception */ protected function _initRouter() { - $router = Zend_Controller_Front::getInstance()->getRouter(); + $this->bootstrap(array('Config', 'FrontController')); - // Init Modules - $frontController = Zend_Controller_Front::getInstance(); + $frontController = $this->getResource('FrontController'); $frontController->addControllerDirectory(BASE_PATH.'/core/controllers'); - $modules = new Zend_Config_Ini(APPLICATION_CONFIG, 'module'); - // routes modules - $listeModule = array(); - $apiModules = array(); - foreach ($modules as $key => $module) { - if ($module == 1 && file_exists(BASE_PATH.'/modules/'.$key) && file_exists( - BASE_PATH.'/modules/'.$key.'/AppController.php' - ) - ) { - $listeModule[] = $key; - // get web API controller directories and web API module names for enabled modules - if (file_exists(BASE_PATH.'/modules/'.$key.'/controllers/api')) { - $frontController->addControllerDirectory( - BASE_PATH.'/modules/'.$key.'/controllers/api', - 'api'.$key - ); - $apiModules[] = $key; - } - } elseif ($module == 1 && file_exists(BASE_PATH.'/privateModules/'.$key) && file_exists( - BASE_PATH.'/privateModules/'.$key.'/AppController.php' - ) - ) { - $listeModule[] = $key; - // get web API controller directories and web API module names for enabled modules - if (file_exists(BASE_PATH.'/privateModules/'.$key.'/controllers/api')) { - $frontController->addControllerDirectory( - BASE_PATH.'/privateModules/'.$key.'/controllers/api', - 'api'.$key - ); - $apiModules[] = $key; - } - } - } - - // get web API controller directory for core APIs require_once BASE_PATH.'/core/ApiController.php'; $frontController->addControllerDirectory(BASE_PATH.'/core/controllers/api', 'rest'); - // add RESTful route for web APIs - $restRoute = new Zend_Rest_Route($frontController, array(), array('rest')); - $router->addRoute('api-core', $restRoute); - // loading modules elements - foreach ($listeModule as $m) { - $route = $m; - $nameModule = $m; - $router->addRoute( - $nameModule.'-1', - new Zend_Controller_Router_Route( - ''.$route.'/:controller/:action/*', array('module' => $nameModule) - ) - ); - $router->addRoute( - $nameModule.'-2', - new Zend_Controller_Router_Route( - ''.$route.'/:controller/', - array('module' => $nameModule, 'action' => 'index') - ) - ); - $router->addRoute( - $nameModule.'-3', - new Zend_Controller_Router_Route( - ''.$route.'/', - array('module' => $nameModule, 'controller' => 'index', 'action' => 'index') - ) - ); - if (file_exists(BASE_PATH.'/modules/'.$route.'/AppController.php')) { - require_once BASE_PATH.'/modules/'.$route.'/AppController.php'; - } - if (file_exists(BASE_PATH.'/modules/'.$route.'/models/AppDao.php')) { - require_once BASE_PATH.'/modules/'.$route.'/models/AppDao.php'; - } - if (file_exists(BASE_PATH.'/modules/'.$route.'/models/AppModel.php')) { - require_once BASE_PATH.'/modules/'.$route.'/models/AppModel.php'; + $router = $frontController->getRouter(); + $router->addRoute('api-core', new Zend_Rest_Route($frontController, array(), array('rest'))); + + $enabledModules = array(); + + if (isset(Zend_Registry::get('configDatabase')->version) === false) { + Zend_Registry::set('models', array()); + + /** @var ModuleModel $moduleModel */ + $moduleModel = MidasLoader::loadModel('Module'); + $moduleDaos = $moduleModel->getEnabled(); + + /** @var ModuleDao $moduleDao */ + foreach ($moduleDaos as $moduleDao) { + $enabledModules[] = $moduleDao->getName(); } - if (file_exists(BASE_PATH.'/modules/'.$route.'/constant/module.php')) { - require_once BASE_PATH.'/modules/'.$route.'/constant/module.php'; + } else { + $modules = new Zend_Config_Ini(APPLICATION_CONFIG, 'module'); + $enabledModules = array_keys($modules->toArray(), 1); + } + + $enabledApiModules = array(); + + /** @var string $enabledModule */ + foreach ($enabledModules as $enabledModule) { + if (file_exists(BASE_PATH.'/modules/'.$enabledModule.'/AppController.php')) { + $moduleRoot = BASE_PATH.'/modules/'.$enabledModule; + } elseif (file_exists(BASE_PATH.'/privateModules/'.$enabledModule.'/AppController.php')) { + $moduleRoot = BASE_PATH.'/privateModules/'.$enabledModule; + } else { + throw new Zend_Exception('Module '.$enabledModule.'" does not exist.'); } - if (file_exists(BASE_PATH.'/privateModules/'.$route.'/AppController.php')) { - require_once BASE_PATH.'/privateModules/'.$route.'/AppController.php'; + $frontController->addControllerDirectory($moduleRoot.'/controllers', $enabledModule); + + if (file_exists($moduleRoot.'/constant/module.php')) { + require_once $moduleRoot.'/constant/module.php'; } - if (file_exists(BASE_PATH.'/privateModules/'.$route.'/models/AppDao.php')) { - require_once BASE_PATH.'/privateModules/'.$route.'/models/AppDao.php'; + + if (file_exists($moduleRoot.'/AppController.php')) { + require_once $moduleRoot.'/AppController.php'; } - if (file_exists(BASE_PATH.'/privateModules/'.$route.'/models/AppModel.php')) { - require_once BASE_PATH.'/privateModules/'.$route.'/models/AppModel.php'; + + if (file_exists($moduleRoot.'/models/AppDao.php')) { + require_once $moduleRoot.'/models/AppDao.php'; } - if (file_exists(BASE_PATH.'/privateModules/'.$route.'/constant/module.php')) { - require_once BASE_PATH.'/privateModules/'.$route.'/constant/module.php'; + + if (file_exists($moduleRoot.'/models/AppModel.php')) { + require_once $moduleRoot.'/models/AppModel.php'; } - $dir = BASE_PATH.'/modules/'.$route.'/models/base'; - if (!is_dir($dir)) { - $dir = BASE_PATH.'/privateModules/'.$route.'/models/base'; + if (file_exists($moduleRoot.'/controllers/api')) { + $frontController->addControllerDirectory($moduleRoot.'/controllers/api', 'api'.$enabledModule); + $enabledApiModules[] = $enabledModule; } - if (is_dir($dir)) { - $objects = scandir($dir); - foreach ($objects as $object) { - if ($object != '.' && $object != '..') { - if (filetype($dir.'/'.$object) != 'dir') { - require_once $dir.'/'.$object; - } + $router->addRoute($enabledModule.'-1', new Zend_Controller_Router_Route($enabledModule.'/:controller/:action/*', array('module' => $enabledModule))); + $router->addRoute($enabledModule.'-2', new Zend_Controller_Router_Route($enabledModule.'/:controller/', array('module' => $enabledModule, 'action' => 'index'))); + $router->addRoute($enabledModule.'-3', new Zend_Controller_Router_Route($enabledModule.'/', array('module' => $enabledModule, 'controller' => 'index', 'action' => 'index'))); + + $baseModels = $moduleRoot.'/models/base'; + + if (is_dir($baseModels)) { + $fileNames = array_diff(scandir($baseModels), array('..', '.')); + + /** @var string $fileName */ + foreach ($fileNames as $fileName) { + if (filetype($baseModels.'/'.$fileName) != 'dir') { + require_once $baseModels.'/'.$fileName; } } } } - Zend_Registry::set('modulesEnable', $listeModule); - Zend_Registry::set('modulesHaveApi', $apiModules); + + Zend_Registry::set('modulesEnable', $enabledModules); + Zend_Registry::set('modulesHaveApi', $enabledApiModules); return $router; } @@ -397,7 +370,8 @@ protected function _initRouter() /** Register the plugins and helpers for the REST controllers. */ protected function _initREST() { - $frontController = Zend_Controller_Front::getInstance(); + $this->bootstrap('FrontController'); + $frontController = $this->getResource('FrontController'); // register the RestHandler plugin $frontController->registerPlugin(new REST_Controller_Plugin_RestHandler($frontController)); diff --git a/core/configs/application.ini b/core/configs/application.ini index 2dfb6400a..f22d31eef 100644 --- a/core/configs/application.ini +++ b/core/configs/application.ini @@ -28,8 +28,6 @@ cookie_secure = "0" ; show debug toolbar debug_toolbar = "0" -[module] - [production] [development] diff --git a/core/configs/core.ini b/core/configs/core.ini index 1c4b2cb24..934870484 100644 --- a/core/configs/core.ini +++ b/core/configs/core.ini @@ -15,5 +15,6 @@ rest.formats[] = "json" rest.formats[] = "html" rest.formats[] = "php" uuid = "67a81613-074d-4c9a-afb7-4613f3144a3d" +version = "3.4.1" [testing] diff --git a/core/configs/database.ini b/core/configs/database.ini index e932f213f..486d81c70 100644 --- a/core/configs/database.ini +++ b/core/configs/database.ini @@ -8,7 +8,6 @@ database.params.unix_socket = "" database.params.dbname = "midas" database.params.username = "root" database.params.password = "" -version = "" [development] database.adapter = "PDO_MYSQL" @@ -18,7 +17,6 @@ database.params.unix_socket = "" database.params.dbname = "midas" database.params.username = "root" database.params.password = "" -version = "" [testing] database.adapter = "PDO_MYSQL" @@ -28,4 +26,3 @@ database.params.unix_socket = "" database.params.dbname = "midas_test" database.params.username = "root" database.params.password = "" -version = "" diff --git a/core/controllers/AdminController.php b/core/controllers/AdminController.php index 40dc93a63..961bfbdf7 100644 --- a/core/controllers/AdminController.php +++ b/core/controllers/AdminController.php @@ -21,7 +21,7 @@ /** Admin Controller. */ class AdminController extends AppController { - public $_models = array('Assetstore', 'Bitstream', 'Item', 'ItemRevision', 'Folder', 'License', 'Setting'); + public $_models = array('Assetstore', 'Bitstream', 'Item', 'ItemRevision', 'Folder', 'License', 'Module', 'Setting'); public $_daos = array(); public $_components = array('Upgrade', 'Utility', 'MIDAS2Migration'); public $_forms = array('Admin', 'Assetstore', 'Migrate'); @@ -69,8 +69,7 @@ public function indexAction() $this->requireAdminPrivileges(); $this->view->header = 'Administration'; - $options = array('allowModifications' => true); - $config = new Zend_Config_Ini(APPLICATION_CONFIG, null, $options); + $config = new Zend_Config_Ini(APPLICATION_CONFIG, null, true); $configForm = $this->Form->Admin->createConfigForm(); $formArray = $this->getFormAsArray($configForm); @@ -131,28 +130,14 @@ public function indexAction() } if (isset($submitModule)) { $moduleName = $this->getParam('modulename'); - $modulevalue = $this->getParam('modulevalue'); - $moduleConfigLocalFile = LOCAL_CONFIGS_PATH.'/'.$moduleName.'.local.ini'; - $moduleConfigFile = BASE_PATH.'/modules/'.$moduleName.'/configs/module.ini'; - $moduleConfigPrivateFile = BASE_PATH.'/privateModules/'.$moduleName.'/configs/module.ini'; - if (!file_exists($moduleConfigLocalFile) && file_exists($moduleConfigFile) - ) { - copy($moduleConfigFile, $moduleConfigLocalFile); - $this->Component->Utility->installModule($moduleName); - } elseif (!file_exists($moduleConfigLocalFile) && file_exists($moduleConfigPrivateFile) - ) { - copy($moduleConfigPrivateFile, $moduleConfigLocalFile); + $moduleEnabled = $this->getParam('modulevalue'); + $moduleDao = $this->Module->getByName($moduleName); + if ($moduleDao === false) { $this->Component->Utility->installModule($moduleName); - } elseif (!file_exists($moduleConfigLocalFile)) { - throw new Zend_Exception('Unable to find config file'); + $moduleDao = $this->Module->getByName($moduleName); } - - $config->module->$moduleName = $modulevalue; - - $writer = new Zend_Config_Writer_Ini(); - $writer->setConfig($config); - $writer->setFilename(APPLICATION_CONFIG); - $writer->write(); + $moduleDao->setEnabled($moduleEnabled); + $this->Module->save($moduleDao); echo JsonComponent::encode(array(true, 'Changes saved')); } } @@ -201,7 +186,7 @@ public function indexAction() $this->view->assetstoreForm = $this->Form->Assetstore->createAssetstoreForm(); // get modules - $enabledModules = Zend_Registry::get('modulesEnable'); + // $adapter = Zend_Registry::get('configDatabase')->database->adapter; foreach ($allModules as $key => $module) { if (file_exists(BASE_PATH.'/modules/'.$key.'/controllers/ConfigController.php')) { @@ -262,8 +247,11 @@ public function indexAction() ksort($modulesList); $this->view->countModules = $countModules; $this->view->modulesList = $modulesList; + + $enabledModules = Zend_Registry::get('modulesEnable'); $this->view->modulesEnable = $enabledModules; - $this->view->databaseType = Zend_Registry::get('configDatabase')->database->adapter; + + $this->view->databaseType = $adapter; } /** admin dashboard view */ @@ -336,6 +324,11 @@ public function upgradeAction() $dbtype = Zend_Registry::get('configDatabase')->database->adapter; $modulesConfig = Zend_Registry::get('configsModules'); + $version = UtilityComponent::getCurrentModuleVersion('core'); + if ($version === false) { + throw new Zend_Exception('Core version is undefined.'); + } + if ($this->_request->isPost()) { $this->disableView(); $upgraded = false; @@ -346,8 +339,7 @@ public function upgradeAction() } } $this->Component->Upgrade->initUpgrade('core', $db, $dbtype); - if ($this->Component->Upgrade->upgrade(Zend_Registry::get('configDatabase')->version) - ) { + if ($this->Component->Upgrade->upgrade($version)) { $upgraded = true; } @@ -374,10 +366,8 @@ public function upgradeAction() $this->Component->Upgrade->initUpgrade('core', $db, $dbtype); $core['target'] = $this->Component->Upgrade->getNewestVersion(); $core['targetText'] = $this->Component->Upgrade->getNewestVersion(true); - $core['currentText'] = Zend_Registry::get('configDatabase')->version; - $core['current'] = $this->Component->Upgrade->transformVersionToNumeric( - Zend_Registry::get('configDatabase')->version - ); + $core['currentText'] = $version; + $core['current'] = $this->Component->Upgrade->transformVersionToNumeric($version); $this->view->core = $core; } diff --git a/core/controllers/InstallController.php b/core/controllers/InstallController.php index e0d206e5f..5d0b10af1 100644 --- a/core/controllers/InstallController.php +++ b/core/controllers/InstallController.php @@ -118,9 +118,7 @@ public function step2Action() $dbtype = 'PDO_'.strtoupper($type); $version = str_replace('.sql', '', basename($sqlFile)); - $options = array('allowModifications' => true); - $databaseConfig = new Zend_Config_Ini(CORE_CONFIGS_PATH.'/database.ini', null, $options); - + $databaseConfig = new Zend_Config_Ini(CORE_CONFIGS_PATH.'/database.ini', null, true); $databaseConfig->production->database->adapter = $dbtype; $databaseConfig->production->database->params->host = $form->getValue('host'); $databaseConfig->production->database->params->port = $form->getValue('port'); @@ -128,7 +126,6 @@ public function step2Action() $databaseConfig->production->database->params->dbname = $form->getValue('dbname'); $databaseConfig->production->database->params->username = $form->getValue('username'); $databaseConfig->production->database->params->password = $form->getValue('password'); - $databaseConfig->production->version = $version; $databaseConfig->development->database->adapter = $dbtype; $databaseConfig->development->database->params->host = $form->getValue('host'); @@ -137,7 +134,6 @@ public function step2Action() $databaseConfig->development->database->params->dbname = $form->getValue('dbname'); $databaseConfig->development->database->params->username = $form->getValue('username'); $databaseConfig->development->database->params->password = $form->getValue('password'); - $databaseConfig->development->version = $version; $writer = new Zend_Config_Writer_Ini(); $writer->setConfig($databaseConfig); @@ -168,8 +164,7 @@ public function step2Action() $this->Component->Utility->run_sql_from_file($db, $sqlFile); // Must generate and store our password salt before we create our first user - $options = array('allowModifications' => true); - $applicationConfig = new Zend_Config_Ini(CORE_CONFIGS_PATH.'/application.ini', null, $options); + $applicationConfig = new Zend_Config_Ini(CORE_CONFIGS_PATH.'/application.ini', null, true); $prefix = $this->Component->Random->generateString(32); $applicationConfig->global->password->prefix = $prefix; @@ -186,11 +181,22 @@ public function step2Action() $configDatabase = new Zend_Config_Ini(LOCAL_CONFIGS_PATH.'/database.local.ini', 'production'); Zend_Registry::set('configDatabase', $configDatabase); + $configCore = new Zend_Config_Ini(CORE_CONFIGS_PATH.'/core.ini', 'global'); + + /** @var ModuleModel $moduleModel */ + $moduleModel = MidasLoader::loadModel('Module'); + /** @var ModuleDao $moduleDao */ + $moduleDao = MidasLoader::newDao('ModuleDao'); + $moduleDao->setName('core'); + $moduleDao->setUuid(str_replace('-', '', $configCore->get('uuid'))); + $moduleDao->setCurrentVersion($version); + $moduleDao->setEnabled(1); + $moduleModel->save($moduleDao); + require_once BASE_PATH.'/core/controllers/components/UpgradeComponent.php'; $upgradeComponent = new UpgradeComponent(); - $upgradeComponent->initUpgrade('core', $db, $dbtype); - $upgradeComponent->upgrade(str_replace('.sql', '', basename($sqlFile))); + $upgradeComponent->upgrade($version); session_start(); require_once BASE_PATH.'/core/models/pdo/UserModel.php'; @@ -232,8 +238,7 @@ public function step3Action() $this->redirect('/install/index'); } - $options = array('allowModifications' => true); - $config = new Zend_Config_Ini(APPLICATION_CONFIG, null, $options); + $config = new Zend_Config_Ini(APPLICATION_CONFIG, null, true); $form = $this->Form->Install->createConfigForm(); $formArray = $this->getFormAsArray($form); diff --git a/core/controllers/UserController.php b/core/controllers/UserController.php index cc4627d44..50bfdf34b 100644 --- a/core/controllers/UserController.php +++ b/core/controllers/UserController.php @@ -567,7 +567,10 @@ public function loginAction() } $instanceSalt = Zend_Registry::get('configGlobal')->password->prefix; - $currentVersion = Zend_Registry::get('configDatabase')->version; + $currentVersion = UtilityComponent::getCurrentModuleVersion('core'); + if ($currentVersion === false) { + throw new Zend_Exception('Core version is undefined.'); + } // We have to have this so that an admin can log in to upgrade from version < 3.2.12 to >= 3.2.12. // Version 3.2.12 introduced the new password hashing and storage system. if (!$authModule && version_compare($currentVersion, '3.2.12', '>=') diff --git a/core/controllers/components/ApisystemComponent.php b/core/controllers/components/ApisystemComponent.php index 49c43bcbb..2a27efcd2 100644 --- a/core/controllers/components/ApisystemComponent.php +++ b/core/controllers/components/ApisystemComponent.php @@ -32,7 +32,12 @@ class ApisystemComponent extends AppComponent */ public function version($args) { - return array('version' => Zend_Registry::get('configDatabase')->version); + $version = UtilityComponent::getCurrentModuleVersion('core'); + if ($version === false) { + throw new Zend_Exception('Core version is undefined.'); + } + + return array('version' => $version); } /** diff --git a/core/controllers/components/UpgradeComponent.php b/core/controllers/components/UpgradeComponent.php index 7bbfad3f6..27452d0e1 100644 --- a/core/controllers/components/UpgradeComponent.php +++ b/core/controllers/components/UpgradeComponent.php @@ -49,7 +49,7 @@ class UpgradeComponent extends AppComponent */ public function initUpgrade($module, $db, $dbtype) { - if ($module == 'core') { + if ($module === 'core') { $this->dir = BASE_PATH.'/core/database/upgrade'; } elseif (file_exists(BASE_PATH.'/privateModules/'.$module.'/database/upgrade')) { $this->dir = BASE_PATH.'/privateModules/'.$module.'/database/upgrade'; @@ -86,9 +86,10 @@ public function initUpgrade($module, $db, $dbtype) */ public function getNewestVersion($text = false) { - if (!$this->init) { - throw new Zend_Exception('Please init the component first'); + if ($this->init === false) { + throw new Zend_Exception('Upgrade component is not initialized.'); } + $files = $this->getMigrationFiles(); if (empty($files)) { return 0; @@ -112,9 +113,10 @@ public function getNewestVersion($text = false) */ public function getMigrationFiles() { - if (!$this->init) { - throw new Zend_Exception('Please init the component first'); + if ($this->init === false) { + throw new Zend_Exception('Upgrade component is not initialized.'); } + $files = array(); if (file_exists($this->dir)) { $d = dir($this->dir); @@ -154,29 +156,33 @@ public function getMigrationFiles() */ public function transformVersionToNumeric($text) { - $array = explode('.', $text); - if (count($array) != 3) { - throw new Zend_Exception('The version format shoud be 1.2.3. You set:'.$text); + $result = preg_match('/^([0-9]+)\.([0-9]+)\.([0-9]+)$/i', $text, $matches); + if ($result !== 1) { + throw new Zend_Exception('Core or module version string is invalid.'); } - return (int) $array[0] * 1000000 + (int) $array[1] * 1000 + (int) $array[2]; + return (int) $matches[1] * 1000000 + (int) $matches[2] * 1000 + (int) $matches[3]; } /** * Upgrade. * - * @param null|int|string $currentVersion + * @param false|null|int|string $currentVersion * @param bool $testing * @return bool * @throws Zend_Exception */ - public function upgrade($currentVersion = null, $testing = false) + public function upgrade($currentVersion = false, $testing = false) { - if ($currentVersion == null) { - $currentVersion = Zend_Registry::get('configDatabase')->version; + if ($this->init === false) { + throw new Zend_Exception('Upgrade component is not initialized.'); + } + + if (is_null($currentVersion) || $currentVersion === false) { + $currentVersion = UtilityComponent::getCurrentModuleVersion($this->module); } - if ($currentVersion == null) { - throw new Zend_Exception('Version undefined'); + if ($currentVersion === false) { + throw new Zend_Exception('Core or module version is undefined.'); } if (!is_numeric($currentVersion)) { $currentVersion = $this->transformVersionToNumeric($currentVersion); @@ -184,74 +190,65 @@ public function upgrade($currentVersion = null, $testing = false) $version = $this->getNewestVersion($text = false); - if ($currentVersion >= $version || $version == 0) { + if ($currentVersion >= $version || $version === 0) { return false; } $migrations = $this->getMigrationFiles(); + $versionText = false; + /** @var array $migration */ foreach ($migrations as $migration) { if ($migration['version'] > $currentVersion) { $this->_processFile($migration); + $versionText = $migration['versionText']; + Zend_Registry::get('logger')->info($versionText); } } - if ($this->module == 'core') { - if (isset($migration)) { - $path = LOCAL_CONFIGS_PATH.'/database.local.ini'; - if ($testing || Zend_Registry::get('configGlobal')->environment == 'testing' - ) { - $path = getenv('MIDAS_DATABASE_INI'); - if (!file_exists($path)) { - if (file_exists(BASE_PATH.'/tests/configs/lock.mysql.ini')) { - $path = BASE_PATH.'/tests/configs/lock.mysql.ini'; - } - if (file_exists(BASE_PATH.'/tests/configs/lock.pgsql.ini')) { - $path = BASE_PATH.'/tests/configs/lock.pgsql.ini'; - } - if (file_exists(BASE_PATH.'/tests/configs/lock.sqlite.ini')) { - $path = BASE_PATH.'/tests/configs/lock.sqlite.ini'; - } + if ($versionText !== false) { + if (isset(Zend_Registry::get('configDatabase')->version) === false) { + /** @var ModuleModel $moduleModel */ + $moduleModel = MidasLoader::loadModel('Module'); + $moduleDao = $moduleModel->getByName($this->module); + if ($moduleDao === false) { + /** @var ModuleDao $moduleDao */ + $moduleDao = MidasLoader::newDao('ModuleDao'); + $moduleDao->setName($this->module); + + if ($this->module === 'core') { + $moduleConfig = Zend_Registry::get('configCore'); + } else { + /** @var UtilityComponent $utilityComponent */ + $utilityComponent = MidasLoader::loadComponent('Utility'); + $moduleConfigs = $utilityComponent->getAllModules(); + /** @var Zend_Config_Ini $moduleConfig */ + $moduleConfig = $moduleConfigs[$this->module]; } + + /** @var UuidComponent $uuidComponent */ + $uuidComponent = MidasLoader::loadComponent('Uuid'); + $uuid = $moduleConfig->get('uuid', $uuidComponent->generate()); + $uuid = str_replace('-', '', $uuid); + $moduleDao->setUuid($uuid); } - $options = array('allowModifications' => true); - if ($testing || Zend_Registry::get('configGlobal')->environment == 'testing' - ) { - $path = getenv('MIDAS_DATABASE_INI'); - if (!file_exists($path)) { - if (file_exists(BASE_PATH.'/tests/configs/lock.mysql.ini')) { - $path = BASE_PATH.'/tests/configs/lock.mysql.ini'; - } - if (file_exists(BASE_PATH.'/tests/configs/lock.pgsql.ini')) { - $path = BASE_PATH.'/tests/configs/lock.pgsql.ini'; - } - if (file_exists(BASE_PATH.'/tests/configs/lock.sqlite.ini')) { - $path = BASE_PATH.'/tests/configs/lock.sqlite.ini'; - } - } - $config = new Zend_Config_Ini($path, null, $options); - $config->testing->version = $migration['versionText']; + $moduleDao->setCurrentVersion($versionText); + $moduleModel->save($moduleDao); + } else { + if ($this->module === 'core') { + $configPath = DATABASE_CONFIG; + $config = new Zend_Config_Ini($configPath, null, true); + $config->development->version = $versionText; + $config->production->version = $versionText; } else { - $config = new Zend_Config_Ini($path, null, $options); - $config->development->version = $migration['versionText']; - $config->production->version = $migration['versionText']; + $configPath = LOCAL_CONFIGS_PATH.'/'.$this->module.'.local.ini'; + $config = new Zend_Config_Ini($configPath, null, true); + $config->global->version = $versionText; } $writer = new Zend_Config_Writer_Ini(); $writer->setConfig($config); - $writer->setFilename($path); - $writer->write(); - } - } else { - $path = LOCAL_CONFIGS_PATH.'/'.$this->module.'.local.ini'; - if (file_exists($path)) { - $options = array('allowModifications' => true); - $config = new Zend_Config_Ini($path, null, $options); - $config->global->version = $migration['versionText']; - - $writer = new Zend_Config_Writer_Ini(); - $writer->setConfig($config); - $writer->setFilename($path); + $writer->setFilename($configPath); $writer->write(); } } @@ -268,20 +265,18 @@ public function upgrade($currentVersion = null, $testing = false) */ public function getClassName($filename) { - $array = explode('.', str_replace('.php', '', basename($filename))); - if (count($array) != 3) { - throw new Zend_Exception( - 'The version format shoud be 1.2.3. You set:'.str_replace('.php', '', basename($filename)) - ); + $result = preg_match('/^([0-9]+)\.([0-9]+)\.([0-9]+).php$/i', basename($filename), $matches); + if ($result !== 1) { + throw new Zend_Exception('Core or module version string is invalid.'); } - $classname = ''; + $className = ''; if ($this->module != 'core') { - $classname = ucfirst($this->module).'_'; + $className = ucfirst($this->module).'_'; } - $classname .= 'Upgrade_'; + $className .= 'Upgrade_'; - return $classname.$array[0].'_'.$array[1].'_'.$array[2]; + return $className.$matches[1].'_'.$matches[2].'_'.$matches[3]; } /** @@ -293,17 +288,19 @@ public function getClassName($filename) protected function _processFile($migration) { require_once BASE_PATH.'/core/models/MIDASUpgrade.php'; - $filename = $migration['filename']; - $classname = $this->getClassName($filename); - require_once $this->dir.'/'.$filename; - if (!class_exists($classname, false)) { - throw new Zend_Exception("Could not find class '".$classname."' in file '".$filename."'"); + $fileName = $migration['filename']; + $className = $this->getClassName($fileName); + + require_once $this->dir.'/'.$fileName; + if (!class_exists($className, false)) { + throw new Zend_Exception("Could not find class '".$className."' in file '".$fileName."'"); } - $class = new $classname($this->db, $this->module, $this->dbtype); - $class->preUpgrade(); - $dbtypeShort = $this->dbtypeShort; - $class->$dbtypeShort(); - $class->postUpgrade(); + /** @var MIDASUpgrade $upgradeClass */ + $upgradeClass = new $className($this->db, $this->module, $this->dbtype); + $upgradeClass->preUpgrade(); + $dbTypeShort = $this->dbtypeShort; + $upgradeClass->$dbTypeShort(); + $upgradeClass->postUpgrade(); } } diff --git a/core/controllers/components/UtilityComponent.php b/core/controllers/components/UtilityComponent.php index 7392458aa..adedcb44d 100644 --- a/core/controllers/components/UtilityComponent.php +++ b/core/controllers/components/UtilityComponent.php @@ -388,6 +388,62 @@ public static function run_sql_from_file($db, $sqlfile) return true; } + /** + * Get the current module version. + * + * @param string $moduleName module name + * @return string current module version + */ + public static function getCurrentModuleVersion($moduleName) + { + if (isset(Zend_Registry::get('configDatabase')->version) === false) { + /** @var ModuleModel $moduleModel */ + $moduleModel = MidasLoader::loadModel('Module'); + $moduleDao = $moduleModel->getByName($moduleName); + + if ($moduleDao !== false) { + return $moduleDao->getCurrentVersion(); + } + } + + if ($moduleName === 'core') { + return Zend_Registry::get('configDatabase')->version; + } + + $configPath = LOCAL_CONFIGS_PATH.'/'.$moduleName.'.local.ini'; + + if (file_exists($configPath)) { + $config = new Zend_Config_Ini($configPath, 'global'); + + return $config->get('version', false); + } + + return false; + } + + /** + * Get the latest module version. + * + * @param string $moduleName module name + * @return string latest module version + */ + public static function getLatestModuleVersion($moduleName) + { + if ($moduleName === 'core') { + return Zend_Registry::get('configCore')->get('version', false); + } + + $configPath = BASE_PATH.'/modules/'.$moduleName.'/configs/module.ini'; + + if (file_exists($configPath)) { + $config = new Zend_Config_Ini($configPath, 'global'); + + return $config->get('version', false); + } + + return false; + } + /** * Get the data directory. * @@ -481,27 +537,41 @@ public static function getCacheDirectory() * install a module. * * @param string $moduleName + * @return bool * @throws Zend_Exception */ public function installModule($moduleName) { + if ($moduleName === 'core') { + return false; + } + + if (self::getCurrentModuleVersion($moduleName) !== false) { + return false; + } + // TODO, The module installation process needs some improvement. - $allModules = $this->getAllModules(); - $version = $allModules[$moduleName]->version; + $moduleConfigs = $this->getAllModules(); + + /** @var Zend_Config_Ini $moduleConfig */ + $moduleConfig = $moduleConfigs[$moduleName]; + $version = $moduleConfig->get('version'); $installScript = BASE_PATH.'/modules/'.$moduleName.'/database/InstallScript.php'; - $installScriptExists = file_exists($installScript); - if ($installScriptExists) { + if (file_exists($installScript)) { require_once BASE_PATH.'/core/models/MIDASModuleInstallScript.php'; require_once $installScript; - $classname = ucfirst($moduleName).'_InstallScript'; - if (!class_exists($classname, false)) { - throw new Zend_Exception('Could not find class "'.$classname.'" in file "'.$installScript.'"'); + $className = ucfirst($moduleName).'_InstallScript'; + if (!class_exists($className, false)) { + throw new Zend_Exception('Could not find class "'.$className.'" in file "'.$installScript.'"'); } - $class = new $classname(); - $class->preInstall(); + /** @var MIDASModuleInstallScript $installScriptClass */ + $installScriptClass = new $className(); + $installScriptClass->preInstall(); + } else { + $installScriptClass = false; } try { @@ -540,16 +610,49 @@ public function installModule($moduleName) $this->getLogger()->warn($exc->getMessage()); } - if ($installScriptExists) { - $class->postInstall(); + if ($installScriptClass !== false) { + $installScriptClass->postInstall(); + } + + /** @var ModuleModel $moduleModel */ + $moduleModel = MidasLoader::loadModel('Module'); + /** @var ModuleDao $moduleDao */ + $moduleDao = MidasLoader::newDao('ModuleDao'); + $moduleDao->setName($moduleName); + + $uuid = $moduleConfig->get('uuid', false); + if ($uuid === false) { + /** @var UuidComponent $uuidComponent */ + $uuidComponent = MidasLoader::loadComponent('Uuid'); + $moduleDao->setUuid($uuidComponent->generate()); + } else { + $moduleDao->setUuid(str_replace('-', '', $uuid)); + } + + $moduleDao->setCurrentVersion($version); + $moduleModel->save($moduleDao); + + if ($uuid === false) { + if (file_exists(BASE_PATH.'/modules/'.$moduleName.'/AppController.php')) { + $path = BASE_PATH.'/modules/'.$moduleName.'/configs/module.ini'; + } elseif (file_exists(BASE_PATH.'/privateModules/'.$moduleName.'/AppController.php')) { + $path = BASE_PATH.'/privateModules/'.$moduleName.'/configs/module.ini'; + } else { + $path = false; + } + if ($path !== false && file_exists($path)) { + copy($path, LOCAL_CONFIGS_PATH.'/'.$moduleName.'local.ini'); + } } require_once dirname(__FILE__).'/UpgradeComponent.php'; $upgrade = new UpgradeComponent(); $db = Zend_Registry::get('dbAdapter'); - $dbtype = Zend_Registry::get('configDatabase')->database->adapter; - $upgrade->initUpgrade($moduleName, $db, $dbtype); + $dbType = Zend_Registry::get('configDatabase')->database->adapter; + $upgrade->initUpgrade($moduleName, $db, $dbType); $upgrade->upgrade($version); + + return true; } /** @@ -605,6 +708,7 @@ public static function markdown($text) * This is used to suppress warnings from being written to the output and the * error log. Users should not call this function; see beginIgnoreWarnings(). * + * @internal * @param int $errno * @param string $errstr * @param string $errfile diff --git a/core/database/mysql/3.4.1.sql b/core/database/mysql/3.4.1.sql new file mode 100644 index 000000000..1885d502b --- /dev/null +++ b/core/database/mysql/3.4.1.sql @@ -0,0 +1,355 @@ +-- Midas Server. Copyright Kitware SAS. Licensed under the Apache License 2.0. + +-- MySQL core database, version 3.4.1 + +CREATE TABLE IF NOT EXISTS `activedownload` ( + `activedownload_id` bigint(20) NOT NULL AUTO_INCREMENT, + `ip` varchar(100) NOT NULL DEFAULT '', + `date_creation` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `last_update` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', + PRIMARY KEY (`activedownload_id`), + KEY (`ip`) +) DEFAULT CHARSET=utf8; + +CREATE TABLE IF NOT EXISTS `assetstore` ( + `assetstore_id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(255) NOT NULL, + `path` varchar(512) NOT NULL, + `type` tinyint(4) NOT NULL, + PRIMARY KEY (`assetstore_id`) +) DEFAULT CHARSET=utf8; + +CREATE TABLE IF NOT EXISTS `bitstream` ( + `bitstream_id` bigint(20) NOT NULL AUTO_INCREMENT, + `itemrevision_id` bigint(20) NOT NULL, + `name` varchar(255) NOT NULL, + `mimetype` varchar(30) NOT NULL, + `sizebytes` bigint(20) NOT NULL, + `checksum` varchar(64) NOT NULL, + `path` varchar(512) NOT NULL, + `assetstore_id` int(11) NOT NULL, + `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`bitstream_id`), + KEY (`itemrevision_id`), + KEY (`checksum`) +) DEFAULT CHARSET=utf8; + +CREATE TABLE IF NOT EXISTS `community` ( + `community_id` bigint(20) NOT NULL AUTO_INCREMENT, + `name` varchar(255) NOT NULL, + `description` text NOT NULL, + `creation` timestamp, + `privacy` tinyint(4) NOT NULL, + `folder_id` bigint(20), + `admingroup_id` bigint(20), + `moderatorgroup_id` bigint(20), + `membergroup_id` bigint(20) NOT NULL DEFAULT '0', + `view` bigint(20) NOT NULL DEFAULT '0', + `can_join` int(11) DEFAULT '0', + `uuid` varchar(255) DEFAULT '', + PRIMARY KEY (`community_id`), + KEY (`name`) +) DEFAULT CHARSET=utf8; + +CREATE TABLE IF NOT EXISTS `communityinvitation` ( + `communityinvitation_id` bigint(20) NOT NULL AUTO_INCREMENT, + `community_id` bigint(20), + `user_id` bigint(20), + `group_id` bigint(20), + PRIMARY KEY (`communityinvitation_id`) +) DEFAULT CHARSET=utf8; + +CREATE TABLE IF NOT EXISTS `errorlog` ( + `errorlog_id` bigint(20) NOT NULL AUTO_INCREMENT, + `priority` tinyint(4) NOT NULL, + `module` varchar(255) NOT NULL, + `message` text NOT NULL, + `datetime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`errorlog_id`) +) DEFAULT CHARSET=utf8; + +CREATE TABLE IF NOT EXISTS `feed` ( + `feed_id` bigint(20) NOT NULL AUTO_INCREMENT, + `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `user_id` bigint(20) NOT NULL, + `type` tinyint(4) NOT NULL, + `resource` varchar(255) NOT NULL, + PRIMARY KEY (`feed_id`) +) DEFAULT CHARSET=utf8; + +CREATE TABLE IF NOT EXISTS `feed2community` ( + `feed_id` bigint(20) NOT NULL, + `community_id` bigint(20) NOT NULL, + UNIQUE KEY `feed_community_id` (`feed_id`,`community_id`) +) DEFAULT CHARSET=utf8; + +CREATE TABLE IF NOT EXISTS `feedpolicygroup` ( + `feed_id` bigint(20) NOT NULL, + `group_id` bigint(20) NOT NULL, + `policy` tinyint(4) NOT NULL, + `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE KEY `feed_group_id` (`feed_id`,`group_id`) +) DEFAULT CHARSET=utf8; + +CREATE TABLE IF NOT EXISTS `feedpolicyuser` ( + `feed_id` bigint(20) NOT NULL, + `user_id` bigint(20) NOT NULL, + `policy` tinyint(4) NOT NULL, + `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE KEY `feed_user_id` (`feed_id`,`user_id`) +) DEFAULT CHARSET=utf8; + +CREATE TABLE IF NOT EXISTS `folder` ( + `folder_id` bigint(20) NOT NULL AUTO_INCREMENT, + `left_index` bigint(20) NOT NULL, + `right_index` bigint(20) NOT NULL, + `parent_id` bigint(20) NOT NULL DEFAULT '0', + `name` varchar(255) NOT NULL, + `description` text NOT NULL, + `date_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `view` bigint(20) NOT NULL DEFAULT '0', + `teaser` varchar(255) DEFAULT '', + `privacy_status` int(11) DEFAULT '0', + `uuid` varchar(255) DEFAULT '', + `date_creation` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', + PRIMARY KEY (`folder_id`), + KEY (`parent_id`), + KEY (`left_index`), + KEY (`right_index`) +) DEFAULT CHARSET=utf8; + +CREATE TABLE IF NOT EXISTS `folderpolicygroup` ( + `folder_id` bigint(20) NOT NULL, + `group_id` bigint(20) NOT NULL, + `policy` tinyint(4) NOT NULL, + `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE KEY `folder_group_id` (`folder_id`,`group_id`) +) DEFAULT CHARSET=utf8; + +CREATE TABLE IF NOT EXISTS `folderpolicyuser` ( + `folder_id` bigint(20) NOT NULL, + `user_id` bigint(20) NOT NULL, + `policy` tinyint(4) NOT NULL, + `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE KEY `folder_user_id` (`folder_id`,`user_id`) +) DEFAULT CHARSET=utf8; + +CREATE TABLE IF NOT EXISTS `group` ( + `group_id` bigint(20) NOT NULL AUTO_INCREMENT, + `community_id` bigint(20) NOT NULL, + `name` varchar(255) NOT NULL, + PRIMARY KEY (`group_id`), + KEY (`community_id`) +) DEFAULT CHARSET=utf8; + +CREATE TABLE IF NOT EXISTS `item` ( + `item_id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(255) NOT NULL, + `date_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `description` text NOT NULL, + `type` int(11) NOT NULL, + `view` bigint(20) NOT NULL DEFAULT '0', + `download` bigint(20) NOT NULL DEFAULT '0', + `sizebytes` bigint(20) NOT NULL DEFAULT '0', + `privacy_status` int(11) DEFAULT '0', + `uuid` varchar(255) DEFAULT '', + `date_creation` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', + `thumbnail_id` bigint(20), + PRIMARY KEY (`item_id`) +) DEFAULT CHARSET=utf8; + +CREATE TABLE IF NOT EXISTS `item2folder` ( + `item_id` bigint(20) NOT NULL, + `folder_id` bigint(20) NOT NULL, + KEY (`folder_id`) +) DEFAULT CHARSET=utf8; + +CREATE TABLE IF NOT EXISTS `itempolicygroup` ( + `item_id` bigint(20) NOT NULL, + `group_id` bigint(20) NOT NULL, + `policy` tinyint(4) NOT NULL, + `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE KEY `item_group_id` (`item_id`,`group_id`) +) DEFAULT CHARSET=utf8; + +CREATE TABLE IF NOT EXISTS `itempolicyuser` ( + `item_id` bigint(20) NOT NULL, + `user_id` bigint(20) NOT NULL, + `policy` tinyint(4) NOT NULL, + `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE KEY `item_user_id` (`item_id`,`user_id`) +) DEFAULT CHARSET=utf8; + +CREATE TABLE IF NOT EXISTS `itemrevision` ( + `itemrevision_id` int(11) NOT NULL AUTO_INCREMENT, + `item_id` bigint(20) NOT NULL, + `revision` int(11) NOT NULL, + `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `changes` text NOT NULL, + `user_id` int(11) NOT NULL, + `uuid` varchar(255) DEFAULT '', + `license_id` bigint(20), + PRIMARY KEY (`itemrevision_id`), + UNIQUE KEY `item_revision_id` (`item_id`,`revision`), + KEY (`user_id`), + KEY (`date`) +) DEFAULT CHARSET=utf8; + +CREATE TABLE IF NOT EXISTS `license` ( + `license_id` bigint(20) NOT NULL AUTO_INCREMENT, + `name` text NOT NULL, + `fulltext` text NOT NULL, + PRIMARY KEY (`license_id`) +) DEFAULT CHARSET=utf8; + +INSERT INTO `license` VALUES +('1', 'Public (PDDL)', '**You are free:**\n\n* To Share: To copy, distribute and use the database.\n* To Create: To produce works from the database.\n* To Adapt: To modify, transform, and build upon the database.\n\n[Full License Information](http://opendatacommons.org/licenses/pddl/summary)'), +('2', 'Public: Attribution (ODC-BY)', '**You are free:**\n\n* To Share: To copy, distribute and use the database.\n* To Create: To produce works from the database.\n* To Adapt: To modify, transform, and build upon the database.\n\n**As long as you:**\n\n* Attribute: You must attribute any public use of the database, or works produced from the database, in the manner specified in the license. For any use or redistribution of the database, or works produced from it, you must make clear to others the license of the database and keep intact any notices on the original database.\n\n[Full License Information](http://opendatacommons.org/licenses/by/summary)'), +('3', 'Public: Attribution, Share-Alike (ODbL)', '**You are free:**\n\n* To Share: To copy, distribute and use the database.\n* To Create: To produce works from the database.\n* To Adapt: To modify, transform, and build upon the database.\n\n**As long as you:**\n\n* Attribute: You must attribute any public use of the database, or works produced from the database, in the manner specified in the license. For any use or redistribution of the database, or works produced from it, you must make clear to others the license of the database and keep intact any notices on the original database.\n* Share-Alike: If you publicly use any adapted version of this database, or works produced from an adapted database, you must also offer that adapted database under the ODbL.\n* Keep open: If you redistribute the database, or an adapted version of it, then you may use technological measures that restrict the work (such as DRM) as long as you also redistribute a version without such measures.\n\n[Full License Information](http://opendatacommons.org/licenses/odbl/summary)'), +('4', 'Private: All Rights Reserved', 'This work is copyrighted by its author or licensor. You must not share, distribute, or modify this work without the prior consent of the author or licensor.'), +('5', 'Public: Attribution (CC BY 3.0)', '**You are free:**\n\n* To Share: To copy, distribute and transmit the work.\n* To Remix: To adapt the work.\n* To make commercial use of the work.\n\n**Under the following conditions:**\n\n* Attribution: You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work).\n\n[Full License Information](http://creativecommons.org/licenses/by/3.0/)'), +('6', 'Public: Attribution, Share-Alike (CC BY-SA 3.0)', '**You are free:**\n\n* To Share: To copy, distribute and transmit the work.\n* To Remix: To adapt the work.\n* To make commercial use of the work.\n\n**Under the following conditions:**\n\n* Attribution: You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work).\n* Share-Alike: If you alter, transform, or build upon this work, you may distribute the resulting work only under the same or similar license to this one.\n\n[Full License Information](http://creativecommons.org/licenses/by-sa/3.0/)'), +('7', 'Public: Attribution, No Derivative Works (CC BY-ND 3.0)', '**You are free:**\n\n* To Share: To copy, distribute and transmit the work.\n* To make commercial use of the work.\n\n**Under the following conditions:**\n\n* Attribution: You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work).\n* No Derivative Works: You may not alter, transform, or build upon this work.\n\n[Full License Information](http://creativecommons.org/licenses/by-nd/3.0/)'), +('8', 'Public: Attribution, Non-Commercial (CC BY-NC 3.0)', '**You are free:**\n\n* To Share: To copy, distribute and transmit the work.\n* To Remix: To adapt the work.\n\n**Under the following conditions:**\n\n* Attribution: You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work).\n* Non-Commercial: You may not use this work for commercial purposes.\n\n[Full License Information](http://creativecommons.org/licenses/by-nc/3.0/)'), +('9', 'Public: Attribution, Non-Commercial, Share-Alike (CC BY-NC-SA 3.0)', '**You are free:**\n\n* To Share: To copy, distribute and transmit the work.\n* To Remix: To adapt the work.\n\n**Under the following conditions:**\n\n* Attribution: You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work).\n* Non-Commercial: You may not use this work for commercial purposes.\n* Share-Alike: If you alter, transform, or build upon this work, you may distribute the resulting work only under the same or similar license to this one.\n\n[Full License Information](http://creativecommons.org/licenses/by-nc-sa/3.0/)'), +('10', 'Public: Attribution, Non-Commercial, No Derivative Works (CC BY-NC-ND 3.0)', '**You are free:**\n\n* To Share: To copy, distribute and transmit the work.\n\n**Under the following conditions:**\n\n* Attribution: You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work).\n* Non-Commercial: You may not use this work for commercial purposes.\n* No Derivative Works: You may not alter, transform, or build upon this work.\n\n[Full License Information](http://creativecommons.org/licenses/by-nc-nd/3.0/)'); + +CREATE TABLE IF NOT EXISTS `metadata` ( + `metadata_id` bigint(20) NOT NULL AUTO_INCREMENT, + `metadatatype` int(11) DEFAULT '0', + `element` varchar(255) NOT NULL, + `qualifier` varchar(255) NOT NULL, + PRIMARY KEY (`metadata_id`), + KEY (`metadatatype`) +) DEFAULT CHARSET=utf8; + +INSERT INTO `metadata` VALUES +('1', '0', 'contributor', 'author'), +('2', '0', 'date', 'uploaded'), +('3', '0', 'date', 'issued'), +('4', '0', 'date', 'created'), +('5', '0', 'identifier', 'citation'), +('6', '0', 'identifier', 'uri'), +('7', '0', 'identifier', 'pubmed'), +('8', '0', 'identifier', 'doi'), +('9', '0', 'description', 'general'), +('10', '0', 'description', 'provenance'), +('11', '0', 'description', 'sponsorship'), +('12', '0', 'description', 'publisher'), +('13', '0', 'subject', 'keyword'), +('14', '0', 'subject', 'ocis'); + +CREATE TABLE IF NOT EXISTS `metadatavalue` ( + `metadatavalue_id` bigint(20) NOT NULL AUTO_INCREMENT, + `metadata_id` bigint(20) NOT NULL, + `itemrevision_id` bigint(20) NOT NULL, + `value` varchar(1024) NOT NULL, + PRIMARY KEY (`metadatavalue_id`), + KEY `metadata_itemrevision_id` (`metadata_id`,`itemrevision_id`) +) DEFAULT CHARSET=utf8; + +CREATE TABLE IF NOT EXISTS `module` ( + `module_id` bigint(20) NOT NULL AUTO_INCREMENT, + `name` varchar(255) NOT NULL, + `uuid` varchar(36) NOT NULL, + `current_major_version` int(11) NOT NULL DEFAULT '0', + `current_minor_version` int(11) NOT NULL DEFAULT '0', + `current_patch_version` int(11) NOT NULL DEFAULT '0', + `enabled` tinyint(4) NOT NULL DEFAULT '0', + PRIMARY KEY (`module_id`), + UNIQUE KEY (`name`), + UNIQUE KEY (`uuid`) +) DEFAULT CHARSET=utf8; + +CREATE TABLE IF NOT EXISTS `newuserinvitation` ( + `newuserinvitation_id` bigint(20) NOT NULL AUTO_INCREMENT, + `auth_key` varchar(255) NOT NULL, + `email` varchar(255) NOT NULL, + `inviter_id` bigint(20) NOT NULL, + `community_id` bigint(20) NOT NULL, + `group_id` bigint(20) NOT NULL, + `date_creation` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`newuserinvitation_id`) +) DEFAULT CHARSET=utf8; + +CREATE TABLE IF NOT EXISTS `password` ( + `hash` varchar(128) NOT NULL, + PRIMARY KEY (`hash`) +) DEFAULT CHARSET=utf8; + +CREATE TABLE IF NOT EXISTS `pendinguser` ( + `pendinguser_id` bigint(20) NOT NULL AUTO_INCREMENT, + `auth_key` varchar(255) NOT NULL, + `email` varchar(255) NOT NULL, + `firstname` varchar(255) NOT NULL, + `lastname` varchar(255) NOT NULL, + `date_creation` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `salt` varchar(64) NOT NULL DEFAULT '', + PRIMARY KEY (`pendinguser_id`) +) DEFAULT CHARSET=utf8; + +CREATE TABLE IF NOT EXISTS `progress` ( + `progress_id` bigint(20) NOT NULL AUTO_INCREMENT, + `message` text NOT NULL, + `current` bigint(20) NOT NULL, + `maximum` bigint(20) NOT NULL, + `date_creation` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `last_update` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', + PRIMARY KEY (`progress_id`) +) DEFAULT CHARSET=utf8; + +CREATE TABLE IF NOT EXISTS `setting` ( + `setting_id` bigint(20) NOT NULL AUTO_INCREMENT, + `module` varchar(255) NOT NULL, + `name` varchar(255) NOT NULL, + `value` text, + PRIMARY KEY (`setting_id`) +) DEFAULT CHARSET=utf8; + +CREATE TABLE IF NOT EXISTS `token` ( + `token_id` bigint(20) NOT NULL AUTO_INCREMENT, + `userapi_id` bigint(20) NOT NULL, + `token` varchar(64) NOT NULL, + `expiration_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`token_id`) +) DEFAULT CHARSET=utf8; + +CREATE TABLE IF NOT EXISTS `user` ( + `user_id` bigint(20) NOT NULL AUTO_INCREMENT, + `firstname` varchar(255) NOT NULL, + `company` varchar(255), + `thumbnail` varchar(255), + `lastname` varchar(255) NOT NULL, + `email` varchar(255) NOT NULL, + `privacy` tinyint(4) NOT NULL DEFAULT '0', + `admin` tinyint(4) NOT NULL DEFAULT '0', + `folder_id` bigint(20), + `creation` timestamp, + `view` bigint(20) NOT NULL DEFAULT '0', + `uuid` varchar(255) DEFAULT '', + `city` varchar(100) DEFAULT '', + `country` varchar(100) DEFAULT '', + `website` varchar(255) DEFAULT '', + `biography` text, + `dynamichelp` tinyint(4) DEFAULT '1', + `hash_alg` varchar(32) NOT NULL DEFAULT '', + `salt` varchar(64) NOT NULL DEFAULT '', + PRIMARY KEY (`user_id`), + KEY (`email`) +) DEFAULT CHARSET=utf8; + +CREATE TABLE IF NOT EXISTS `user2group` ( + `user_id` bigint(20) NOT NULL, + `group_id` bigint(20) NOT NULL, + UNIQUE KEY `user_group_id` (`user_id`,`group_id`) +) DEFAULT CHARSET=utf8; + +CREATE TABLE IF NOT EXISTS `userapi` ( + `userapi_id` bigint(20) NOT NULL AUTO_INCREMENT, + `user_id` bigint(20) NOT NULL, + `apikey` varchar(64) NOT NULL, + `application_name` varchar(255) NOT NULL, + `token_expiration_time` int(11) NOT NULL, + `creation_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`userapi_id`) +) DEFAULT CHARSET=utf8; diff --git a/core/database/pgsql/3.4.1.sql b/core/database/pgsql/3.4.1.sql new file mode 100644 index 000000000..17ab3a3db --- /dev/null +++ b/core/database/pgsql/3.4.1.sql @@ -0,0 +1,339 @@ +-- Midas Server. Copyright Kitware SAS. Licensed under the Apache License 2.0. + +-- PostgreSQL core database, version 3.4.1 + +SET client_encoding = 'UTF8'; +SET default_with_oids = FALSE; + +CREATE TABLE IF NOT EXISTS "activedownload" ( + "activedownload_id" serial PRIMARY KEY, + "ip" character varying(100) DEFAULT ''::character varying NOT NULL, + "date_creation" timestamp without time zone NOT NULL DEFAULT now(), + "last_update" timestamp without time zone NOT NULL +); + +CREATE INDEX "activedownload_idx_ip" ON "activedownload" ("ip"); + +CREATE TABLE IF NOT EXISTS "assetstore" ( + "assetstore_id" serial PRIMARY KEY, + "name" character varying(256) NOT NULL, + "path" character varying(512) NOT NULL, + "type" smallint NOT NULL +); + +CREATE TABLE IF NOT EXISTS "bitstream" ( + "bitstream_id" serial PRIMARY KEY, + "itemrevision_id" bigint NOT NULL, + "name" character varying(256) NOT NULL, + "mimetype" character varying(30) NOT NULL, + "sizebytes" bigint NOT NULL, + "checksum" character varying(64) NOT NULL, + "path" character varying(512) NOT NULL, + "assetstore_id" integer NOT NULL, + "date" timestamp without time zone NOT NULL +); + +CREATE INDEX "bitstream_idx_checksum" ON "bitstream" ("checksum"); + +CREATE TABLE IF NOT EXISTS "community" ( + "community_id" serial PRIMARY KEY, + "name" character varying(256) NOT NULL, + "description" text NOT NULL, + "creation" timestamp without time zone, + "privacy" integer NOT NULL, + "folder_id" bigint, + "admingroup_id" bigint, + "moderatorgroup_id" bigint, + "view" bigint DEFAULT 0::bigint NOT NULL, + "membergroup_id" bigint, + "can_join" integer DEFAULT 0 NOT NULL, + "uuid" character varying(512) DEFAULT ''::character varying +); + +CREATE TABLE IF NOT EXISTS "communityinvitation" ( + "communityinvitation_id" serial PRIMARY KEY, + "community_id" bigint, + "user_id" bigint, + "group_id" bigint +); + +CREATE TABLE IF NOT EXISTS "errorlog" ( + "errorlog_id" serial PRIMARY KEY, + "priority" integer NOT NULL, + "module" character varying(256) NOT NULL, + "message" text NOT NULL, + "datetime" timestamp without time zone +); + +CREATE TABLE IF NOT EXISTS "feed" ( + "feed_id" serial PRIMARY KEY, + "date" timestamp without time zone NOT NULL, + "user_id" bigint NOT NULL, + "type" integer NOT NULL, + "resource" character varying(256) NOT NULL +); + +CREATE TABLE IF NOT EXISTS "feed2community" ( + "id" serial PRIMARY KEY, + "feed_id" bigint NOT NULL, + "community_id" bigint NOT NULL +); + +CREATE TABLE IF NOT EXISTS "feedpolicygroup" ( + "id" serial PRIMARY KEY, + "feed_id" bigint NOT NULL, + "group_id" bigint NOT NULL, + "policy" smallint NOT NULL, + "date" timestamp without time zone NOT NULL DEFAULT now() +); + +CREATE TABLE IF NOT EXISTS "feedpolicyuser" ( + "id" serial PRIMARY KEY, + "feed_id" bigint NOT NULL, + "user_id" bigint NOT NULL, + "policy" smallint NOT NULL, + "date" timestamp without time zone NOT NULL DEFAULT now() +); + +CREATE TABLE IF NOT EXISTS "folder" ( + "folder_id" serial PRIMARY KEY, + "left_index" bigint NOT NULL, + "right_index" bigint NOT NULL, + "parent_id" bigint DEFAULT 0::bigint NOT NULL, + "name" character varying(256) NOT NULL, + "description" text NOT NULL, + "view" bigint DEFAULT 0::bigint NOT NULL, + "date_update" timestamp without time zone NOT NULL DEFAULT now(), + "teaser" character varying(256) DEFAULT ''::character varying, + "privacy_status" integer DEFAULT 0 NOT NULL, + "uuid" character varying(512) DEFAULT ''::character varying, + "date_creation" timestamp without time zone +); + +CREATE INDEX "folder_idx_left_index" ON "folder" ("left_index"); +CREATE INDEX "folder_idx_parent_id" ON "folder" ("parent_id"); +CREATE INDEX "folder_idx_right_index" ON "folder" ("right_index"); + +CREATE TABLE IF NOT EXISTS "folderpolicygroup" ( + "id" serial PRIMARY KEY, + "folder_id" bigint NOT NULL, + "group_id" bigint NOT NULL, + "policy" smallint NOT NULL, + "date" timestamp without time zone NOT NULL DEFAULT now(), + UNIQUE ("folder_id", "group_id") +); + +CREATE TABLE IF NOT EXISTS "folderpolicyuser" ( + "id" serial PRIMARY KEY, + "folder_id" bigint NOT NULL, + "user_id" bigint NOT NULL, + "policy" smallint NOT NULL, + "date" timestamp without time zone NOT NULL DEFAULT now(), + UNIQUE ("folder_id", "user_id") +); + +CREATE TABLE IF NOT EXISTS "group" ( + "group_id" serial PRIMARY KEY, + "community_id" bigint NOT NULL, + "name" character varying(256) NOT NULL +); + +CREATE TABLE IF NOT EXISTS "item" ( + "item_id" serial PRIMARY KEY, + "name" character varying(256) NOT NULL, + "date_update" timestamp without time zone NOT NULL DEFAULT now(), + "description" text NOT NULL, + "type" integer NOT NULL, + "view" bigint DEFAULT 0::bigint NOT NULL, + "download" bigint DEFAULT 0::bigint NOT NULL, + "sizebytes" bigint DEFAULT 0::bigint NOT NULL, + "privacy_status" integer DEFAULT 0 NOT NULL, + "uuid" character varying(512) DEFAULT ''::character varying, + "date_creation" timestamp without time zone, + "thumbnail_id" bigint +); + +CREATE TABLE IF NOT EXISTS "item2folder" ( + "id" serial PRIMARY KEY, + "item_id" bigint NOT NULL, + "folder_id" bigint NOT NULL +); + +CREATE INDEX "item2folder_idx_folder_id" ON "item2folder" ("folder_id"); + +CREATE TABLE IF NOT EXISTS "itempolicygroup" ( + "id" serial PRIMARY KEY, + "item_id" bigint NOT NULL, + "group_id" bigint NOT NULL, + "policy" smallint NOT NULL, + "date" timestamp without time zone NOT NULL DEFAULT now(), + UNIQUE ("item_id", "group_id") +); + +CREATE TABLE IF NOT EXISTS "itempolicyuser" ( + "id" serial PRIMARY KEY, + "item_id" bigint NOT NULL, + "user_id" bigint NOT NULL, + "policy" smallint NOT NULL, + "date" timestamp without time zone NOT NULL DEFAULT now(), + UNIQUE ("item_id", "user_id") +); + +CREATE TABLE IF NOT EXISTS "itemrevision" ( + "itemrevision_id" serial PRIMARY KEY, + "item_id" bigint NOT NULL, + "revision" integer NOT NULL, + "date" timestamp without time zone NOT NULL, + "changes" text NOT NULL, + "user_id" integer NOT NULL, + "uuid" character varying(512) DEFAULT ''::character varying, + "license_id" bigint +); + +CREATE TABLE IF NOT EXISTS "license" ( + "license_id" serial PRIMARY KEY, + "name" text NOT NULL, + "fulltext" text NOT NULL +); + +INSERT INTO "license" VALUES +(1, 'Public (PDDL)', '**You are free:**\n\n* To Share: To copy, distribute and use the database.\n* To Create: To produce works from the database.\n* To Adapt: To modify, transform, and build upon the database.\n\n[Full License Information](http://opendatacommons.org/licenses/pddl/summary)'), +(2, 'Public: Attribution (ODC-BY)', '**You are free:**\n\n* To Share: To copy, distribute and use the database.\n* To Create: To produce works from the database.\n* To Adapt: To modify, transform, and build upon the database.\n\n**As long as you:**\n\n* Attribute: You must attribute any public use of the database, or works produced from the database, in the manner specified in the license. For any use or redistribution of the database, or works produced from it, you must make clear to others the license of the database and keep intact any notices on the original database.\n\n[Full License Information](http://opendatacommons.org/licenses/by/summary)'), +(3, 'Public: Attribution, Share-Alike (ODbL)', '**You are free:**\n\n* To Share: To copy, distribute and use the database.\n* To Create: To produce works from the database.\n* To Adapt: To modify, transform, and build upon the database.\n\n**As long as you:**\n\n* Attribute: You must attribute any public use of the database, or works produced from the database, in the manner specified in the license. For any use or redistribution of the database, or works produced from it, you must make clear to others the license of the database and keep intact any notices on the original database.\n* Share-Alike: If you publicly use any adapted version of this database, or works produced from an adapted database, you must also offer that adapted database under the ODbL.\n* Keep open: If you redistribute the database, or an adapted version of it, then you may use technological measures that restrict the work (such as DRM) as long as you also redistribute a version without such measures.\n\n[Full License Information](http://opendatacommons.org/licenses/odbl/summary)'), +(4, 'Private: All Rights Reserved', 'This work is copyrighted by its author or licensor. You must not share, distribute, or modify this work without the prior consent of the author or licensor.'), +(5, 'Public: Attribution (CC BY 3.0)', '**You are free:**\n\n* To Share: To copy, distribute and transmit the work.\n* To Remix: To adapt the work.\n* To make commercial use of the work.\n\n**Under the following conditions:**\n\n* Attribution: You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work).\n\n[Full License Information](http://creativecommons.org/licenses/by/3.0/)'), +(6, 'Public: Attribution, Share-Alike (CC BY-SA 3.0)', '**You are free:**\n\n* To Share: To copy, distribute and transmit the work.\n* To Remix: To adapt the work.\n* To make commercial use of the work.\n\n**Under the following conditions:**\n\n* Attribution: You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work).\n* Share-Alike: If you alter, transform, or build upon this work, you may distribute the resulting work only under the same or similar license to this one.\n\n[Full License Information](http://creativecommons.org/licenses/by-sa/3.0/)'), +(7, 'Public: Attribution, No Derivative Works (CC BY-ND 3.0)', '**You are free:**\n\n* To Share: To copy, distribute and transmit the work.\n* To make commercial use of the work.\n\n**Under the following conditions:**\n\n* Attribution: You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work).\n* No Derivative Works: You may not alter, transform, or build upon this work.\n\n[Full License Information](http://creativecommons.org/licenses/by-nd/3.0/)'), +(8, 'Public: Attribution, Non-Commercial (CC BY-NC 3.0)', '**You are free:**\n\n* To Share: To copy, distribute and transmit the work.\n* To Remix: To adapt the work.\n\n**Under the following conditions:**\n\n* Attribution: You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work).\n* Non-Commercial: You may not use this work for commercial purposes.\n\n[Full License Information](http://creativecommons.org/licenses/by-nc/3.0/)'), +(9, 'Public: Attribution, Non-Commercial, Share-Alike (CC BY-NC-SA 3.0)', '**You are free:**\n\n* To Share: To copy, distribute and transmit the work.\n* To Remix: To adapt the work.\n\n**Under the following conditions:**\n\n* Attribution: You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work).\n* Non-Commercial: You may not use this work for commercial purposes.\n* Share-Alike: If you alter, transform, or build upon this work, you may distribute the resulting work only under the same or similar license to this one.\n\n[Full License Information](http://creativecommons.org/licenses/by-nc-sa/3.0/)'), +(10, 'Public: Attribution, Non-Commercial, No Derivative Works (CC BY-NC-ND 3.0)', '**You are free:**\n\n* To Share: To copy, distribute and transmit the work.\n\n**Under the following conditions:**\n\n* Attribution: You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work).\n* Non-Commercial: You may not use this work for commercial purposes.\n* No Derivative Works: You may not alter, transform, or build upon this work.\n\n[Full License Information](http://creativecommons.org/licenses/by-nc-nd/3.0/)'); + +CREATE TABLE IF NOT EXISTS "metadata" ( + "metadata_id" serial PRIMARY KEY, + "metadatatype" integer DEFAULT 0 NOT NULL, + "element" character varying(256) NOT NULL, + "qualifier" character varying(256) NOT NULL +); + +INSERT INTO metadata VALUES +(1, 0, 'contributor', 'author'), +(2, 0, 'date', 'uploaded'), +(3, 0, 'date', 'issued'), +(4, 0, 'date', 'created'), +(5, 0, 'identifier', 'citation'), +(6, 0, 'identifier', 'uri'), +(7, 0, 'identifier', 'pubmed'), +(8, 0, 'identifier', 'doi'), +(9, 0, 'description', 'general'), +(10, 0, 'description', 'provenance'), +(11, 0, 'description', 'sponsorship'), +(12, 0, 'description', 'publisher'), +(13, 0, 'subject', 'keyword'), +(14, 0, 'subject', 'ocis'); + +CREATE TABLE IF NOT EXISTS "metadatavalue" ( + "metadatavalue_id" serial PRIMARY KEY, + "metadata_id" bigint NOT NULL, + "itemrevision_id" bigint NOT NULL, + "value" character varying(1024) NOT NULL +); + +CREATE TABLE IF NOT EXISTS "module" ( + "module_id" serial PRIMARY KEY, + "name" character varying(256) NOT NULL, + "uuid" character varying(36) NOT NULL, + "current_major_version" integer NOT NULL DEFAULT 0, + "current_minor_version" integer NOT NULL DEFAULT 0, + "current_patch_version" integer NOT NULL DEFAULT 0, + "enabled" smallint NOT NULL DEFAULT 0 +); + +CREATE UNIQUE INDEX "module_idx_name" ON "module" ("name"); +CREATE UNIQUE INDEX "module_idx_uuid" ON "module" ("uuid"); + +CREATE TABLE IF NOT EXISTS "newuserinvitation" ( + "newuserinvitation_id" serial PRIMARY KEY, + "auth_key" character varying(256) NOT NULL, + "email" character varying(256) NOT NULL, + "inviter_id" bigint NOT NULL, + "community_id" bigint NOT NULL, + "group_id" bigint NOT NULL, + "date_creation" timestamp without time zone NOT NULL DEFAULT now() +); + +CREATE TABLE IF NOT EXISTS "password" ( + "hash" character varying(128) NOT NULL, + CONSTRAINT "password_hash" PRIMARY KEY ("hash") +); + +ALTER TABLE "password" CLUSTER ON "password_hash"; + +CREATE TABLE IF NOT EXISTS "pendinguser" ( + "pendinguser_id" serial PRIMARY KEY, + "auth_key" character varying(256) NOT NULL, + "email" character varying(256) NOT NULL, + "firstname" character varying(256) NOT NULL, + "lastname" character varying(256) NOT NULL, + "date_creation" timestamp without time zone NOT NULL DEFAULT now(), + "salt" character varying(64) DEFAULT ''::character varying NOT NULL +); + +CREATE TABLE IF NOT EXISTS "progress" ( + "progress_id" serial PRIMARY KEY, + "message" text NOT NULL, + "current" bigint NOT NULL, + "maximum" bigint NOT NULL, + "date_creation" timestamp without time zone NOT NULL DEFAULT now(), + "last_update" timestamp without time zone NOT NULL +); + +CREATE TABLE IF NOT EXISTS "setting" ( + "setting_id" serial PRIMARY KEY, + "module" character varying(256) NOT NULL, + "name" character varying(256) NOT NULL, + "value" text NOT NULL +); + +CREATE TABLE IF NOT EXISTS "token" ( + "token_id" serial PRIMARY KEY, + "userapi_id" bigint NOT NULL, + "token" character varying(64) NOT NULL, + "expiration_date" timestamp without time zone NOT NULL DEFAULT now() +); + +CREATE TABLE IF NOT EXISTS "user" ( + "user_id" serial PRIMARY KEY, + "firstname" character varying(256) NOT NULL, + "company" character varying(256), + "thumbnail" character varying(256), + "lastname" character varying(256) NOT NULL, + "email" character varying(256) NOT NULL, + "privacy" integer DEFAULT 0 NOT NULL, + "admin" integer DEFAULT 0 NOT NULL, + "view" bigint DEFAULT 0::bigint NOT NULL, + "folder_id" bigint, + "creation" timestamp without time zone, + "uuid" character varying(512) DEFAULT ''::character varying, + "city" character varying(100) DEFAULT ''::character varying, + "country" character varying(100) DEFAULT ''::character varying, + "website" character varying(256) DEFAULT ''::character varying, + "biography" text, + "dynamichelp" integer DEFAULT 1, + "hash_alg" character varying(32) DEFAULT ''::character varying NOT NULL, + "salt" character varying(64) DEFAULT ''::character varying NOT NULL +); + +CREATE TABLE IF NOT EXISTS "user2group" ( + "id" serial PRIMARY KEY, + "user_id" bigint NOT NULL, + "group_id" bigint NOT NULL +); + +CREATE TABLE IF NOT EXISTS "userapi" ( + "userapi_id" serial PRIMARY KEY, + "user_id" bigint NOT NULL, + "apikey" character varying(64) NOT NULL, + "application_name" character varying(256) NOT NULL, + "token_expiration_time" integer NOT NULL, + "creation_date" timestamp without time zone +); diff --git a/core/database/sqlite/3.4.1.sql b/core/database/sqlite/3.4.1.sql new file mode 100644 index 000000000..6f73cb257 --- /dev/null +++ b/core/database/sqlite/3.4.1.sql @@ -0,0 +1,331 @@ +-- Midas Server. Copyright Kitware SAS. Licensed under the Apache License 2.0. + +-- SQLite core database, version 3.4.0 + +CREATE TABLE IF NOT EXISTS "activedownload" ( + "activedownload_id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + "ip" TEXT NOT NULL DEFAULT '', + "date_creation" TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, + "last_update" TEXT NOT NULL DEFAULT '0000-00-00 00:00:00' +); + +CREATE INDEX IF NOT EXISTS "activedownload_ip_idx" ON "activedownload" ("ip"); + +CREATE TABLE IF NOT EXISTS "assetstore" ( + "assetstore_id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + "name" TEXT NOT NULL, + "path" TEXT NOT NULL, + "type" INTEGER NOT NULL +); + +CREATE TABLE IF NOT EXISTS "bitstream" ( + "bitstream_id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + "itemrevision_id" INTEGER NOT NULL, + "name" TEXT NOT NULL, + "mimetype" TEXT NOT NULL, + "sizebytes" INTEGER NOT NULL, + "checksum" TEXT NOT NULL, + "path" TEXT NOT NULL, + "assetstore_id" INTEGER NOT NULL, + "date" TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +CREATE INDEX IF NOT EXISTS "bitstream_checksum_idx" ON "bitstream" ("checksum"); + +CREATE TABLE IF NOT EXISTS "community" ( + "community_id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + "name" TEXT NOT NULL, + "description" TEXT NOT NULL, + "creation" TEXT, + "privacy" INTEGER NOT NULL, + "folder_id" INTEGER, + "admingroup_id" INTEGER, + "moderatorgroup_id" INTEGER, + "view" INTEGER NOT NULL DEFAULT 0, + "membergroup_id" INTEGER, + "can_join" INTEGER NOT NULL DEFAULT 0, + "uuid" TEXT DEFAULT '' +); + +CREATE TABLE IF NOT EXISTS "communityinvitation" ( + "communityinvitation_id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + "community_id" INTEGER, + "user_id" INTEGER, + "group_id" INTEGER +); + +CREATE TABLE IF NOT EXISTS "errorlog" ( + "errorlog_id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + "priority" INTEGER NOT NULL, + "module" TEXT NOT NULL, + "message" TEXT NOT NULL, + "datetime" TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +CREATE TABLE IF NOT EXISTS "feed" ( + "feed_id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + "date" TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, + "user_id" INTEGER NOT NULL, + "type" INTEGER NOT NULL, + "resource" TEXT NOT NULL +); + +CREATE TABLE IF NOT EXISTS "feed2community" ( + "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + "feed_id" INTEGER NOT NULL, + "community_id" INTEGER NOT NULL +); + +CREATE TABLE IF NOT EXISTS "feedpolicygroup" ( + "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + "feed_id" INTEGER NOT NULL, + "group_id" INTEGER NOT NULL, + "policy" INTEGER NOT NULL, + "date" TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +CREATE TABLE IF NOT EXISTS "feedpolicyuser" ( + "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + "feed_id" INTEGER NOT NULL, + "user_id" INTEGER NOT NULL, + "policy" INTEGER NOT NULL, + "date" TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +CREATE TABLE IF NOT EXISTS "folder" ( + "folder_id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + "left_index" INTEGER NOT NULL, + "right_index" INTEGER NOT NULL, + "parent_id" INTEGER NOT NULL DEFAULT 0, + "name" TEXT NOT NULL, + "description" TEXT NOT NULL, + "view" INTEGER NOT NULL DEFAULT 0, + "date_update" TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, + "teaser" TEXT DEFAULT '', + "privacy_status" INTEGER NOT NULL DEFAULT 0, + "uuid" TEXT DEFAULT '', + "date_creation" TEXT NOT NULL DEFAULT '0000-00-00 00:00:00' +); + +CREATE INDEX IF NOT EXISTS "folder_left_index_idx" ON "folder" ("left_index"); +CREATE INDEX IF NOT EXISTS "folder_parent_id_idx" ON "folder" ("parent_id"); +CREATE INDEX IF NOT EXISTS "folder_right_index_idx" ON "folder" ("right_index"); + +CREATE TABLE IF NOT EXISTS "folderpolicygroup" ( + "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + "folder_id" INTEGER NOT NULL, + "group_id" INTEGER NOT NULL, + "policy" INTEGER NOT NULL, + "date" TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE ("folder_id", "group_id") +); + +CREATE TABLE IF NOT EXISTS "folderpolicyuser" ( + "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + "folder_id" INTEGER NOT NULL, + "user_id" INTEGER NOT NULL, + "policy" INTEGER NOT NULL, + "date" TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE ("folder_id", "user_id") +); + +CREATE TABLE IF NOT EXISTS "group" ( + "group_id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + "community_id" INTEGER NOT NULL, + "name" TEXT NOT NULL +); + +CREATE TABLE IF NOT EXISTS "item" ( + "item_id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + "name" TEXT NOT NULL, + "date_update" TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, + "description" TEXT NOT NULL, + "type" INTEGER NOT NULL, + "view" INTEGER NOT NULL DEFAULT 0, + "download" INTEGER NOT NULL DEFAULT 0, + "sizebytes" INTEGER NOT NULL DEFAULT 0, + "privacy_status" INTEGER NOT NULL DEFAULT 0, + "uuid" TEXT DEFAULT '', + "date_creation" TEXT NOT NULL DEFAULT '0000-00-00 00:00:00', + "thumbnail_id" INTEGER +); + +CREATE TABLE IF NOT EXISTS "item2folder" ( + "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + "item_id" INTEGER NOT NULL, + "folder_id" INTEGER NOT NULL +); + +CREATE INDEX IF NOT EXISTS "item2folder_folder_id_idx" ON "item2folder" ("folder_id"); + +CREATE TABLE IF NOT EXISTS "itempolicygroup" ( + "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + "item_id" INTEGER NOT NULL, + "group_id" INTEGER NOT NULL, + "policy" INTEGER NOT NULL, + "date" TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE ("item_id", "group_id") +); + +CREATE TABLE IF NOT EXISTS "itempolicyuser" ( + "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + "item_id" INTEGER NOT NULL, + "user_id" INTEGER NOT NULL, + "policy" INTEGER NOT NULL, + "date" TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE ("item_id", "user_id") +); + +CREATE TABLE IF NOT EXISTS "itemrevision" ( + "itemrevision_id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + "item_id" INTEGER NOT NULL, + "revision" INTEGER NOT NULL, + "date" TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, + "changes" TEXT NOT NULL, + "user_id" INTEGER NOT NULL, + "uuid" TEXT DEFAULT '', + "license_id" INTEGER +); + +CREATE TABLE IF NOT EXISTS "license" ( + "license_id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + "name" TEXT NOT NULL, + "fulltext" TEXT NOT NULL +); + +INSERT OR IGNORE INTO "license" VALUES (1, 'Public (PDDL)', '**You are free:**\n\n* To Share: To copy, distribute and use the database.\n* To Create: To produce works from the database.\n* To Adapt: To modify, transform, and build upon the database.\n\n[Full License Information](http://opendatacommons.org/licenses/pddl/summary)'); +INSERT OR IGNORE INTO "license" VALUES (2, 'Public: Attribution (ODC-BY)', '**You are free:**\n\n* To Share: To copy, distribute and use the database.\n* To Create: To produce works from the database.\n* To Adapt: To modify, transform, and build upon the database.\n\n**As long as you:**\n\n* Attribute: You must attribute any public use of the database, or works produced from the database, in the manner specified in the license. For any use or redistribution of the database, or works produced from it, you must make clear to others the license of the database and keep intact any notices on the original database.\n\n[Full License Information](http://opendatacommons.org/licenses/by/summary)'); +INSERT OR IGNORE INTO "license" VALUES (3, 'Public: Attribution, Share-Alike (ODbL)', '**You are free:**\n\n* To Share: To copy, distribute and use the database.\n* To Create: To produce works from the database.\n* To Adapt: To modify, transform, and build upon the database.\n\n**As long as you:**\n\n* Attribute: You must attribute any public use of the database, or works produced from the database, in the manner specified in the license. For any use or redistribution of the database, or works produced from it, you must make clear to others the license of the database and keep intact any notices on the original database.\n* Share-Alike: If you publicly use any adapted version of this database, or works produced from an adapted database, you must also offer that adapted database under the ODbL.\n* Keep open: If you redistribute the database, or an adapted version of it, then you may use technological measures that restrict the work (such as DRM) as long as you also redistribute a version without such measures.\n\n[Full License Information](http://opendatacommons.org/licenses/odbl/summary)'); +INSERT OR IGNORE INTO "license" VALUES (4, 'Private: All Rights Reserved', 'This work is copyrighted by its author or licensor. You must not share, distribute, or modify this work without the prior consent of the author or licensor.'); +INSERT OR IGNORE INTO "license" VALUES (5, 'Public: Attribution (CC BY 3.0)', '**You are free:**\n\n* To Share: To copy, distribute and transmit the work.\n* To Remix: To adapt the work.\n* To make commercial use of the work.\n\n**Under the following conditions:**\n\n* Attribution: You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work).\n\n[Full License Information](http://creativecommons.org/licenses/by/3.0/)'); +INSERT OR IGNORE INTO "license" VALUES (6, 'Public: Attribution, Share-Alike (CC BY-SA 3.0)', '**You are free:**\n\n* To Share: To copy, distribute and transmit the work.\n* To Remix: To adapt the work.\n* To make commercial use of the work.\n\n**Under the following conditions:**\n\n* Attribution: You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work).\n* Share-Alike: If you alter, transform, or build upon this work, you may distribute the resulting work only under the same or similar license to this one.\n\n[Full License Information](http://creativecommons.org/licenses/by-sa/3.0/)'); +INSERT OR IGNORE INTO "license" VALUES (7, 'Public: Attribution, No Derivative Works (CC BY-ND 3.0)', '**You are free:**\n\n* To Share: To copy, distribute and transmit the work.\n* To make commercial use of the work.\n\n**Under the following conditions:**\n\n* Attribution: You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work).\n* No Derivative Works: You may not alter, transform, or build upon this work.\n\n[Full License Information](http://creativecommons.org/licenses/by-nd/3.0/)'); +INSERT OR IGNORE INTO "license" VALUES (8, 'Public: Attribution, Non-Commercial (CC BY-NC 3.0)', '**You are free:**\n\n* To Share: To copy, distribute and transmit the work.\n* To Remix: To adapt the work.\n\n**Under the following conditions:**\n\n* Attribution: You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work).\n* Non-Commercial: You may not use this work for commercial purposes.\n\n[Full License Information](http://creativecommons.org/licenses/by-nc/3.0/)'); +INSERT OR IGNORE INTO "license" VALUES (9, 'Public: Attribution, Non-Commercial, Share-Alike (CC BY-NC-SA 3.0)', '**You are free:**\n\n* To Share: To copy, distribute and transmit the work.\n* To Remix: To adapt the work.\n\n**Under the following conditions:**\n\n* Attribution: You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work).\n* Non-Commercial: You may not use this work for commercial purposes.\n* Share-Alike: If you alter, transform, or build upon this work, you may distribute the resulting work only under the same or similar license to this one.\n\n[Full License Information](http://creativecommons.org/licenses/by-nc-sa/3.0/)'); +INSERT OR IGNORE INTO "license" VALUES (10, 'Public: Attribution, Non-Commercial, No Derivative Works (CC BY-NC-ND 3.0)', '**You are free:**\n\n* To Share: To copy, distribute and transmit the work.\n\n**Under the following conditions:**\n\n* Attribution: You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work).\n* Non-Commercial: You may not use this work for commercial purposes.\n* No Derivative Works: You may not alter, transform, or build upon this work.\n\n[Full License Information](http://creativecommons.org/licenses/by-nc-nd/3.0/)'); + +CREATE TABLE IF NOT EXISTS "metadata" ( + "metadata_id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + "metadatatype" INTEGER NOT NULL DEFAULT 0, + "element" TEXT NOT NULL, + "qualifier" TEXT NOT NULL +); + +INSERT OR IGNORE INTO "metadata" VALUES (1, 0, 'contributor', 'author'); +INSERT OR IGNORE INTO "metadata" VALUES (2, 0, 'date', 'uploaded'); +INSERT OR IGNORE INTO "metadata" VALUES (3, 0, 'date', 'issued'); +INSERT OR IGNORE INTO "metadata" VALUES (4, 0, 'date', 'created'); +INSERT OR IGNORE INTO "metadata" VALUES (5, 0, 'identifier', 'citation'); +INSERT OR IGNORE INTO "metadata" VALUES (6, 0, 'identifier', 'uri'); +INSERT OR IGNORE INTO "metadata" VALUES (7, 0, 'identifier', 'pubmed'); +INSERT OR IGNORE INTO "metadata" VALUES (8, 0, 'identifier', 'doi'); +INSERT OR IGNORE INTO "metadata" VALUES (9, 0, 'description', 'general'); +INSERT OR IGNORE INTO "metadata" VALUES (10, 0, 'description', 'provenance'); +INSERT OR IGNORE INTO "metadata" VALUES (11, 0, 'description', 'sponsorship'); +INSERT OR IGNORE INTO "metadata" VALUES (12, 0, 'description', 'publisher'); +INSERT OR IGNORE INTO "metadata" VALUES (13, 0, 'subject', 'keyword'); +INSERT OR IGNORE INTO "metadata" VALUES (14, 0, 'subject', 'ocis'); + +CREATE TABLE IF NOT EXISTS "metadatavalue" ( + "metadatavalue_id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + "metadata_id" INTEGER NOT NULL, + "itemrevision_id" INTEGER NOT NULL, + "value" TEXT NOT NULL +); + +CREATE TABLE IF NOT EXISTS "module" ( + "module_id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + "name" TEXT NOT NULL, + "uuid" TEXT NOT NULL, + "current_major_version" INTEGER NOT NULL DEFAULT 0, + "current_minor_version" INTEGER NOT NULL DEFAULT 0, + "current_patch_version" INTEGER NOT NULL DEFAULT 0, + "enabled" INTEGER NOT NULL DEFAULT 0 +); + +CREATE UNIQUE INDEX IF NOT EXISTS "module_name_idx" ON "module" ("name"); +CREATE UNIQUE INDEX IF NOT EXISTS "module_uuid_idx" ON "module" ("uuid"); + +CREATE TABLE IF NOT EXISTS "newuserinvitation" ( + "newuserinvitation_id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + "auth_key" TEXT NOT NULL, + "email" TEXT NOT NULL, + "inviter_id" INTEGER NOT NULL, + "community_id" INTEGER NOT NULL, + "group_id" INTEGER NOT NULL, + "date_creation" TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +CREATE TABLE IF NOT EXISTS "password" ( + "hash" TEXT PRIMARY KEY NOT NULL +); + +CREATE TABLE IF NOT EXISTS "pendinguser" ( + "pendinguser_id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + "auth_key" TEXT NOT NULL, + "email" TEXT NOT NULL, + "firstname" TEXT NOT NULL, + "lastname" TEXT NOT NULL, + "date_creation" TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, + "salt" TEXT NOT NULL DEFAULT '' +); + +CREATE TABLE IF NOT EXISTS "progress" ( + "progress_id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + "message" TEXT NOT NULL, + "current" INTEGER NOT NULL, + "maximum" INTEGER NOT NULL, + "date_creation" TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, + "last_update" TEXT NOT NULL DEFAULT '0000-00-00 00:00:00' +); + +CREATE TABLE IF NOT EXISTS "setting" ( + "setting_id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + "module" TEXT NOT NULL, + "name" TEXT NOT NULL, + "value" TEXT NOT NULL +); + +CREATE TABLE IF NOT EXISTS "token" ( + "token_id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + "userapi_id" INTEGER NOT NULL, + "token" TEXT NOT NULL, + "expiration_date" TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +CREATE TABLE IF NOT EXISTS "user" ( + "user_id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + "firstname" TEXT NOT NULL, + "company" TEXT, + "thumbnail" TEXT, + "lastname" TEXT NOT NULL, + "email" TEXT NOT NULL, + "privacy" INTEGER NOT NULL DEFAULT 0, + "admin" INTEGER NOT NULL DEFAULT 0, + "view" INTEGER NOT NULL DEFAULT 0, + "folder_id" INTEGER, + "creation" TEXT, + "uuid" TEXT DEFAULT '', + "city" TEXT DEFAULT '', + "country" TEXT DEFAULT '', + "website" TEXT DEFAULT '', + "biography" TEXT DEFAULT '', + "dynamichelp" INTEGER DEFAULT 1, + "hash_alg" TEXT NOT NULL DEFAULT '', + "salt" TEXT NOT NULL DEFAULT '' +); + +CREATE TABLE IF NOT EXISTS "user2group" ( + "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + "user_id" INTEGER NOT NULL, + "group_id" INTEGER NOT NULL +); + +CREATE TABLE IF NOT EXISTS "userapi" ( + "userapi_id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + "user_id" INTEGER NOT NULL, + "apikey" TEXT NOT NULL, + "application_name" TEXT NOT NULL, + "token_expiration_time" INTEGER NOT NULL, + "creation_date" TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP +); diff --git a/core/database/upgrade/3.4.1.php b/core/database/upgrade/3.4.1.php new file mode 100644 index 000000000..013a81d2e --- /dev/null +++ b/core/database/upgrade/3.4.1.php @@ -0,0 +1,157 @@ +db->query(" + CREATE TABLE IF NOT EXISTS `module` ( + `module_id` bigint(20) NOT NULL AUTO_INCREMENT, + `name` varchar(255) NOT NULL, + `uuid` varchar(36) NOT NULL, + `current_major_version` int(11) NOT NULL DEFAULT '0', + `current_minor_version` int(11) NOT NULL DEFAULT '0', + `current_patch_version` int(11) NOT NULL DEFAULT '0', + `enabled` tinyint(4) NOT NULL DEFAULT '0', + PRIMARY KEY (`module_id`), + UNIQUE KEY (`name`), + UNIQUE KEY (`uuid`) + ) DEFAULT CHARSET=utf8; + "); + } + + /** Upgrade a PostgreSQL database. */ + public function pgsql() + { + $this->db->query(' + CREATE TABLE IF NOT EXISTS "module" ( + "module_id" serial PRIMARY KEY, + "name" character varying(256) NOT NULL, + "uuid" character varying(36) NOT NULL, + "current_major_version" integer NOT NULL DEFAULT 0, + "current_minor_version" integer NOT NULL DEFAULT 0, + "current_patch_version" integer NOT NULL DEFAULT 0, + "enabled" smallint NOT NULL DEFAULT 0 + ); + '); + $this->db->query('CREATE UNIQUE INDEX "module_idx_name" ON "module" ("name");'); + $this->db->query('CREATE UNIQUE INDEX "module_idx_uuid" ON "module" ("uuid");'); + } + + /** Upgrade a SQLite database. */ + public function sqlite() + { + $this->db->query(' + CREATE TABLE IF NOT EXISTS "module" ( + "module_id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + "name" TEXT NOT NULL, + "uuid" TEXT NOT NULL, + "current_major_version" INTEGER NOT NULL DEFAULT 0, + "current_minor_version" INTEGER NOT NULL DEFAULT 0, + "current_patch_version" INTEGER NOT NULL DEFAULT 0, + "enabled" INTEGER NOT NULL DEFAULT 0 + ); + '); + $this->db->query('CREATE UNIQUE INDEX IF NOT EXISTS "module_name_idx" ON "module" ("name");'); + $this->db->query('CREATE UNIQUE INDEX IF NOT EXISTS "module_uuid_idx" ON "module" ("uuid");'); + } + + /** Post database upgrade. */ + public function postUpgrade() + { + /** @var ModuleModel $moduleModel */ + $moduleModel = MidasLoader::loadModel('Module'); + + /** @var UuidComponent $uuidComponent */ + $uuidComponent = MidasLoader::loadComponent('Uuid'); + + $modules = new Zend_Config_Ini(APPLICATION_CONFIG, 'module'); + $oldLocalConfigs = array(); + + foreach ($modules as $key => $value) { + if (file_exists(BASE_PATH.'/modules/'.$key.'/AppController.php')) { + $moduleRoot = BASE_PATH.'/modules/'.$key; + } elseif (file_exists(BASE_PATH.'/privateModules/'.$key.'/AppController.php')) { + $moduleRoot = BASE_PATH.'/privateModules/'.$key; + } else { + continue; + } + + $moduleConfig = new Zend_Config_Ini($moduleRoot.'/configs/module.ini', 'global'); + + /** @var ModuleDao $moduleDao */ + $moduleDao = MidasLoader::newDao('ModuleDao'); + $moduleDao->setName($key); + + $uuid = $moduleConfig->get('uuid', false); + + if ($uuid === false) { + $moduleDao->setUuid($uuidComponent->generate()); + } else { + $moduleDao->setUuid(str_replace('-', '', $uuid)); + } + + $localConfigPath = LOCAL_CONFIGS_PATH.'/'.$key.'.local.ini'; + + if (file_exists($localConfigPath)) { + $localConfig = new Zend_Config_Ini($localConfigPath, 'global'); + $moduleDao->setCurrentVersion($localConfig->get('version', '0.0.0')); + } else { + $localConfig = false; + $moduleDao->setCurrentVersion($moduleConfig->get('version', '0.0.0')); + } + + $moduleDao->setEnabled($value == 1 ? 1 : 0); + $moduleModel->save($moduleDao); + + if ($uuid && $localConfig) { + $oldLocalConfigs[] = $localConfigPath; + } + } + + $applicationConfig = new Zend_Config_Ini(APPLICATION_CONFIG, null, true); + unset($applicationConfig->module); + + $applicationWriter = new Zend_Config_Writer_Ini(); + $applicationWriter->setConfig($applicationConfig); + $applicationWriter->setFilename(APPLICATION_CONFIG); + $applicationWriter->write(); + + $databaseConfig = new Zend_Config_Ini(DATABASE_CONFIG, null, true); + unset($databaseConfig->development->version); + unset($databaseConfig->production->version); + unset($databaseConfig->testing->version); + + $databaseWriter = new Zend_Config_Writer_Ini(); + $databaseWriter->setConfig($databaseConfig); + $databaseWriter->setFilename(DATABASE_CONFIG); + $databaseWriter->write(); + + unset(Zend_Registry::get('configDatabase')->version); + + /** @var string $oldLocalConfig */ + foreach ($oldLocalConfigs as $oldLocalConfig) { + rename($oldLocalConfig, str_replace('.local.ini', '.old.local.ini', $oldLocalConfig)); + } + } +} diff --git a/core/models/base/ModuleModelBase.php b/core/models/base/ModuleModelBase.php new file mode 100644 index 000000000..02879c9b4 --- /dev/null +++ b/core/models/base/ModuleModelBase.php @@ -0,0 +1,68 @@ +_name = 'module'; + $this->_key = 'module_id'; + + $this->_mainData = array( + 'module_id' => array('type' => MIDAS_DATA), + 'name' => array('type' => MIDAS_DATA), + 'uuid' => array('type' => MIDAS_DATA), + 'current_major_version' => array('type' => MIDAS_DATA), + 'current_minor_version' => array('type' => MIDAS_DATA), + 'current_patch_version' => array('type' => MIDAS_DATA), + 'enabled' => array('type' => MIDAS_DATA), + ); + $this->initialize(); // required + } + + /** + * Return a module given its name. + * + * @param string $name name + * @return false|ModuleDao or false on failure + */ + abstract public function getByName($name); + + /** + * Return a module given its UUID. + * + * @param string $uuid UUID + * @return false|ModuleDao module DAO or false on failure + */ + abstract public function getByUuid($uuid); + + /** + * Return the modules that are enabled. + * + * @param bool $enabled true if a module is enabled + * @return array module DAOs + */ + abstract public function getEnabled($enabled = true); +} diff --git a/core/models/base/SettingModelBase.php b/core/models/base/SettingModelBase.php index 206f985d3..506d52a2f 100644 --- a/core/models/base/SettingModelBase.php +++ b/core/models/base/SettingModelBase.php @@ -64,6 +64,7 @@ public function getValueByName($name, $module = 'core') if ($settingDao === false) { return; } + return $settingDao->getValue(); } @@ -107,6 +108,7 @@ public function setConfig($name, $value, $module = 'core') $settingDao->setValue($value); $this->save($settingDao); } + return $settingDao; } } diff --git a/core/models/dao/ModuleDao.php b/core/models/dao/ModuleDao.php new file mode 100644 index 000000000..12470739d --- /dev/null +++ b/core/models/dao/ModuleDao.php @@ -0,0 +1,80 @@ +getCurrentMajorVersion().'.'.$this->getCurrentMinorVersion().'.'.$this->getCurrentPatchVersion(); + } + + /** + * Set the current version of this module. + * + * @param string $currentVersion current version of this module. + * @throws Zend_Exception + */ + public function setCurrentVersion($currentVersion) + { + $result = preg_match('/^([0-9]+)\.([0-9]+)\.([0-9]+)$/i', $currentVersion, $matches); + if ($result !== 1) { + throw new Zend_Exception('Invalid current version string.'); + } + $this->setCurrentMajorVersion($matches[1]); + $this->setCurrentMinorVersion($matches[2]); + $this->setCurrentPatchVersion($matches[3]); + } + + /** + * Return true if this module is enabled. + * + * @return bool true if this module is enabled, false otherwise. + */ + public function isEnabled() + { + return $this->getEnabled() === 1; + } +} diff --git a/core/models/pdo/ModuleModel.php b/core/models/pdo/ModuleModel.php new file mode 100644 index 000000000..772597f69 --- /dev/null +++ b/core/models/pdo/ModuleModel.php @@ -0,0 +1,77 @@ +database->fetchRow( + $this->database->select()->where('name = ?', $name) + ); + + return $this->initDao('Module', $row); + } + + /** + * Return a module given its UUID. + * + * @param string $uuid UUID + * @return false|ModuleDao module DAO or false on failure + * @throws Zend_Exception + */ + public function getByUuid($uuid) + { + $row = $this->database->fetchRow( + $this->database->select()->where('uuid = ?', $uuid) + ); + + return $this->initDao('Module', $row); + } + + /** + * Return the modules that are enabled. + * + * @param bool $enabled true if a module is enabled + * @return array module DAOs + * @throws Zend_Exception + */ + public function getEnabled($enabled = true) + { + $rows = $this->database->fetchAll( + $this->database->select()->where('enabled = ?', (int) $enabled) + ); + $moduleDaos = array(); + foreach ($rows as $row) { + $moduleDaos[] = $this->initDao('Module', $row); + } + + return $moduleDaos; + } +} diff --git a/core/tests/databaseDataset/default.xml b/core/tests/databaseDataset/default.xml index 760858998..e7af67aa9 100644 --- a/core/tests/databaseDataset/default.xml +++ b/core/tests/databaseDataset/default.xml @@ -1,5 +1,9 @@ + + @@ -46,7 +50,6 @@ - @@ -122,8 +125,8 @@ - + params['method'] = 'midas.version'; $resp = $this->_callJsonApi(); $this->_assertStatusOk($resp); - $this->assertEquals($resp->data->version, Zend_Registry::get('configDatabase')->version); + $this->assertEquals($resp->data->version, UtilityComponent::getCurrentModuleVersion('core')); } /** Test the midas.modules.list method. */ @@ -74,7 +74,7 @@ public function testInfo() $this->_assertStatusOk($resp); // We should get version - $this->assertEquals($resp->data->version, Zend_Registry::get('configDatabase')->version); + $this->assertEquals($resp->data->version, UtilityComponent::getCurrentModuleVersion('core')); // We should get modules list $this->assertNotEmpty($resp->data->modules); diff --git a/tests/ControllerTestCase.php b/tests/ControllerTestCase.php index 6cd7cd648..60b0cebd9 100644 --- a/tests/ControllerTestCase.php +++ b/tests/ControllerTestCase.php @@ -100,7 +100,8 @@ public function getBody() * * @param string $name * @param null|string $module - * @return PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet + * @return PHPUnit_Extensions_Database_DataSet_AbstractDataSet + * @throws Zend_Exception */ protected function getDataSet($name = 'default', $module = null) { @@ -108,8 +109,20 @@ protected function getDataSet($name = 'default', $module = null) if (isset($module) && !empty($module)) { $path = BASE_PATH.'/modules/'.$module.'/tests/databaseDataset/'.$name.'.xml'; } + $xmlDataSet = new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet($path); + $replacementDataSet = new PHPUnit_Extensions_Database_DataSet_ReplacementDataSet($xmlDataSet); + $configCore = new Zend_Config_Ini(CORE_CONFIG, 'global', true); + Zend_Registry::set('configCore', $configCore); + $coreVersion = UtilityComponent::getLatestModuleVersion('core'); + $result = preg_match('/^([0-9]+)\.([0-9]+)\.([0-9]+)$/i', $coreVersion, $matches); + if ($result !== 1) { + throw new Zend_Exception('Invalid core version string.'); + } + $replacementDataSet->addFullReplacement('##CORE_MAJOR_VERSION##', $matches[1]); + $replacementDataSet->addFullReplacement('##CORE_MINOR_VERSION##', $matches[2]); + $replacementDataSet->addFullReplacement('##CORE_PATCH_VERSION##', $matches[3]); - return new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet($path); + return $replacementDataSet; } /** @@ -140,99 +153,70 @@ protected function loadData($modelName, $file = null, $module = '') /** Initialize modules. */ private function _initModule() { - $router = Zend_Controller_Front::getInstance()->getRouter(); - // Init Modules $frontController = Zend_Controller_Front::getInstance(); $frontController->addControllerDirectory(BASE_PATH.'/core/controllers'); - if (isset($this->enabledModules) || (isset($_POST['enabledModules']) || isset($_GET['enabledModules']))) { - if (isset($this->enabledModules)) { - $paramsTestingModules = $this->enabledModules; - } elseif (isset($_POST['enabledModules'])) { - $paramsTestingModules = explode(';', $_POST['enabledModules']); - } else { - $paramsTestingModules = explode(';', $_GET['enabledModules']); - } - $modules = array(); - foreach ($paramsTestingModules as $p) { - $modules[$p] = 1; - if (file_exists(BASE_PATH.'/modules/'.$p.'/constant/module.php')) { - require_once BASE_PATH.'/modules/'.$p.'/constant/module.php'; - } - if (file_exists(BASE_PATH.'/privateModules/'.$p.'/constant/module.php')) { - require_once BASE_PATH.'/privateModules/'.$p.'/constant/module.php'; - } - } - } else { - $modules = array(); - } - // routes modules - $listeModule = array(); - $apiModules = array(); - foreach ($modules as $key => $module) { - if ($module == 1 && file_exists(BASE_PATH.'/modules/'.$key)) { - $listeModule[] = $key; - // get web API controller directories and web API module names for enabled modules - if (file_exists(BASE_PATH.'/modules/'.$key.'/controllers/api')) { - $frontController->addControllerDirectory( - BASE_PATH.'/modules/'.$key.'/controllers/api', - 'api'.$key - ); - $apiModules[] = $key; - } - } + require_once BASE_PATH.'/core/ApiController.php'; + $frontController->addControllerDirectory(BASE_PATH.'/core/controllers/api', 'rest'); + + $router = $frontController->getRouter(); + $router->addRoute('api-core', new Zend_Rest_Route($frontController, array(), array('rest'))); + + $enabledModules = array(); + + if (isset($this->enabledModules)) { + $enabledModules = $this->enabledModules; + } elseif (isset($_POST['enabledModules'])) { + $enabledModules = explode(';', $_POST['enabledModules']); + } elseif (isset($_GET['enabledModules'])) { + $enabledModules = explode(';', $_GET['enabledModules']); } /** @var UtilityComponent $utilityComponent */ $utilityComponent = MidasLoader::loadComponent('Utility'); - require_once BASE_PATH.'/core/ApiController.php'; - $frontController->addControllerDirectory(BASE_PATH.'/core/controllers/api', 'rest'); - // add RESTful route for web APIs - $restRoute = new Zend_Rest_Route($frontController, array(), array('rest')); - // add regular route for apikey configuration page - $router->addRoute( - 'rest-apikey', - new Zend_Controller_Router_Route('/apikey/:action/', array('module' => 'rest', 'controller' => 'apikey')) - ); - $router->addRoute('api-core', $restRoute); - foreach ($listeModule as $m) { - $route = $m; - $nameModule = $m; - $router->addRoute( - $nameModule.'-1', - new Zend_Controller_Router_Route( - ''.$route.'/:controller/:action/*', array('module' => $nameModule) - ) - ); - $router->addRoute( - $nameModule.'-2', - new Zend_Controller_Router_Route( - ''.$route.'/:controller/', - array('module' => $nameModule, 'action' => 'index') - ) - ); - $router->addRoute( - $nameModule.'-3', - new Zend_Controller_Router_Route( - ''.$route.'/', - array('module' => $nameModule, 'controller' => 'index', 'action' => 'index') - ) - ); - $frontController->addControllerDirectory(BASE_PATH.'/modules/'.$route.'/controllers', $nameModule); - if (file_exists(BASE_PATH.'/modules/'.$route.'/AppController.php')) { - require_once BASE_PATH.'/modules/'.$route.'/AppController.php'; + /** @var ModuleModel $moduleModel */ + $moduleModel = MidasLoader::loadModel('Module'); + + $enabledApiModules = array(); + + /** @var string $enabledModule */ + foreach ($enabledModules as $enabledModule) { + $frontController->addControllerDirectory(BASE_PATH.'/modules/'.$enabledModule.'/controllers', $enabledModule); + + if (file_exists(BASE_PATH.'/modules/'.$enabledModule.'/constant/module.php')) { + require_once BASE_PATH.'/modules/'.$enabledModule.'/constant/module.php'; } - if (file_exists(BASE_PATH.'/modules/'.$route.'/models/AppDao.php')) { - require_once BASE_PATH.'/modules/'.$route.'/models/AppDao.php'; + + if (file_exists(BASE_PATH.'/modules/'.$enabledModule.'/AppController.php')) { + require_once BASE_PATH.'/modules/'.$enabledModule.'/AppController.php'; + } + + if (file_exists(BASE_PATH.'/modules/'.$enabledModule.'/models/AppDao.php')) { + require_once BASE_PATH.'/modules/'.$enabledModule.'/models/AppDao.php'; } - if (file_exists(BASE_PATH.'/modules/'.$route.'/models/AppModel.php')) { - require_once BASE_PATH.'/modules/'.$route.'/models/AppModel.php'; + + if (file_exists(BASE_PATH.'/modules/'.$enabledModule.'/models/AppModel.php')) { + require_once BASE_PATH.'/modules/'.$enabledModule.'/models/AppModel.php'; } - $utilityComponent->installModule($m); + + if (file_exists(BASE_PATH.'/modules/'.$enabledModule.'/controllers/api')) { + $frontController->addControllerDirectory(BASE_PATH.'/modules/'.$enabledModule.'/controllers/api', 'api'.$enabledModule); + $enabledApiModules[] = $enabledModule; + } + + $router->addRoute($enabledModule.'-1', new Zend_Controller_Router_Route($enabledModule.'/:controller/:action/*', array('module' => $enabledModule))); + $router->addRoute($enabledModule.'-2', new Zend_Controller_Router_Route($enabledModule.'/:controller/', array('module' => $enabledModule, 'action' => 'index'))); + $router->addRoute($enabledModule.'-3', new Zend_Controller_Router_Route($enabledModule.'/', array('module' => $enabledModule, 'controller' => 'index', 'action' => 'index'))); + + $utilityComponent->installModule($enabledModule); + $moduleDao = $moduleModel->getByName($enabledModule); + $moduleDao->setEnabled(1); + $moduleModel->save($moduleDao); } - Zend_Registry::set('modulesEnable', $listeModule); - Zend_Registry::set('modulesHaveApi', $apiModules); + + Zend_Registry::set('modulesEnable', $enabledModules); + Zend_Registry::set('modulesHaveApi', $enabledApiModules); } /** Register plugins and helpers for the REST controller. */ @@ -339,6 +323,7 @@ public function appBootstrap() * * @param string|array $files * @param null|string $module + * @throws Zend_Exception */ public function setupDatabase($files, $module = null) { @@ -352,16 +337,34 @@ public function setupDatabase($files, $module = null) if (isset($module)) { $path = BASE_PATH.'/modules/'.$module.'/tests/databaseDataset/'.$f.'.xml'; } - $databaseFixture = new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet($path); - $databaseTester->setupDatabase($databaseFixture); + $xmlDataSet = new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet($path); + $replacementDataSet = new PHPUnit_Extensions_Database_DataSet_ReplacementDataSet($xmlDataSet); + $coreVersion = UtilityComponent::getLatestModuleVersion('core'); + $result = preg_match('/^([0-9]+)\.([0-9]+)\.([0-9]+)$/i', $coreVersion, $matches); + if ($result !== 1) { + throw new Zend_Exception('Invalid core version string.'); + } + $replacementDataSet->addFullReplacement('##CORE_MAJOR_VERSION##', $matches[1]); + $replacementDataSet->addFullReplacement('##CORE_MINOR_VERSION##', $matches[2]); + $replacementDataSet->addFullReplacement('##CORE_PATCH_VERSION##', $matches[3]); + $databaseTester->setupDatabase($replacementDataSet); } } else { $path = BASE_PATH.'/core/tests/databaseDataset/'.$files.'.xml'; if (isset($module)) { $path = BASE_PATH.'/modules/'.$module.'/tests/databaseDataset/'.$files.'.xml'; } - $databaseFixture = new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet($path); - $databaseTester->setupDatabase($databaseFixture); + $xmlDataSet = new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet($path); + $replacementDataSet = new PHPUnit_Extensions_Database_DataSet_ReplacementDataSet($xmlDataSet); + $coreVersion = UtilityComponent::getLatestModuleVersion('core'); + $result = preg_match('/^([0-9]+)\.([0-9]+)\.([0-9]+)$/i', $coreVersion, $matches); + if ($result !== 1) { + throw new Zend_Exception('Invalid core version string.'); + } + $replacementDataSet->addFullReplacement('##CORE_MAJOR_VERSION##', $matches[1]); + $replacementDataSet->addFullReplacement('##CORE_MINOR_VERSION##', $matches[2]); + $replacementDataSet->addFullReplacement('##CORE_PATCH_VERSION##', $matches[3]); + $databaseTester->setupDatabase($replacementDataSet); } if ($configDatabase->database->adapter == 'PDO_PGSQL') { diff --git a/tests/DatabaseSetup.php b/tests/DatabaseSetup.php index 2bb9e08d6..5abc331a9 100644 --- a/tests/DatabaseSetup.php +++ b/tests/DatabaseSetup.php @@ -132,46 +132,40 @@ function dropTables($db, $dbType) */ function installCore($db, $dbType, $utilityComponent) { + if ($dbType !== 'mysql' && $dbType !== 'pgsql' && $dbType !== 'sqlite') { + throw new Zend_Exception('Unknown database type: '.$dbType); + } + require_once BASE_PATH.'/core/controllers/components/UpgradeComponent.php'; $upgradeComponent = new UpgradeComponent(); $upgradeComponent->dir = BASE_PATH.'/core/database/'.$dbType; $upgradeComponent->init = true; $newestVersion = $upgradeComponent->getNewestVersion(true); - $sqlFile = BASE_PATH.'/core/database/'.$dbType.'/'.$newestVersion.'.sql'; - if (!isset($sqlFile) || !file_exists($sqlFile)) { + + if (!file_exists($sqlFile)) { throw new Zend_Exception('Unable to find SQL file: '.$sqlFile); } - switch ($dbType) { - case 'mysql': - $utilityComponent->run_sql_from_file($db, $sqlFile); - $upgradeDbType = 'PDO_MYSQL'; - break; - case 'pgsql': - $utilityComponent->run_sql_from_file($db, $sqlFile); - $upgradeDbType = 'PDO_PGSQL'; - break; - case 'sqlite': - $utilityComponent->run_sql_from_file($db, $sqlFile); - $upgradeDbType = 'PDO_SQLITE'; - break; - default: - throw new Zend_Exception('Unknown database type: '.$dbType); - break; - } + $utilityComponent->run_sql_from_file($db, $sqlFile); + + Zend_Registry::set('models', array()); + + $configCore = new Zend_Config_Ini(BASE_PATH.'/core/configs/core.ini', 'global'); - $options = array('allowModifications' => true); - $databaseConfig = new Zend_Config_Ini(BASE_PATH.'/tests/configs/lock.'.$dbType.'.ini', null, $options); - $databaseConfig->testing->version = $newestVersion; - $writer = new Zend_Config_Writer_Ini(); - $writer->setConfig($databaseConfig); - $writer->setFilename(BASE_PATH.'/tests/configs/lock.'.$dbType.'.ini'); - $writer->write(); + /** @var ModuleModel $moduleModel */ + $moduleModel = MidasLoader::loadModel('Module'); + /** @var ModuleDao $moduleDao */ + $moduleDao = MidasLoader::newDao('ModuleDao'); + $moduleDao->setName('core'); + $moduleDao->setUuid(str_replace('-', '', $configCore->get('uuid'))); + $moduleDao->setCurrentVersion($newestVersion); + $moduleDao->setEnabled(1); + $moduleModel->save($moduleDao); - $upgradeComponent->initUpgrade('core', $db, $upgradeDbType); - $upgradeComponent->upgrade(str_replace('.sql', '', basename($sqlFile)), true /* true for testing */); + $upgradeComponent->initUpgrade('core', $db, 'PDO_'.strtoupper($dbType)); + $upgradeComponent->upgrade($newestVersion, true /* true for testing */); } /** Create default asset store. */ diff --git a/tests/DatabaseTestCase.php b/tests/DatabaseTestCase.php index 8b4247d6a..9e63c470f 100644 --- a/tests/DatabaseTestCase.php +++ b/tests/DatabaseTestCase.php @@ -97,14 +97,66 @@ public function tearDown() public function appBootstrap() { $this->application = new Zend_Application(APPLICATION_ENV, CORE_CONFIG); + $this->_initModule(); $this->application->bootstrap(); } + /** Initialize modules. */ + private function _initModule() + { + $frontController = Zend_Controller_Front::getInstance(); + $frontController->addControllerDirectory(BASE_PATH.'/core/controllers'); + $router = $frontController->getRouter(); + $enabledModules = array(); + + if (isset($this->enabledModules)) { + $enabledModules = $this->enabledModules; + } + + /** @var UtilityComponent $utilityComponent */ + $utilityComponent = MidasLoader::loadComponent('Utility'); + + /** @var ModuleModel $moduleModel */ + $moduleModel = MidasLoader::loadModel('Module'); + + foreach ($enabledModules as $enabledModule) { + $frontController->addControllerDirectory(BASE_PATH.'/modules/'.$enabledModule.'/controllers', $enabledModule); + + if (file_exists(BASE_PATH.'/modules/'.$enabledModule.'/constant/module.php')) { + require_once BASE_PATH.'/modules/'.$enabledModule.'/constant/module.php'; + } + + if (file_exists(BASE_PATH.'/modules/'.$enabledModule.'/AppController.php')) { + require_once BASE_PATH.'/modules/'.$enabledModule.'/AppController.php'; + } + + if (file_exists(BASE_PATH.'/modules/'.$enabledModule.'/models/AppDao.php')) { + require_once BASE_PATH.'/modules/'.$enabledModule.'/models/AppDao.php'; + } + + if (file_exists(BASE_PATH.'/modules/'.$enabledModule.'/models/AppModel.php')) { + require_once BASE_PATH.'/modules/'.$enabledModule.'/models/AppModel.php'; + } + + $router->addRoute($enabledModule.'-1', new Zend_Controller_Router_Route($enabledModule.'/:controller/:action/*', array('module' => $enabledModule))); + $router->addRoute($enabledModule.'-2', new Zend_Controller_Router_Route($enabledModule.'/:controller/', array('module' => $enabledModule, 'action' => 'index'))); + $router->addRoute($enabledModule.'-3', new Zend_Controller_Router_Route($enabledModule.'/', array('module' => $enabledModule, 'controller' => 'index', 'action' => 'index'))); + + $utilityComponent->installModule($enabledModule); + $moduleDao = $moduleModel->getByName($enabledModule); + $moduleDao->setEnabled(1); + $moduleModel->save($moduleDao); + } + + Zend_Registry::set('modulesEnable', $enabledModules); + } + /** * Setup the database using XML files. * * @param string|array $files * @param null|string $module + * @throws Zend_Exception */ public function setupDatabase($files, $module = null) { @@ -118,16 +170,37 @@ public function setupDatabase($files, $module = null) if (isset($module)) { $path = BASE_PATH.'/modules/'.$module.'/tests/databaseDataset/'.$f.'.xml'; } - $databaseFixture = new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet($path); - $databaseTester->setupDatabase($databaseFixture); + $xmlDataSet = new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet($path); + $replacementDataSet = new PHPUnit_Extensions_Database_DataSet_ReplacementDataSet($xmlDataSet); + $configCore = new Zend_Config_Ini(CORE_CONFIG, 'global', true); + Zend_Registry::set('configCore', $configCore); + $coreVersion = UtilityComponent::getLatestModuleVersion('core'); + $result = preg_match('/^([0-9]+)\.([0-9]+)\.([0-9]+)$/i', $coreVersion, $matches); + if ($result !== 1) { + throw new Zend_Exception('Invalid core version string.'); + } + $replacementDataSet->addFullReplacement('##CORE_MAJOR_VERSION##', $matches[1]); + $replacementDataSet->addFullReplacement('##CORE_MINOR_VERSION##', $matches[2]); + $replacementDataSet->addFullReplacement('##CORE_PATCH_VERSION##', $matches[3]); + $databaseTester->setupDatabase($replacementDataSet); } } else { $path = BASE_PATH.'/core/tests/databaseDataset/'.$files.'.xml'; if (isset($module)) { $path = BASE_PATH.'/modules/'.$module.'/tests/databaseDataset/'.$files.'.xml'; } - $databaseFixture = new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet($path); - $databaseTester->setupDatabase($databaseFixture); + $xmlDataSet = new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet($path); + $replacementDataSet = new PHPUnit_Extensions_Database_DataSet_ReplacementDataSet($xmlDataSet); + $coreVersion = UtilityComponent::getLatestModuleVersion('core'); + $result = preg_match('/^([0-9]+)\.([0-9]+)\.([0-9]+)$/i', $coreVersion, $matches); + if ($result !== 1) { + throw new Zend_Exception('Invalid core version string.'); + } + $replacementDataSet->addFullReplacement('##CORE_MAJOR_VERSION##', $matches[1]); + $replacementDataSet->addFullReplacement('##CORE_MINOR_VERSION##', $matches[2]); + $replacementDataSet->addFullReplacement('##CORE_PATCH_VERSION##', $matches[3]); + + $databaseTester->setupDatabase($replacementDataSet); } if ($configDatabase->database->adapter == 'PDO_PGSQL') { @@ -186,7 +259,8 @@ protected function getConnection() * * @param string $name * @param null|string $module - * @return PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet + * @return PHPUnit_Extensions_Database_DataSet_AbstractDataSet + * @throws Zend_Exception */ protected function getDataSet($name = 'default', $module = null) { @@ -194,8 +268,18 @@ protected function getDataSet($name = 'default', $module = null) if (isset($module) && !empty($module)) { $path = BASE_PATH.'/modules/'.$module.'/tests/databaseDataset/'.$name.'.xml'; } + $xmlDataSet = new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet($path); + $replacementDataSet = new PHPUnit_Extensions_Database_DataSet_ReplacementDataSet($xmlDataSet); + $coreVersion = UtilityComponent::getLatestModuleVersion('core'); + $result = preg_match('/^([0-9]+)\.([0-9]+)\.([0-9]+)$/i', $coreVersion, $matches); + if ($result !== 1) { + throw new Zend_Exception('Invalid core version string.'); + } + $replacementDataSet->addFullReplacement('##CORE_MAJOR_VERSION##', $matches[1]); + $replacementDataSet->addFullReplacement('##CORE_MINOR_VERSION##', $matches[2]); + $replacementDataSet->addFullReplacement('##CORE_PATCH_VERSION##', $matches[3]); - return $this->createFlatXmlDataSet($path); + return $replacementDataSet; } /** diff --git a/tests/TestsBootstrap.php b/tests/TestsBootstrap.php index 733fe80e6..7a59606d0 100644 --- a/tests/TestsBootstrap.php +++ b/tests/TestsBootstrap.php @@ -36,6 +36,9 @@ Zend_Session::$_unitTestEnabled = true; Zend_Session::start(); +$configCore = new Zend_Config_Ini(CORE_CONFIG, 'global', true); +Zend_Registry::set('configCore', $configCore); + require_once 'ControllerTestCase.php'; require_once 'DatabaseTestCase.php'; @@ -86,15 +89,17 @@ Zend_Db_Table::setDefaultAdapter($db); Zend_Registry::set('dbAdapter', $db); Zend_Registry::set('configDatabase', $configDatabase); +Zend_Registry::set('models', array()); require_once BASE_PATH.'/core/controllers/components/UpgradeComponent.php'; $upgradeComponent = new UpgradeComponent(); $db = Zend_Registry::get('dbAdapter'); $dbtype = Zend_Registry::get('configDatabase')->database->adapter; - $upgradeComponent->initUpgrade('core', $db, $dbtype); -$version = Zend_Registry::get('configDatabase')->version; -if (!isset($version)) { + +require_once BASE_PATH.'/core/controllers/components/UtilityComponent.php'; +$version = UtilityComponent::getLatestModuleVersion('core'); +if ($version === false) { if (Zend_Registry::get('configDatabase')->database->adapter === 'PDO_MYSQL' ) { $type = 'mysql'; diff --git a/tests/ci/travis/mysql.ini b/tests/ci/travis/mysql.ini index f74b8012d..721134572 100644 --- a/tests/ci/travis/mysql.ini +++ b/tests/ci/travis/mysql.ini @@ -8,4 +8,3 @@ database.params.unix_socket = "" database.params.dbname = "midas_test" database.params.username = "root" database.params.password = "" -version = "" diff --git a/tests/ci/travis/pgsql.ini b/tests/ci/travis/pgsql.ini index be7d298a9..1c8e727e9 100644 --- a/tests/ci/travis/pgsql.ini +++ b/tests/ci/travis/pgsql.ini @@ -8,4 +8,3 @@ database.params.unix_socket = database.params.dbname = "midas_test" database.params.username = "postgres" database.params.password = "" -version = "" diff --git a/tests/ci/travis/sqlite.ini b/tests/ci/travis/sqlite.ini index f04287436..6513e25c9 100644 --- a/tests/ci/travis/sqlite.ini +++ b/tests/ci/travis/sqlite.ini @@ -8,4 +8,3 @@ database.params.unix_socket = "" database.params.dbname = ${TRAVIS_BUILD_DIR}/midas_test.db database.params.username = "" database.params.password = "" -version = "" diff --git a/tests/ci/vagrant/mysql.ini b/tests/ci/vagrant/mysql.ini index 08e619c85..e7f4cd3e3 100644 --- a/tests/ci/vagrant/mysql.ini +++ b/tests/ci/vagrant/mysql.ini @@ -8,4 +8,3 @@ database.params.unix_socket = "" database.params.dbname = "midas_test" database.params.username = "vagrant" database.params.password = "vagrant" -version = "" diff --git a/tests/ci/vagrant/pgsql.ini b/tests/ci/vagrant/pgsql.ini index 506cfc340..3e936227f 100644 --- a/tests/ci/vagrant/pgsql.ini +++ b/tests/ci/vagrant/pgsql.ini @@ -8,4 +8,3 @@ database.params.unix_socket = database.params.dbname = "midas_test" database.params.username = "vagrant" database.params.password = "vagrant" -version = "" diff --git a/tests/ci/vagrant/sqlite.ini b/tests/ci/vagrant/sqlite.ini index 6fc648ecc..469692915 100644 --- a/tests/ci/vagrant/sqlite.ini +++ b/tests/ci/vagrant/sqlite.ini @@ -8,4 +8,3 @@ database.params.unix_socket = "" database.params.dbname = "/vagrant/data/midas_test.db" database.params.username = "" database.params.password = "" -version = ""