3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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;
48 * Upgrade for multilingual
52 public $multilingual = FALSE;
55 * Locales available for multilingual upgrade
62 * Number to string mapper
66 static $_numberMap = array(
80 * Constructor for the basic form page
82 * We should not use QuickForm directly. This class provides a lot
83 * of default convenient functions, rules and buttons
85 * @param object $state
86 * State associated with this form.
87 * @param \const|\enum $action The mode the form is operating in (None/Create/View/Update/Delete)
88 * @param string $method
89 * The type of http method used (GET/POST).
91 * The name of the form if different from class name.
93 * @return \CRM_Core_Form
96 * @param null|object $state
97 * @param const|enum|int $action
98 * @param string $method
99 * @param null|string $name
101 function __construct(
103 $action = CRM_Core_Action
::NONE
,
107 $this->_config
= CRM_Core_Config
::singleton();
109 $domain = new CRM_Core_DAO_Domain();
112 $this->multilingual
= (bool) $domain->locales
;
113 $this->locales
= explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $domain->locales
);
115 $smarty = CRM_Core_Smarty
::singleton();
116 $smarty->compile_dir
= $this->_config
->templateCompileDir
;
117 $smarty->assign('multilingual', $this->multilingual
);
118 $smarty->assign('locales', $this->locales
);
120 // we didn't call CRM_Core_BAO_ConfigSetting::retrieve(), so we need to set $dbLocale by hand
121 if ($this->multilingual
) {
123 $dbLocale = "_{$this->_config->lcMessages}";
126 parent
::__construct($state, $action, $method, $name);
134 public static function &incrementalPhpObject($version) {
135 static $incrementalPhpObject = array();
137 $versionParts = explode('.', $version);
138 $versionName = self
::$_numberMap[$versionParts[0]] . self
::$_numberMap[$versionParts[1]];
140 if (!array_key_exists($versionName, $incrementalPhpObject)) {
141 $className = "CRM_Upgrade_Incremental_php_{$versionName}";
142 $incrementalPhpObject[$versionName] = new $className();
144 return $incrementalPhpObject[$versionName];
153 public function checkVersionRelease($version, $release) {
154 $versionParts = explode('.', $version);
155 if ($versionParts[2] == $release) {
162 * @param $constraints
166 public function checkSQLConstraints(&$constraints) {
168 foreach ($constraints as $constraint) {
169 if ($this->checkSQLConstraint($constraint)) {
175 return array($pass, $fail);
184 public function checkSQLConstraint($constraint) {
185 // check constraint here
190 * @param string $fileName
191 * @param bool $isQueryString
193 public function source($fileName, $isQueryString = FALSE) {
195 CRM_Utils_File
::sourceSQLFile($this->_config
->dsn
,
196 $fileName, NULL, $isQueryString
200 public function preProcess() {
201 CRM_Utils_System
::setTitle($this->getTitle());
202 if (!$this->verifyPreDBState($errorMessage)) {
203 if (!isset($errorMessage)) {
204 $errorMessage = 'pre-condition failed for current upgrade step';
206 CRM_Core_Error
::fatal($errorMessage);
208 $this->assign('recentlyViewed', FALSE);
211 public function buildQuickForm() {
212 $this->addDefaultButtons($this->getButtonTitle(),
220 * Getter function for title. Should be over-ridden by derived class
227 public function getTitle() {
228 return ts('Title not Set');
234 public function getFieldsetTitle() {
241 public function getButtonTitle() {
242 return ts('Continue');
246 * Use the form name to create the tpl file name
253 public function getTemplateFileName() {
254 $this->assign('title',
255 $this->getFieldsetTitle()
257 $this->assign('message',
258 $this->getTemplateMessage()
260 return 'CRM/Upgrade/Base.tpl';
263 public function postProcess() {
266 if (!$this->verifyPostDBState($errorMessage)) {
267 if (!isset($errorMessage)) {
268 $errorMessage = 'post-condition failed for current upgrade step';
270 CRM_Core_Error
::fatal($errorMessage);
279 public function runQuery($query) {
280 return CRM_Core_DAO
::executeQuery($query,
281 CRM_Core_DAO
::$_nullArray
290 public function setVersion($version) {
291 $this->logVersion($version);
294 UPDATE civicrm_domain
295 SET version = '$version'
297 return $this->runQuery($query);
305 public function logVersion($newVersion) {
307 $oldVersion = CRM_Core_BAO_Domain
::version();
309 $session = CRM_Core_Session
::singleton();
311 'entity_table' => 'civicrm_domain',
313 'data' => "upgrade:{$oldVersion}->{$newVersion}",
314 // lets skip 'modified_id' for now, as it causes FK issues And
315 // is not very important for now.
316 'modified_date' => date('YmdHis'),
318 CRM_Core_BAO_Log
::add($logParams);
330 public function checkVersion($version) {
331 $domainID = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain',
335 return $domainID ?
TRUE : FALSE;
342 public function getRevisionSequence() {
344 $sqlDir = implode(DIRECTORY_SEPARATOR
,
345 array(dirname(__FILE__
), 'Incremental', 'sql')
347 $sqlFiles = scandir($sqlDir);
349 $sqlFilePattern = '/^((\d{1,2}\.\d{1,2})\.(\d{1,2}\.)?(\d{1,2}|\w{4,7}))\.(my)?sql(\.tpl)?$/i';
350 foreach ($sqlFiles as $file) {
351 if (preg_match($sqlFilePattern, $file, $matches)) {
352 if ($matches[2] == '4.0') {
353 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."));
355 if (!in_array($matches[1], $revList)) {
356 $revList[] = $matches[1];
363 '2.1.0', '2.2.beta2', '2.2.beta1', '2.2.alpha1', */
365 /* '2.2.alpha3', '2.2.0', '2.2.2', '2.1.alpha1', '2.1.3'); */
367 usort($revList, 'version_compare');
377 public static function getRevisionPart($rev, $index = 1) {
378 $revPattern = '/^((\d{1,2})\.\d{1,2})\.(\d{1,2}|\w{4,7})?$/i';
379 preg_match($revPattern, $rev, $matches);
381 return array_key_exists($index, $matches) ?
$matches[$index] : NULL;
390 public function processLocales($tplFile, $rev) {
391 $smarty = CRM_Core_Smarty
::singleton();
392 $smarty->assign('domainID', CRM_Core_Config
::domainID());
394 $this->source($smarty->fetch($tplFile), TRUE);
396 if ($this->multilingual
) {
397 CRM_Core_I18n_Schema
::rebuildMultilingualSchema($this->locales
, $rev);
399 return $this->multilingual
;
405 public function setSchemaStructureTables($rev) {
406 if ($this->multilingual
) {
407 CRM_Core_I18n_Schema
::schemaStructureTables($rev, TRUE);
416 public function processSQL($rev) {
417 $sqlFile = implode(DIRECTORY_SEPARATOR
,
425 $tplFile = "$sqlFile.tpl";
427 if (file_exists($tplFile)) {
428 $this->processLocales($tplFile, $rev);
431 if (!file_exists($sqlFile)) {
432 CRM_Core_Error
::fatal("sqlfile - $rev.mysql not found.");
434 $this->source($sqlFile);
439 * Determine the start and end version of the upgrade process
441 * @return array(0=>$currentVer, 1=>$latestVer)
443 public function getUpgradeVersions() {
444 $latestVer = CRM_Utils_System
::version();
445 $currentVer = CRM_Core_BAO_Domain
::version(TRUE);
447 CRM_Core_Error
::fatal(ts('Version information missing in civicrm database.'));
449 elseif (stripos($currentVer, 'upgrade')) {
450 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.'));
453 CRM_Core_Error
::fatal(ts('Version information missing in civicrm codebase.'));
456 // hack to make past ver compatible /w new incremental upgrade process
459 '2.2' => '2.2.alpha1',
460 '2.2.alph' => '2.2.alpha3',
461 // since 3.1.1 had domain.version set as 3.1.0
464 if (isset($convertVer[$currentVer])) {
465 $currentVer = $convertVer[$currentVer];
468 return array($currentVer, $latestVer);
472 * Determine if $currentVer can be upgraded to $latestVer
477 * @return mixed, a string error message or boolean 'false' if OK
479 public function checkUpgradeableVersion($currentVer, $latestVer) {
481 // since version is suppose to be in valid format at this point, especially after conversion ($convertVer),
482 // lets do a pattern check -
483 if (!CRM_Utils_System
::isVersionFormatValid($currentVer)) {
484 $error = ts('Database is marked with invalid version format. You may want to investigate this before you proceed further.');
486 elseif (version_compare($currentVer, $latestVer) > 0) {
487 // DB version number is higher than codebase being upgraded to. This is unexpected condition-fatal error.
488 $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.',
489 array(1 => $currentVer, 2 => $latestVer, 3 => $dbToolsLink)
492 elseif (version_compare($currentVer, $latestVer) == 0) {
493 $error = ts('Your database has already been upgraded to CiviCRM %1',
494 array(1 => $latestVer)
498 $phpVersion = phpversion();
499 $minPhpVersion = '5.3.3';
500 if (version_compare($phpVersion, $minPhpVersion) < 0) {
501 $error = ts('CiviCRM %3 requires PHP version %1 (or newer), but the current system uses %2 ',
509 // check for mysql trigger privileges
510 if (!CRM_Core_DAO
::checkTriggerViewPermission(FALSE, TRUE)) {
511 $error = ts('CiviCRM %1 requires MySQL trigger privileges.',
512 array(1 => $latestVer));
515 if (CRM_Core_DAO
::getGlobalSetting('thread_stack', 0) < (1024 * self
::MINIMUM_THREAD_STACK
)) {
516 $error = ts('CiviCRM %1 requires MySQL thread stack >= %2k', array(
518 2 => self
::MINIMUM_THREAD_STACK
,
526 * Determine if $currentver already matches $latestVer
531 * @return mixed, a string error message or boolean 'false' if OK
533 public function checkCurrentVersion($currentVer, $latestVer) {
536 // since version is suppose to be in valid format at this point, especially after conversion ($convertVer),
537 // lets do a pattern check -
538 if (!CRM_Utils_System
::isVersionFormatValid($currentVer)) {
539 $error = ts('Database is marked with invalid version format. You may want to investigate this before you proceed further.');
541 elseif (version_compare($currentVer, $latestVer) != 0) {
542 $error = ts('Your database is not configured for version %1',
543 array(1 => $latestVer)
550 * Fill the queue with upgrade tasks
552 * @param string $currentVer
553 * the original revision.
554 * @param string $latestVer
555 * the target (final) revision.
556 * @param string $postUpgradeMessageFile
557 * path of a modifiable file which lists the post-upgrade messages.
561 public static function buildQueue($currentVer, $latestVer, $postUpgradeMessageFile) {
562 $upgrade = new CRM_Upgrade_Form();
564 // hack to make 4.0.x (D7,J1.6) codebase go through 3.4.x (d6, J1.5) upgrade files,
565 // since schema wise they are same
566 if (CRM_Upgrade_Form
::getRevisionPart($currentVer) == '4.0') {
567 $currentVer = str_replace('4.0.', '3.4.', $currentVer);
570 // Ensure that queue can be created
571 if (!CRM_Queue_BAO_QueueItem
::findCreateTable()) {
572 CRM_Core_Error
::fatal(ts('Failed to find or create queueing table'));
574 $queue = CRM_Queue_Service
::singleton()->create(array(
575 'name' => self
::QUEUE_NAME
,
580 $revisions = $upgrade->getRevisionSequence();
581 foreach ($revisions as $rev) {
582 // proceed only if $currentVer < $rev
583 if (version_compare($currentVer, $rev) < 0) {
584 $beginTask = new CRM_Queue_Task(
586 array('CRM_Upgrade_Form', 'doIncrementalUpgradeStart'),
589 "Begin Upgrade to $rev"
591 $queue->createItem($beginTask);
593 $task = new CRM_Queue_Task(
595 array('CRM_Upgrade_Form', 'doIncrementalUpgradeStep'),
597 array($rev, $currentVer, $latestVer, $postUpgradeMessageFile),
600 $queue->createItem($task);
602 $task = new CRM_Queue_Task(
604 array('CRM_Upgrade_Form', 'doIncrementalUpgradeFinish'),
606 array($rev, $currentVer, $latestVer, $postUpgradeMessageFile),
607 "Finish Upgrade DB to $rev"
609 $queue->createItem($task);
617 * Perform an incremental version update
619 * @param CRM_Queue_TaskContext $ctx
621 * the target (intermediate) revision e.g '3.2.alpha1'.
625 public static function doIncrementalUpgradeStart(CRM_Queue_TaskContext
$ctx, $rev) {
626 $upgrade = new CRM_Upgrade_Form();
628 // as soon as we start doing anything we append ".upgrade" to version.
629 // this also helps detect any partial upgrade issues
630 $upgrade->setVersion($rev . '.upgrade');
636 * Perform an incremental version update
638 * @param CRM_Queue_TaskContext $ctx
640 * the target (intermediate) revision e.g '3.2.alpha1'.
641 * @param string $originalVer
642 * the original revision.
643 * @param string $latestVer
644 * the target (final) revision.
645 * @param string $postUpgradeMessageFile
646 * path of a modifiable file which lists the post-upgrade messages.
650 public static function doIncrementalUpgradeStep(CRM_Queue_TaskContext
$ctx, $rev, $originalVer, $latestVer, $postUpgradeMessageFile) {
651 $upgrade = new CRM_Upgrade_Form();
653 $phpFunctionName = 'upgrade_' . str_replace('.', '_', $rev);
655 $versionObject = $upgrade->incrementalPhpObject($rev);
657 // pre-db check for major release.
658 if ($upgrade->checkVersionRelease($rev, 'alpha1')) {
659 if (!(is_callable(array(
664 CRM_Core_Error
::fatal("verifyPreDBstate method was not found for $rev");
668 if (!($versionObject->verifyPreDBstate($error))) {
669 if (!isset($error)) {
670 $error = "post-condition failed for current upgrade for $rev";
672 CRM_Core_Error
::fatal($error);
677 $upgrade->setSchemaStructureTables($rev);
679 if (is_callable(array(
683 $versionObject->$phpFunctionName($rev, $originalVer, $latestVer);
686 $upgrade->processSQL($rev);
689 // set post-upgrade-message if any
690 if (is_callable(array(
692 'setPostUpgradeMessage'
694 $postUpgradeMessage = file_get_contents($postUpgradeMessageFile);
695 $versionObject->setPostUpgradeMessage($postUpgradeMessage, $rev);
696 file_put_contents($postUpgradeMessageFile, $postUpgradeMessage);
699 $postUpgradeMessage = file_get_contents($postUpgradeMessageFile);
700 CRM_Upgrade_Incremental_Legacy
::setPostUpgradeMessage($postUpgradeMessage, $rev);
701 file_put_contents($postUpgradeMessageFile, $postUpgradeMessage);
708 * Perform an incremental version update
710 * @param CRM_Queue_TaskContext $ctx
712 * the target (intermediate) revision e.g '3.2.alpha1'.
713 * @param string $currentVer
714 * the original revision.
715 * @param string $latestVer
716 * the target (final) revision.
717 * @param string $postUpgradeMessageFile
718 * path of a modifiable file which lists the post-upgrade messages.
722 public static function doIncrementalUpgradeFinish(CRM_Queue_TaskContext
$ctx, $rev, $currentVer, $latestVer, $postUpgradeMessageFile) {
723 $upgrade = new CRM_Upgrade_Form();
724 $upgrade->setVersion($rev);
725 CRM_Utils_System
::flushCache();
727 $config = CRM_Core_Config
::singleton();
728 $config->userSystem
->flush();
732 public static function doFinish() {
733 $upgrade = new CRM_Upgrade_Form();
734 list($ignore, $latestVer) = $upgrade->getUpgradeVersions();
735 // Seems extraneous in context, but we'll preserve old behavior
736 $upgrade->setVersion($latestVer);
738 // lets rebuild the config array in case we've made a few changes in the
740 // this also helps us always store the latest version of civi in the DB
742 CRM_Core_BAO_ConfigSetting
::add($params);
744 // CRM-12804 comment-51411 : add any missing settings
745 // at the end of upgrade
746 CRM_Core_BAO_Setting
::updateSettingsFromMetaData();
748 // cleanup caches CRM-8739
749 $config = CRM_Core_Config
::singleton();
750 $config->cleanupCaches(1);
752 // Rebuild all triggers and re-enable logging if needed
753 $logging = new CRM_Logging_Schema();
754 $logging->fixSchemaDifferences();
758 * Compute any messages which should be displayed before upgrade
759 * by calling the 'setPreUpgradeMessage' on each incremental upgrade
762 * @param string $preUpgradeMessage
767 public function setPreUpgradeMessage(&$preUpgradeMessage, $currentVer, $latestVer) {
768 CRM_Upgrade_Incremental_Legacy
::setPreUpgradeMessage($preUpgradeMessage, $currentVer, $latestVer);
770 // Scan through all php files and see if any file is interested in setting pre-upgrade-message
771 // based on $currentVer, $latestVer.
772 // Please note, at this point upgrade hasn't started executing queries.
773 $revisions = $this->getRevisionSequence();
774 foreach ($revisions as $rev) {
775 if (version_compare($currentVer, $rev) < 0 &&
776 version_compare($rev, '3.2.alpha1') > 0
778 $versionObject = $this->incrementalPhpObject($rev);
779 if (is_callable(array(
781 'setPreUpgradeMessage'
783 $versionObject->setPreUpgradeMessage($preUpgradeMessage, $rev, $currentVer);