3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
13 * Class CRM_Upgrade_Form
15 class CRM_Upgrade_Form
extends CRM_Core_Form
{
16 const QUEUE_NAME
= 'CRM_Upgrade';
19 * Minimum size of MySQL's thread_stack option
21 * @see install/index.php MINIMUM_THREAD_STACK
23 const MINIMUM_THREAD_STACK
= 192;
26 * Minimum previous CiviCRM version we can directly upgrade from
28 const MINIMUM_UPGRADABLE_VERSION
= '4.4.7';
31 * @var \CRM_Core_Config
36 * Upgrade for multilingual.
40 public $multilingual = FALSE;
43 * Locales available for multilingual upgrade.
50 * Constructor for the basic form page.
52 * We should not use QuickForm directly. This class provides a lot
53 * of default convenient functions, rules and buttons
55 * @param object $state
56 * State associated with this form.
57 * @param const|\enum|int $action The mode the form is operating in (None/Create/View/Update/Delete)
58 * @param string $method
59 * The type of http method used (GET/POST).
61 * The name of the form if different from class name.
63 public function __construct(
65 $action = CRM_Core_Action
::NONE
,
69 $this->_config
= CRM_Core_Config
::singleton();
71 $locales = CRM_Core_I18n
::getMultilingual();
73 $this->multilingual
= (bool) $locales;
74 $this->locales
= $locales;
76 $smarty = CRM_Core_Smarty
::singleton();
77 //$smarty->compile_dir = $this->_config->templateCompileDir;
78 $smarty->assign('multilingual', $this->multilingual
);
79 $smarty->assign('locales', $this->locales
);
81 // we didn't call CRM_Core_BAO_ConfigSetting::retrieve(), so we need to set $dbLocale by hand
82 if ($this->multilingual
) {
84 $dbLocale = "_{$this->_config->lcMessages}";
87 parent
::__construct($state, $action, $method, $name);
95 public static function &incrementalPhpObject($version) {
96 static $incrementalPhpObject = [];
98 $versionParts = explode('.', $version);
99 $versionName = CRM_Utils_EnglishNumber
::toCamelCase($versionParts[0]) . CRM_Utils_EnglishNumber
::toCamelCase($versionParts[1]);
101 if (!array_key_exists($versionName, $incrementalPhpObject)) {
102 $className = "CRM_Upgrade_Incremental_php_{$versionName}";
103 $incrementalPhpObject[$versionName] = new $className();
105 return $incrementalPhpObject[$versionName];
114 public function checkVersionRelease($version, $release) {
115 $versionParts = explode('.', $version);
116 return ($versionParts[2] == $release);
120 * @param $constraints
124 public function checkSQLConstraints(&$constraints) {
126 foreach ($constraints as $constraint) {
127 if ($this->checkSQLConstraint($constraint)) {
133 return [$pass, $fail];
142 public function checkSQLConstraint($constraint) {
143 // check constraint here
148 * @param string $fileName
149 * @param bool $isQueryString
151 public function source($fileName, $isQueryString = FALSE) {
152 if ($isQueryString) {
153 CRM_Utils_File
::runSqlQuery($this->_config
->dsn
,
158 CRM_Utils_File
::sourceSQLFile($this->_config
->dsn
,
164 public function preProcess() {
165 CRM_Utils_System
::setTitle($this->getTitle());
166 if (!$this->verifyPreDBState($errorMessage)) {
167 if (!isset($errorMessage)) {
168 $errorMessage = 'pre-condition failed for current upgrade step';
170 throw new CRM_Core_Exception($errorMessage);
172 $this->assign('recentlyViewed', FALSE);
175 public function buildQuickForm() {
176 $this->addDefaultButtons($this->getButtonTitle(),
184 * Getter function for title. Should be over-ridden by derived class
192 public function getTitle() {
193 return ts('Title not Set');
199 public function getFieldsetTitle() {
206 public function getButtonTitle() {
207 return ts('Continue');
211 * Use the form name to create the tpl file name.
219 public function getTemplateFileName() {
220 $this->assign('title',
221 $this->getFieldsetTitle()
223 $this->assign('message',
224 $this->getTemplateMessage()
226 return 'CRM/Upgrade/Base.tpl';
229 public function postProcess() {
232 if (!$this->verifyPostDBState($errorMessage)) {
233 if (!isset($errorMessage)) {
234 $errorMessage = 'post-condition failed for current upgrade step';
236 throw new CRM_Core_Exception($errorMessage);
245 public function runQuery($query) {
246 return CRM_Core_DAO
::executeQuery($query);
254 public function setVersion($version) {
255 $this->logVersion($version);
258 UPDATE civicrm_domain
259 SET version = '$version'
261 return $this->runQuery($query);
269 public function logVersion($newVersion) {
271 $oldVersion = CRM_Core_BAO_Domain
::version();
273 $session = CRM_Core_Session
::singleton();
275 'entity_table' => 'civicrm_domain',
277 'data' => "upgrade:{$oldVersion}->{$newVersion}",
278 // lets skip 'modified_id' for now, as it causes FK issues And
279 // is not very important for now.
280 'modified_date' => date('YmdHis'),
282 CRM_Core_BAO_Log
::add($logParams);
293 public function getRevisionSequence() {
295 $sqlDir = implode(DIRECTORY_SEPARATOR
,
296 [dirname(__FILE__
), 'Incremental', 'sql']
298 $sqlFiles = scandir($sqlDir);
300 $sqlFilePattern = '/^((\d{1,2}\.\d{1,2})\.(\d{1,2}\.)?(\d{1,2}|\w{4,7}))\.(my)?sql(\.tpl)?$/i';
301 foreach ($sqlFiles as $file) {
302 if (preg_match($sqlFilePattern, $file, $matches)) {
303 if (!in_array($matches[1], $revList)) {
304 $revList[] = $matches[1];
309 usort($revList, 'version_compare');
319 public static function getRevisionPart($rev, $index = 1) {
320 $revPattern = '/^((\d{1,2})\.\d{1,2})\.(\d{1,2}|\w{4,7})?$/i';
321 preg_match($revPattern, $rev, $matches);
323 return array_key_exists($index, $matches) ?
$matches[$index] : NULL;
332 public function processLocales($tplFile, $rev) {
333 $smarty = CRM_Core_Smarty
::singleton();
334 $smarty->assign('domainID', CRM_Core_Config
::domainID());
336 $this->source($smarty->fetch($tplFile), TRUE);
338 if ($this->multilingual
) {
339 CRM_Core_I18n_Schema
::rebuildMultilingualSchema($this->locales
, $rev);
341 return $this->multilingual
;
347 public function setSchemaStructureTables($rev) {
348 if ($this->multilingual
) {
349 CRM_Core_I18n_Schema
::schemaStructureTables($rev, TRUE);
358 public function processSQL($rev) {
359 $sqlFile = implode(DIRECTORY_SEPARATOR
,
367 $tplFile = "$sqlFile.tpl";
369 if (file_exists($tplFile)) {
370 $this->processLocales($tplFile, $rev);
373 if (!file_exists($sqlFile)) {
374 throw new CRM_Core_Exception("sqlfile - $rev.mysql not found.");
376 $this->source($sqlFile);
381 * Determine the start and end version of the upgrade process.
383 * @return array(0=>$currentVer, 1=>$latestVer)
385 public function getUpgradeVersions() {
386 $latestVer = CRM_Utils_System
::version();
387 $currentVer = CRM_Core_BAO_Domain
::version(TRUE);
389 throw new CRM_Core_Exception(ts('Version information missing in civicrm database.'));
391 elseif (stripos($currentVer, 'upgrade')) {
392 throw new CRM_Core_Exception(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.'));
395 throw new CRM_Core_Exception(ts('Version information missing in civicrm codebase.'));
398 return [$currentVer, $latestVer];
402 * Determine if $currentVer can be upgraded to $latestVer
407 * @return mixed, a string error message or boolean 'false' if OK
409 public function checkUpgradeableVersion($currentVer, $latestVer) {
411 // since version is suppose to be in valid format at this point, especially after conversion ($convertVer),
412 // lets do a pattern check -
413 if (!CRM_Utils_System
::isVersionFormatValid($currentVer)) {
414 $error = ts('Database is marked with invalid version format. You may want to investigate this before you proceed further.');
416 elseif (version_compare($currentVer, $latestVer) > 0) {
417 // DB version number is higher than codebase being upgraded to. This is unexpected condition-fatal error.
418 $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.',
419 [1 => $currentVer, 2 => $latestVer]
422 elseif (version_compare($currentVer, $latestVer) == 0) {
423 $error = ts('Your database has already been upgraded to CiviCRM %1',
427 elseif (version_compare($currentVer, self
::MINIMUM_UPGRADABLE_VERSION
) < 0) {
428 $error = ts('CiviCRM versions prior to %1 cannot be upgraded directly to %2. This upgrade will need to be done in stages. First download an intermediate version (the LTS may be a good choice) and upgrade to that before proceeding to this version.',
429 [1 => self
::MINIMUM_UPGRADABLE_VERSION
, 2 => $latestVer]
433 if (version_compare(phpversion(), CRM_Upgrade_Incremental_General
::MIN_INSTALL_PHP_VER
) < 0) {
434 $error = ts('CiviCRM %3 requires PHP version %1 (or newer), but the current system uses %2 ',
436 1 => CRM_Upgrade_Incremental_General
::MIN_INSTALL_PHP_VER
,
442 if (version_compare(CRM_Utils_SQL
::getDatabaseVersion(), CRM_Upgrade_Incremental_General
::MIN_INSTALL_MYSQL_VER
) < 0) {
443 $error = ts('CiviCRM %4 requires MySQL version v%1 or MariaDB v%3 (or newer), but the current system uses %2 ',
445 1 => CRM_Upgrade_Incremental_General
::MIN_INSTALL_MYSQL_VER
,
446 2 => CRM_Utils_SQL
::getDatabaseVersion(),
452 // check for mysql trigger privileges
453 if (!\Civi
::settings()->get('logging_no_trigger_permission') && !CRM_Core_DAO
::checkTriggerViewPermission(FALSE, TRUE)) {
454 $error = ts('CiviCRM %1 requires MySQL trigger privileges.',
458 if (CRM_Core_DAO
::getGlobalSetting('thread_stack', 0) < (1024 * self
::MINIMUM_THREAD_STACK
)) {
459 $error = ts('CiviCRM %1 requires MySQL thread stack >= %2k', [
461 2 => self
::MINIMUM_THREAD_STACK
,
469 * Determine if $currentver already matches $latestVer
474 * @return mixed, a string error message or boolean 'false' if OK
476 public function checkCurrentVersion($currentVer, $latestVer) {
479 // since version is suppose to be in valid format at this point, especially after conversion ($convertVer),
480 // lets do a pattern check -
481 if (!CRM_Utils_System
::isVersionFormatValid($currentVer)) {
482 $error = ts('Database is marked with invalid version format. You may want to investigate this before you proceed further.');
484 elseif (version_compare($currentVer, $latestVer) != 0) {
485 $error = ts('Your database is not configured for version %1',
493 * Fill the queue with upgrade tasks.
495 * @param string $currentVer
496 * the original revision.
497 * @param string $latestVer
498 * the target (final) revision.
499 * @param string $postUpgradeMessageFile
500 * path of a modifiable file which lists the post-upgrade messages.
502 * @return CRM_Queue_Service
504 public static function buildQueue($currentVer, $latestVer, $postUpgradeMessageFile) {
505 $upgrade = new CRM_Upgrade_Form();
507 // Ensure that queue can be created
508 if (!CRM_Queue_BAO_QueueItem
::findCreateTable()) {
509 throw new CRM_Core_Exception(ts('Failed to find or create queueing table'));
511 $queue = CRM_Queue_Service
::singleton()->create([
512 'name' => self
::QUEUE_NAME
,
517 $task = new CRM_Queue_Task(
518 ['CRM_Upgrade_Form', 'doFileCleanup'],
519 [$postUpgradeMessageFile],
522 $queue->createItem($task);
524 $task = new CRM_Queue_Task(
525 ['CRM_Upgrade_Form', 'disableOldExtensions'],
526 [$postUpgradeMessageFile],
527 "Checking extensions"
529 $queue->createItem($task);
531 $revisions = $upgrade->getRevisionSequence();
532 foreach ($revisions as $rev) {
533 // proceed only if $currentVer < $rev
534 if (version_compare($currentVer, $rev) < 0) {
535 $beginTask = new CRM_Queue_Task(
537 ['CRM_Upgrade_Form', 'doIncrementalUpgradeStart'],
540 "Begin Upgrade to $rev"
542 $queue->createItem($beginTask);
544 $task = new CRM_Queue_Task(
546 ['CRM_Upgrade_Form', 'doIncrementalUpgradeStep'],
548 [$rev, $currentVer, $latestVer, $postUpgradeMessageFile],
551 $queue->createItem($task);
553 $task = new CRM_Queue_Task(
555 ['CRM_Upgrade_Form', 'doIncrementalUpgradeFinish'],
557 [$rev, $currentVer, $latestVer, $postUpgradeMessageFile],
558 "Finish Upgrade DB to $rev"
560 $queue->createItem($task);
568 * Find any old, orphaned files that should have been deleted.
570 * These files can get left behind, eg, if you use the Joomla
573 * The earlier we can do this, the better - don't want upgrade logic
574 * to inadvertently rely on old/relocated files.
576 * @param \CRM_Queue_TaskContext $ctx
577 * @param string $postUpgradeMessageFile
580 public static function doFileCleanup(CRM_Queue_TaskContext
$ctx, $postUpgradeMessageFile) {
581 $source = new CRM_Utils_Check_Component_Source();
582 $files = $source->findOrphanedFiles();
584 foreach ($files as $file) {
585 if (is_dir($file['path'])) {
586 @rmdir
($file['path']);
589 @unlink
($file['path']);
592 if (file_exists($file['path'])) {
593 $errors[] = sprintf("<li>%s</li>", htmlentities($file['path']));
597 if (!empty($errors)) {
598 file_put_contents($postUpgradeMessageFile,
599 '<br/><br/>' . ts('Some old files could not be removed. Please remove them.')
600 . '<ul>' . implode("\n", $errors) . '</ul>',
609 * Disable/uninstall any extensions not compatible with this new version.
611 * @param \CRM_Queue_TaskContext $ctx
612 * @param string $postUpgradeMessageFile
615 public static function disableOldExtensions(CRM_Queue_TaskContext
$ctx, $postUpgradeMessageFile) {
617 $manager = CRM_Extension_System
::singleton()->getManager();
618 foreach ($manager->getStatuses() as $key => $status) {
619 $obsolete = $manager->isIncompatible($key);
621 if (!empty($obsolete['disable']) && in_array($status, [$manager::STATUS_INSTALLED
, $manager::STATUS_INSTALLED_MISSING
])) {
623 $manager->disable($key);
624 // Update the status for the sake of uninstall below.
625 $status = $status == $manager::STATUS_INSTALLED ?
$manager::STATUS_DISABLED
: $manager::STATUS_DISABLED_MISSING
;
626 // This message is intentionally overwritten by uninstall below as it would be redundant
627 $messages[$key] = ts('The extension %1 is now obsolete and has been disabled.', [1 => $key]);
629 catch (CRM_Extension_Exception
$e) {
630 $messages[] = ts('The obsolete extension %1 could not be removed due to an error. It is recommended to remove this extension manually.', [1 => $key]);
633 if (!empty($obsolete['uninstall']) && in_array($status, [$manager::STATUS_DISABLED
, $manager::STATUS_DISABLED_MISSING
])) {
635 $manager->uninstall($key);
636 $messages[$key] = ts('The extension %1 is now obsolete and has been uninstalled.', [1 => $key]);
637 if ($status == $manager::STATUS_DISABLED
) {
638 $messages[$key] .= ' ' . ts('You can remove it from your extensions directory.');
641 catch (CRM_Extension_Exception
$e) {
642 $messages[] = ts('The obsolete extension %1 could not be removed due to an error. It is recommended to remove this extension manually.', [1 => $key]);
645 if (!empty($obsolete['force-uninstall'])) {
646 CRM_Core_DAO
::executeQuery('UPDATE civicrm_extension SET is_active = 0 WHERE full_name = %1', [
647 1 => [$key, 'String'],
653 file_put_contents($postUpgradeMessageFile,
654 '<br/><br/><ul><li>' . implode("</li>\n<li>", $messages) . '</li></ul>',
663 * Perform an incremental version update.
665 * @param CRM_Queue_TaskContext $ctx
667 * the target (intermediate) revision e.g '3.2.alpha1'.
671 public static function doIncrementalUpgradeStart(CRM_Queue_TaskContext
$ctx, $rev) {
672 $upgrade = new CRM_Upgrade_Form();
674 // as soon as we start doing anything we append ".upgrade" to version.
675 // this also helps detect any partial upgrade issues
676 $upgrade->setVersion($rev . '.upgrade');
682 * Perform an incremental version update.
684 * @param CRM_Queue_TaskContext $ctx
686 * the target (intermediate) revision e.g '3.2.alpha1'.
687 * @param string $originalVer
688 * the original revision.
689 * @param string $latestVer
690 * the target (final) revision.
691 * @param string $postUpgradeMessageFile
692 * path of a modifiable file which lists the post-upgrade messages.
696 public static function doIncrementalUpgradeStep(CRM_Queue_TaskContext
$ctx, $rev, $originalVer, $latestVer, $postUpgradeMessageFile) {
697 $upgrade = new CRM_Upgrade_Form();
699 $phpFunctionName = 'upgrade_' . str_replace('.', '_', $rev);
701 $versionObject = $upgrade->incrementalPhpObject($rev);
703 // pre-db check for major release.
704 if ($upgrade->checkVersionRelease($rev, 'alpha1')) {
705 if (!(is_callable([$versionObject, 'verifyPreDBstate']))) {
706 throw new CRM_Core_Exception("verifyPreDBstate method was not found for $rev");
710 if (!($versionObject->verifyPreDBstate($error))) {
711 if (!isset($error)) {
712 $error = "post-condition failed for current upgrade for $rev";
714 throw new CRM_Core_Exception($error);
719 $upgrade->setSchemaStructureTables($rev);
721 if (is_callable([$versionObject, $phpFunctionName])) {
722 $versionObject->$phpFunctionName($rev, $originalVer, $latestVer);
725 $upgrade->processSQL($rev);
728 // set post-upgrade-message if any
729 if (is_callable([$versionObject, 'setPostUpgradeMessage'])) {
730 $postUpgradeMessage = file_get_contents($postUpgradeMessageFile);
731 $versionObject->setPostUpgradeMessage($postUpgradeMessage, $rev);
732 file_put_contents($postUpgradeMessageFile, $postUpgradeMessage);
739 * Perform an incremental version update.
741 * @param CRM_Queue_TaskContext $ctx
743 * the target (intermediate) revision e.g '3.2.alpha1'.
744 * @param string $currentVer
745 * the original revision.
746 * @param string $latestVer
747 * the target (final) revision.
748 * @param string $postUpgradeMessageFile
749 * path of a modifiable file which lists the post-upgrade messages.
753 public static function doIncrementalUpgradeFinish(CRM_Queue_TaskContext
$ctx, $rev, $currentVer, $latestVer, $postUpgradeMessageFile) {
754 $upgrade = new CRM_Upgrade_Form();
755 $upgrade->setVersion($rev);
756 CRM_Utils_System
::flushCache();
758 $config = CRM_Core_Config
::singleton();
759 $config->userSystem
->flush();
763 public static function doFinish() {
764 Civi
::dispatcher()->setDispatchPolicy(\CRM_Upgrade_DispatchPolicy
::get('upgrade.finish'));
765 $restore = \CRM_Utils_AutoClean
::with(function() {
766 Civi
::dispatcher()->setDispatchPolicy(\CRM_Upgrade_DispatchPolicy
::get('upgrade.main'));
769 $upgrade = new CRM_Upgrade_Form();
770 list($ignore, $latestVer) = $upgrade->getUpgradeVersions();
771 // Seems extraneous in context, but we'll preserve old behavior
772 $upgrade->setVersion($latestVer);
774 CRM_Core_Invoke
::rebuildMenuAndCaches(FALSE, TRUE);
775 // NOTE: triggerRebuild is FALSE becaues it will run again in a moment (via fixSchemaDifferences).
777 $versionCheck = new CRM_Utils_VersionCheck();
778 $versionCheck->flushCache();
780 // Rebuild all triggers and re-enable logging if needed
781 $logging = new CRM_Logging_Schema();
782 $logging->fixSchemaDifferences();
786 * Compute any messages which should be displayed before upgrade
787 * by calling the 'setPreUpgradeMessage' on each incremental upgrade
790 * @param string $preUpgradeMessage
795 public function setPreUpgradeMessage(&$preUpgradeMessage, $currentVer, $latestVer) {
796 // check for changed message templates
797 CRM_Upgrade_Incremental_General
::checkMessageTemplate($preUpgradeMessage, $latestVer, $currentVer);
798 // set global messages
799 CRM_Upgrade_Incremental_General
::setPreUpgradeMessage($preUpgradeMessage, $currentVer, $latestVer);
801 // Scan through all php files and see if any file is interested in setting pre-upgrade-message
802 // based on $currentVer, $latestVer.
803 // Please note, at this point upgrade hasn't started executing queries.
804 $revisions = $this->getRevisionSequence();
805 foreach ($revisions as $rev) {
806 if (version_compare($currentVer, $rev) < 0) {
807 $versionObject = $this->incrementalPhpObject($rev);
808 CRM_Upgrade_Incremental_General
::updateMessageTemplate($preUpgradeMessage, $rev);
809 if (is_callable([$versionObject, 'setPreUpgradeMessage'])) {
810 $versionObject->setPreUpgradeMessage($preUpgradeMessage, $rev, $currentVer);