3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
35 class CRM_Upgrade_Form
extends CRM_Core_Form
{
36 CONST QUEUE_NAME
= 'CRM_Upgrade';
39 * Minimum size of MySQL's thread_stack option
41 * @see install/index.php MINIMUM_THREAD_STACK
43 const MINIMUM_THREAD_STACK
= 192;
47 // note latestVersion is legacy code, and
48 // only used for 2.0 -> 2.1 upgrade
49 public $latestVersion;
52 * Upgrade for multilingual
57 public $multilingual = FALSE;
60 * locales available for multilingual upgrade
68 * number to string mapper
73 static $_numberMap = array(
87 * Constructor for the basic form page
89 * We should not use QuickForm directly. This class provides a lot
90 * of default convenient functions, rules and buttons
92 * @param object $state State associated with this form
93 * @param \const|\enum $action The mode the form is operating in (None/Create/View/Update/Delete)
94 * @param string $method The type of http method used (GET/POST)
95 * @param string $name The name of the form if different from class name
97 * @return \CRM_Core_Form
101 * @param null|object $state
102 * @param const|enum|int $action
103 * @param string $method
104 * @param null|string $name
106 function __construct($state = NULL,
107 $action = CRM_Core_Action
::NONE
,
111 $this->_config
= CRM_Core_Config
::singleton();
113 // this->latestVersion is legacy code, only used for 2.0 -> 2.1 upgrade
114 // latest ver in 2.1 series
115 $this->latestVersion
= '2.1.6';
117 $domain = new CRM_Core_DAO_Domain();
120 $this->multilingual
= (bool) $domain->locales
;
121 $this->locales
= explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $domain->locales
);
123 $smarty = CRM_Core_Smarty
::singleton();
124 $smarty->compile_dir
= $this->_config
->templateCompileDir
;
125 $smarty->assign('multilingual', $this->multilingual
);
126 $smarty->assign('locales', $this->locales
);
128 // we didn't call CRM_Core_BAO_ConfigSetting::retrieve(), so we need to set $dbLocale by hand
129 if ($this->multilingual
) {
131 $dbLocale = "_{$this->_config->lcMessages}";
134 parent
::__construct($state, $action, $method, $name);
142 static function &incrementalPhpObject($version) {
143 static $incrementalPhpObject = array();
145 $versionParts = explode('.', $version);
146 $versionName = self
::$_numberMap[$versionParts[0]] . self
::$_numberMap[$versionParts[1]];
148 if (!array_key_exists($versionName, $incrementalPhpObject)) {
149 $className = "CRM_Upgrade_Incremental_php_{$versionName}";
150 $incrementalPhpObject[$versionName] = new $className();
152 return $incrementalPhpObject[$versionName];
161 function checkVersionRelease($version, $release) {
162 $versionParts = explode('.', $version);
163 if ($versionParts[2] == $release) {
170 * @param $constraints
174 function checkSQLConstraints(&$constraints) {
176 foreach ($constraints as $constraint) {
177 if ($this->checkSQLConstraint($constraint)) {
183 return array($pass, $fail);
192 function checkSQLConstraint($constraint) {
193 // check constraint here
199 * @param bool $isQueryString
201 function source($fileName, $isQueryString = FALSE) {
203 CRM_Utils_File
::sourceSQLFile($this->_config
->dsn
,
204 $fileName, NULL, $isQueryString
208 function preProcess() {
209 CRM_Utils_System
::setTitle($this->getTitle());
210 if (!$this->verifyPreDBState($errorMessage)) {
211 if (!isset($errorMessage)) {
212 $errorMessage = 'pre-condition failed for current upgrade step';
214 CRM_Core_Error
::fatal($errorMessage);
216 $this->assign('recentlyViewed', FALSE);
219 function buildQuickForm() {
220 $this->addDefaultButtons($this->getButtonTitle(),
228 * getter function for title. Should be over-ridden by derived class
236 function getTitle() {
237 return ts('Title not Set');
243 function getFieldsetTitle() {
250 function getButtonTitle() {
251 return ts('Continue');
255 * Use the form name to create the tpl file name
263 function getTemplateFileName() {
264 $this->assign('title',
265 $this->getFieldsetTitle()
267 $this->assign('message',
268 $this->getTemplateMessage()
270 return 'CRM/Upgrade/Base.tpl';
273 function postProcess() {
276 if (!$this->verifyPostDBState($errorMessage)) {
277 if (!isset($errorMessage)) {
278 $errorMessage = 'post-condition failed for current upgrade step';
280 CRM_Core_Error
::fatal($errorMessage);
289 function runQuery($query) {
290 return CRM_Core_DAO
::executeQuery($query,
291 CRM_Core_DAO
::$_nullArray
300 function setVersion($version) {
301 $this->logVersion($version);
304 UPDATE civicrm_domain
305 SET version = '$version'
307 return $this->runQuery($query);
315 function logVersion($newVersion) {
317 $oldVersion = CRM_Core_BAO_Domain
::version();
319 $session = CRM_Core_Session
::singleton();
321 'entity_table' => 'civicrm_domain',
323 'data' => "upgrade:{$oldVersion}->{$newVersion}",
324 // lets skip 'modified_id' for now, as it causes FK issues And
325 // is not very important for now.
326 'modified_date' => date('YmdHis'),
328 CRM_Core_BAO_Log
::add($logParams);
340 function checkVersion($version) {
341 $domainID = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain',
345 return $domainID ?
TRUE : FALSE;
352 function getRevisionSequence() {
354 $sqlDir = implode(DIRECTORY_SEPARATOR
,
355 array(dirname(__FILE__
), 'Incremental', 'sql')
357 $sqlFiles = scandir($sqlDir);
359 $sqlFilePattern = '/^((\d{1,2}\.\d{1,2})\.(\d{1,2}\.)?(\d{1,2}|\w{4,7}))\.(my)?sql(\.tpl)?$/i';
360 foreach ($sqlFiles as $file) {
361 if (preg_match($sqlFilePattern, $file, $matches)) {
362 if ($matches[2] == '4.0') {
363 CRM_Core_Error
::fatal(ts("4.0.x upgrade files shouldn't exist. Contact Lobo to discuss this. This is related to the issue CRM-7731."));
365 if (!in_array($matches[1], $revList)) {
366 $revList[] = $matches[1];
373 '2.1.0', '2.2.beta2', '2.2.beta1', '2.2.alpha1', */
375 /* '2.2.alpha3', '2.2.0', '2.2.2', '2.1.alpha1', '2.1.3'); */
378 usort($revList, 'version_compare');
388 static function getRevisionPart($rev, $index = 1) {
389 $revPattern = '/^((\d{1,2})\.\d{1,2})\.(\d{1,2}|\w{4,7})?$/i';
390 preg_match($revPattern, $rev, $matches);
392 return array_key_exists($index, $matches) ?
$matches[$index] : NULL;
401 function processLocales($tplFile, $rev) {
402 $smarty = CRM_Core_Smarty
::singleton();
403 $smarty->assign('domainID', CRM_Core_Config
::domainID());
405 $this->source($smarty->fetch($tplFile), TRUE);
407 if ($this->multilingual
) {
408 CRM_Core_I18n_Schema
::rebuildMultilingualSchema($this->locales
, $rev);
410 return $this->multilingual
;
416 function setSchemaStructureTables($rev) {
417 if ($this->multilingual
) {
418 CRM_Core_I18n_Schema
::schemaStructureTables($rev, TRUE);
427 function processSQL($rev) {
428 $sqlFile = implode(DIRECTORY_SEPARATOR
,
430 dirname(__FILE__
), 'Incremental',
431 'sql', $rev . '.mysql',
434 $tplFile = "$sqlFile.tpl";
436 if (file_exists($tplFile)) {
437 $this->processLocales($tplFile, $rev);
440 if (!file_exists($sqlFile)) {
441 CRM_Core_Error
::fatal("sqlfile - $rev.mysql not found.");
443 $this->source($sqlFile);
448 * Determine the start and end version of the upgrade process
450 * @return array(0=>$currentVer, 1=>$latestVer)
452 function getUpgradeVersions() {
453 $latestVer = CRM_Utils_System
::version();
454 $currentVer = CRM_Core_BAO_Domain
::version(true);
456 CRM_Core_Error
::fatal(ts('Version information missing in civicrm database.'));
458 elseif (stripos($currentVer, 'upgrade')) {
459 CRM_Core_Error
::fatal(ts('Database check failed - the database looks to have been partially upgraded. You may want to reload the database with the backup and try the upgrade process again.'));
462 CRM_Core_Error
::fatal(ts('Version information missing in civicrm codebase.'));
465 // hack to make past ver compatible /w new incremental upgrade process
468 '2.2' => '2.2.alpha1',
469 '2.2.alph' => '2.2.alpha3',
470 // since 3.1.1 had domain.version set as 3.1.0
473 if (isset($convertVer[$currentVer])) {
474 $currentVer = $convertVer[$currentVer];
477 return array($currentVer, $latestVer);
481 * Determine if $currentVer can be upgraded to $latestVer
486 * @return mixed, a string error message or boolean 'false' if OK
488 function checkUpgradeableVersion($currentVer, $latestVer) {
490 // since version is suppose to be in valid format at this point, especially after conversion ($convertVer),
491 // lets do a pattern check -
492 if (!CRM_Utils_System
::isVersionFormatValid($currentVer)) {
493 $error = ts('Database is marked with invalid version format. You may want to investigate this before you proceed further.');
495 elseif (version_compare($currentVer, $latestVer) > 0) {
496 // DB version number is higher than codebase being upgraded to. This is unexpected condition-fatal error.
497 $error = ts('Your database is marked with an unexpected version number: %1. The automated upgrade to version %2 can not be run - and the %2 codebase may not be compatible with your database state. You will need to determine the correct version corresponding to your current database state. You may want to revert to the codebase you were using prior to beginning this upgrade until you resolve this problem.',
498 array(1 => $currentVer, 2 => $latestVer, 3 => $dbToolsLink)
501 elseif (version_compare($currentVer, $latestVer) == 0) {
502 $error = ts('Your database has already been upgraded to CiviCRM %1',
503 array(1 => $latestVer)
507 $phpVersion = phpversion();
508 $minPhpVersion = '5.3.3';
509 if (version_compare($phpVersion, $minPhpVersion) < 0) {
510 $error = ts('CiviCRM %3 requires PHP version %1 (or newer), but the current system uses %2 ',
518 // check for mysql trigger privileges
519 if (!CRM_Core_DAO
::checkTriggerViewPermission(FALSE, TRUE)) {
520 $error = ts('CiviCRM %1 requires MySQL trigger privileges.',
521 array(1 => $latestVer));
524 if (CRM_Core_DAO
::getGlobalSetting('thread_stack', 0) < (1024*self
::MINIMUM_THREAD_STACK
)) {
525 $error = ts('CiviCRM %1 requires MySQL thread stack >= %2k', array(
527 2 => self
::MINIMUM_THREAD_STACK
535 * Determine if $currentver already matches $latestVer
540 * @return mixed, a string error message or boolean 'false' if OK
542 function checkCurrentVersion($currentVer, $latestVer) {
545 // since version is suppose to be in valid format at this point, especially after conversion ($convertVer),
546 // lets do a pattern check -
547 if (!CRM_Utils_System
::isVersionFormatValid($currentVer)) {
548 $error = ts('Database is marked with invalid version format. You may want to investigate this before you proceed further.');
550 elseif (version_compare($currentVer, $latestVer) != 0) {
551 $error = ts('Your database is not configured for version %1',
552 array(1 => $latestVer)
559 * Fill the queue with upgrade tasks
561 * @param $currentVer string, the original revision
562 * @param $latestVer string, the target (final) revision
563 * @param $postUpgradeMessageFile string, path of a modifiable file which lists the post-upgrade messages
567 static function buildQueue($currentVer, $latestVer, $postUpgradeMessageFile) {
568 $upgrade = new CRM_Upgrade_Form();
570 // hack to make 4.0.x (D7,J1.6) codebase go through 3.4.x (d6, J1.5) upgrade files,
571 // since schema wise they are same
572 if (CRM_Upgrade_Form
::getRevisionPart($currentVer) == '4.0') {
573 $currentVer = str_replace('4.0.', '3.4.', $currentVer);
576 // Ensure that queue can be created
577 if (!CRM_Queue_BAO_QueueItem
::findCreateTable()) {
578 CRM_Core_Error
::fatal(ts('Failed to find or create queueing table'));
580 $queue = CRM_Queue_Service
::singleton()->create(array(
581 'name' => self
::QUEUE_NAME
,
586 $revisions = $upgrade->getRevisionSequence();
587 foreach ($revisions as $rev) {
588 // proceed only if $currentVer < $rev
589 if (version_compare($currentVer, $rev) < 0) {
590 $beginTask = new CRM_Queue_Task(
592 array('CRM_Upgrade_Form', 'doIncrementalUpgradeStart'),
595 "Begin Upgrade to $rev"
597 $queue->createItem($beginTask);
599 $task = new CRM_Queue_Task(
601 array('CRM_Upgrade_Form', 'doIncrementalUpgradeStep'),
603 array($rev, $currentVer, $latestVer, $postUpgradeMessageFile),
606 $queue->createItem($task);
608 $task = new CRM_Queue_Task(
610 array('CRM_Upgrade_Form', 'doIncrementalUpgradeFinish'),
612 array($rev, $currentVer, $latestVer, $postUpgradeMessageFile),
613 "Finish Upgrade DB to $rev"
615 $queue->createItem($task);
623 * Perform an incremental version update
625 * @param CRM_Queue_TaskContext $ctx
626 * @param $rev string, the target (intermediate) revision e.g '3.2.alpha1'
629 * @internal param string $currentVer , the original revision
630 * @internal param string $latestVer , the target (final) revision
631 * @internal param string $postUpgradeMessageFile , path of a modifiable file which lists the post-upgrade messages
633 static function doIncrementalUpgradeStart(CRM_Queue_TaskContext
$ctx, $rev) {
634 $upgrade = new CRM_Upgrade_Form();
636 // as soon as we start doing anything we append ".upgrade" to version.
637 // this also helps detect any partial upgrade issues
638 $upgrade->setVersion($rev . '.upgrade');
644 * Perform an incremental version update
646 * @param CRM_Queue_TaskContext $ctx
647 * @param $rev string, the target (intermediate) revision e.g '3.2.alpha1'
648 * @param $currentVer string, the original revision
649 * @param $latestVer string, the target (final) revision
650 * @param $postUpgradeMessageFile string, path of a modifiable file which lists the post-upgrade messages
654 static function doIncrementalUpgradeStep(CRM_Queue_TaskContext
$ctx, $rev, $currentVer, $latestVer, $postUpgradeMessageFile) {
655 $upgrade = new CRM_Upgrade_Form();
657 $phpFunctionName = 'upgrade_' . str_replace('.', '_', $rev);
659 // follow old upgrade process for all version
661 if (version_compare($rev, '3.2.alpha1') < 0) {
662 if (is_callable(array(
663 'CRM_Upgrade_Incremental_Legacy', $phpFunctionName))) {
664 call_user_func(array('CRM_Upgrade_Incremental_Legacy', $phpFunctionName), $rev);
667 $upgrade->processSQL($rev);
671 // new upgrade process from version
673 $versionObject = $upgrade->incrementalPhpObject($rev);
675 // pre-db check for major release.
676 if ($upgrade->checkVersionRelease($rev, 'alpha1')) {
677 if (!(is_callable(array(
678 $versionObject, 'verifyPreDBstate')))) {
679 CRM_Core_Error
::fatal("verifyPreDBstate method was not found for $rev");
683 if (!($versionObject->verifyPreDBstate($error))) {
684 if (!isset($error)) {
685 $error = "post-condition failed for current upgrade for $rev";
687 CRM_Core_Error
::fatal($error);
692 $upgrade->setSchemaStructureTables($rev);
694 if (is_callable(array(
695 $versionObject, $phpFunctionName))) {
696 $versionObject->$phpFunctionName($rev);
699 $upgrade->processSQL($rev);
702 // set post-upgrade-message if any
703 if (is_callable(array(
704 $versionObject, 'setPostUpgradeMessage'))) {
705 $postUpgradeMessage = file_get_contents($postUpgradeMessageFile);
706 $versionObject->setPostUpgradeMessage($postUpgradeMessage, $rev);
707 file_put_contents($postUpgradeMessageFile, $postUpgradeMessage);
709 $postUpgradeMessage = file_get_contents($postUpgradeMessageFile);
710 CRM_Upgrade_Incremental_Legacy
::setPostUpgradeMessage($postUpgradeMessage, $rev);
711 file_put_contents($postUpgradeMessageFile, $postUpgradeMessage);
719 * Perform an incremental version update
721 * @param CRM_Queue_TaskContext $ctx
722 * @param $rev string, the target (intermediate) revision e.g '3.2.alpha1'
723 * @param $currentVer string, the original revision
724 * @param $latestVer string, the target (final) revision
725 * @param $postUpgradeMessageFile string, path of a modifiable file which lists the post-upgrade messages
729 static function doIncrementalUpgradeFinish(CRM_Queue_TaskContext
$ctx, $rev, $currentVer, $latestVer, $postUpgradeMessageFile) {
730 $upgrade = new CRM_Upgrade_Form();
731 $upgrade->setVersion($rev);
732 CRM_Utils_System
::flushCache();
734 $config = CRM_Core_Config
::singleton();
735 $config->userSystem
->flush();
739 static function doFinish() {
740 $upgrade = new CRM_Upgrade_Form();
741 list($ignore, $latestVer) = $upgrade->getUpgradeVersions();
742 // Seems extraneous in context, but we'll preserve old behavior
743 $upgrade->setVersion($latestVer);
745 // lets rebuild the config array in case we've made a few changes in the
747 // this also helps us always store the latest version of civi in the DB
749 CRM_Core_BAO_ConfigSetting
::add($params);
751 // CRM-12804 comment-51411 : add any missing settings
752 // at the end of upgrade
753 CRM_Core_BAO_Setting
::updateSettingsFromMetaData();
755 // cleanup caches CRM-8739
756 $config = CRM_Core_Config
::singleton();
757 $config->cleanupCaches(1);
759 // Rebuild all triggers and re-enable logging if needed
760 $logging = new CRM_Logging_Schema();
761 $logging->fixSchemaDifferences();
765 * Compute any messages which should be displayed before upgrade
766 * by calling the 'setPreUpgradeMessage' on each incremental upgrade
769 * @param $preUpgradeMessage string, alterable
773 function setPreUpgradeMessage(&$preUpgradeMessage, $currentVer, $latestVer) {
774 CRM_Upgrade_Incremental_Legacy
::setPreUpgradeMessage($preUpgradeMessage, $currentVer, $latestVer);
776 // Scan through all php files and see if any file is interested in setting pre-upgrade-message
777 // based on $currentVer, $latestVer.
778 // Please note, at this point upgrade hasn't started executing queries.
779 $revisions = $this->getRevisionSequence();
780 foreach ($revisions as $rev) {
781 if (version_compare($currentVer, $rev) < 0 &&
782 version_compare($rev, '3.2.alpha1') > 0
784 $versionObject = $this->incrementalPhpObject($rev);
785 if (is_callable(array(
786 $versionObject, 'setPreUpgradeMessage'))) {
787 $versionObject->setPreUpgradeMessage($preUpgradeMessage, $rev, $currentVer);