3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
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;
46 * Minimum previous CiviCRM version we can directly upgrade from
48 const MINIMUM_UPGRADABLE_VERSION
= '4.1.3';
51 * Minimum php version required to run (equal to or lower than the minimum install version)
53 const MINIMUM_PHP_VERSION
= '5.5';
58 * Upgrade for multilingual.
62 public $multilingual = FALSE;
65 * Locales available for multilingual upgrade.
72 * Constructor for the basic form page.
74 * We should not use QuickForm directly. This class provides a lot
75 * of default convenient functions, rules and buttons
77 * @param object $state
78 * State associated with this form.
79 * @param const|\enum|int $action The mode the form is operating in (None/Create/View/Update/Delete)
80 * @param string $method
81 * The type of http method used (GET/POST).
83 * The name of the form if different from class name.
85 public function __construct(
87 $action = CRM_Core_Action
::NONE
,
91 $this->_config
= CRM_Core_Config
::singleton();
93 $domain = new CRM_Core_DAO_Domain();
96 $this->multilingual
= (bool) $domain->locales
;
97 $this->locales
= explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $domain->locales
);
99 $smarty = CRM_Core_Smarty
::singleton();
100 //$smarty->compile_dir = $this->_config->templateCompileDir;
101 $smarty->assign('multilingual', $this->multilingual
);
102 $smarty->assign('locales', $this->locales
);
104 // we didn't call CRM_Core_BAO_ConfigSetting::retrieve(), so we need to set $dbLocale by hand
105 if ($this->multilingual
) {
107 $dbLocale = "_{$this->_config->lcMessages}";
110 parent
::__construct($state, $action, $method, $name);
118 public static function &incrementalPhpObject($version) {
119 static $incrementalPhpObject = array();
121 $versionParts = explode('.', $version);
122 $versionName = CRM_Utils_EnglishNumber
::toCamelCase($versionParts[0]) . CRM_Utils_EnglishNumber
::toCamelCase($versionParts[1]);
124 if (!array_key_exists($versionName, $incrementalPhpObject)) {
125 $className = "CRM_Upgrade_Incremental_php_{$versionName}";
126 $incrementalPhpObject[$versionName] = new $className();
128 return $incrementalPhpObject[$versionName];
137 public function checkVersionRelease($version, $release) {
138 $versionParts = explode('.', $version);
139 return ($versionParts[2] == $release);
143 * @param $constraints
147 public function checkSQLConstraints(&$constraints) {
149 foreach ($constraints as $constraint) {
150 if ($this->checkSQLConstraint($constraint)) {
156 return array($pass, $fail);
165 public function checkSQLConstraint($constraint) {
166 // check constraint here
171 * @param string $fileName
172 * @param bool $isQueryString
174 public function source($fileName, $isQueryString = FALSE) {
175 if ($isQueryString) {
176 CRM_Utils_File
::runSqlQuery($this->_config
->dsn
,
181 CRM_Utils_File
::sourceSQLFile($this->_config
->dsn
,
187 public function preProcess() {
188 CRM_Utils_System
::setTitle($this->getTitle());
189 if (!$this->verifyPreDBState($errorMessage)) {
190 if (!isset($errorMessage)) {
191 $errorMessage = 'pre-condition failed for current upgrade step';
193 CRM_Core_Error
::fatal($errorMessage);
195 $this->assign('recentlyViewed', FALSE);
198 public function buildQuickForm() {
199 $this->addDefaultButtons($this->getButtonTitle(),
207 * Getter function for title. Should be over-ridden by derived class
214 public function getTitle() {
215 return ts('Title not Set');
221 public function getFieldsetTitle() {
228 public function getButtonTitle() {
229 return ts('Continue');
233 * Use the form name to create the tpl file name.
240 public function getTemplateFileName() {
241 $this->assign('title',
242 $this->getFieldsetTitle()
244 $this->assign('message',
245 $this->getTemplateMessage()
247 return 'CRM/Upgrade/Base.tpl';
250 public function postProcess() {
253 if (!$this->verifyPostDBState($errorMessage)) {
254 if (!isset($errorMessage)) {
255 $errorMessage = 'post-condition failed for current upgrade step';
257 CRM_Core_Error
::fatal($errorMessage);
266 public function runQuery($query) {
267 return CRM_Core_DAO
::executeQuery($query,
268 CRM_Core_DAO
::$_nullArray
277 public function setVersion($version) {
278 $this->logVersion($version);
281 UPDATE civicrm_domain
282 SET version = '$version'
284 return $this->runQuery($query);
292 public function logVersion($newVersion) {
294 $oldVersion = CRM_Core_BAO_Domain
::version();
296 $session = CRM_Core_Session
::singleton();
298 'entity_table' => 'civicrm_domain',
300 'data' => "upgrade:{$oldVersion}->{$newVersion}",
301 // lets skip 'modified_id' for now, as it causes FK issues And
302 // is not very important for now.
303 'modified_date' => date('YmdHis'),
305 CRM_Core_BAO_Log
::add($logParams);
317 public function checkVersion($version) {
318 $domainID = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain',
322 return $domainID ?
TRUE : FALSE;
329 public function getRevisionSequence() {
331 $sqlDir = implode(DIRECTORY_SEPARATOR
,
332 array(dirname(__FILE__
), 'Incremental', 'sql')
334 $sqlFiles = scandir($sqlDir);
336 $sqlFilePattern = '/^((\d{1,2}\.\d{1,2})\.(\d{1,2}\.)?(\d{1,2}|\w{4,7}))\.(my)?sql(\.tpl)?$/i';
337 foreach ($sqlFiles as $file) {
338 if (preg_match($sqlFilePattern, $file, $matches)) {
339 if (!in_array($matches[1], $revList)) {
340 $revList[] = $matches[1];
345 usort($revList, 'version_compare');
355 public static function getRevisionPart($rev, $index = 1) {
356 $revPattern = '/^((\d{1,2})\.\d{1,2})\.(\d{1,2}|\w{4,7})?$/i';
357 preg_match($revPattern, $rev, $matches);
359 return array_key_exists($index, $matches) ?
$matches[$index] : NULL;
368 public function processLocales($tplFile, $rev) {
369 $smarty = CRM_Core_Smarty
::singleton();
370 $smarty->assign('domainID', CRM_Core_Config
::domainID());
372 $this->source($smarty->fetch($tplFile), TRUE);
374 if ($this->multilingual
) {
375 CRM_Core_I18n_Schema
::rebuildMultilingualSchema($this->locales
, $rev);
377 return $this->multilingual
;
383 public function setSchemaStructureTables($rev) {
384 if ($this->multilingual
) {
385 CRM_Core_I18n_Schema
::schemaStructureTables($rev, TRUE);
394 public function processSQL($rev) {
395 $sqlFile = implode(DIRECTORY_SEPARATOR
,
403 $tplFile = "$sqlFile.tpl";
405 if (file_exists($tplFile)) {
406 $this->processLocales($tplFile, $rev);
409 if (!file_exists($sqlFile)) {
410 CRM_Core_Error
::fatal("sqlfile - $rev.mysql not found.");
412 $this->source($sqlFile);
417 * Determine the start and end version of the upgrade process.
419 * @return array(0=>$currentVer, 1=>$latestVer)
421 public function getUpgradeVersions() {
422 $latestVer = CRM_Utils_System
::version();
423 $currentVer = CRM_Core_BAO_Domain
::version(TRUE);
425 CRM_Core_Error
::fatal(ts('Version information missing in civicrm database.'));
427 elseif (stripos($currentVer, 'upgrade')) {
428 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.'));
431 CRM_Core_Error
::fatal(ts('Version information missing in civicrm codebase.'));
434 return array($currentVer, $latestVer);
438 * Determine if $currentVer can be upgraded to $latestVer
443 * @return mixed, a string error message or boolean 'false' if OK
445 public function checkUpgradeableVersion($currentVer, $latestVer) {
447 // since version is suppose to be in valid format at this point, especially after conversion ($convertVer),
448 // lets do a pattern check -
449 if (!CRM_Utils_System
::isVersionFormatValid($currentVer)) {
450 $error = ts('Database is marked with invalid version format. You may want to investigate this before you proceed further.');
452 elseif (version_compare($currentVer, $latestVer) > 0) {
453 // DB version number is higher than codebase being upgraded to. This is unexpected condition-fatal error.
454 $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.',
455 array(1 => $currentVer, 2 => $latestVer)
458 elseif (version_compare($currentVer, $latestVer) == 0) {
459 $error = ts('Your database has already been upgraded to CiviCRM %1',
460 array(1 => $latestVer)
463 elseif (version_compare($currentVer, self
::MINIMUM_UPGRADABLE_VERSION
) < 0) {
464 $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.',
465 array(1 => self
::MINIMUM_UPGRADABLE_VERSION
, 2 => $latestVer)
469 if (version_compare(phpversion(), self
::MINIMUM_PHP_VERSION
) < 0) {
470 $error = ts('CiviCRM %3 requires PHP version %1 (or newer), but the current system uses %2 ',
472 1 => self
::MINIMUM_PHP_VERSION
,
478 // check for mysql trigger privileges
479 if (!\Civi
::settings()->get('logging_no_trigger_permission') && !CRM_Core_DAO
::checkTriggerViewPermission(FALSE, TRUE)) {
480 $error = ts('CiviCRM %1 requires MySQL trigger privileges.',
481 array(1 => $latestVer));
484 if (CRM_Core_DAO
::getGlobalSetting('thread_stack', 0) < (1024 * self
::MINIMUM_THREAD_STACK
)) {
485 $error = ts('CiviCRM %1 requires MySQL thread stack >= %2k', array(
487 2 => self
::MINIMUM_THREAD_STACK
,
495 * Determine if $currentver already matches $latestVer
500 * @return mixed, a string error message or boolean 'false' if OK
502 public function checkCurrentVersion($currentVer, $latestVer) {
505 // since version is suppose to be in valid format at this point, especially after conversion ($convertVer),
506 // lets do a pattern check -
507 if (!CRM_Utils_System
::isVersionFormatValid($currentVer)) {
508 $error = ts('Database is marked with invalid version format. You may want to investigate this before you proceed further.');
510 elseif (version_compare($currentVer, $latestVer) != 0) {
511 $error = ts('Your database is not configured for version %1',
512 array(1 => $latestVer)
519 * Fill the queue with upgrade tasks.
521 * @param string $currentVer
522 * the original revision.
523 * @param string $latestVer
524 * the target (final) revision.
525 * @param string $postUpgradeMessageFile
526 * path of a modifiable file which lists the post-upgrade messages.
528 * @return CRM_Queue_Service
530 public static function buildQueue($currentVer, $latestVer, $postUpgradeMessageFile) {
531 $upgrade = new CRM_Upgrade_Form();
533 // Ensure that queue can be created
534 if (!CRM_Queue_BAO_QueueItem
::findCreateTable()) {
535 CRM_Core_Error
::fatal(ts('Failed to find or create queueing table'));
537 $queue = CRM_Queue_Service
::singleton()->create(array(
538 'name' => self
::QUEUE_NAME
,
543 $task = new CRM_Queue_Task(
544 array('CRM_Upgrade_Form', 'doFileCleanup'),
545 array($postUpgradeMessageFile),
548 $queue->createItem($task);
550 $revisions = $upgrade->getRevisionSequence();
551 foreach ($revisions as $rev) {
552 // proceed only if $currentVer < $rev
553 if (version_compare($currentVer, $rev) < 0) {
554 $beginTask = new CRM_Queue_Task(
556 array('CRM_Upgrade_Form', 'doIncrementalUpgradeStart'),
559 "Begin Upgrade to $rev"
561 $queue->createItem($beginTask);
563 $task = new CRM_Queue_Task(
565 array('CRM_Upgrade_Form', 'doIncrementalUpgradeStep'),
567 array($rev, $currentVer, $latestVer, $postUpgradeMessageFile),
570 $queue->createItem($task);
572 $task = new CRM_Queue_Task(
574 array('CRM_Upgrade_Form', 'doIncrementalUpgradeFinish'),
576 array($rev, $currentVer, $latestVer, $postUpgradeMessageFile),
577 "Finish Upgrade DB to $rev"
579 $queue->createItem($task);
587 * Find any old, orphaned files that should have been deleted.
589 * These files can get left behind, eg, if you use the Joomla
592 * The earlier we can do this, the better - don't want upgrade logic
593 * to inadvertently rely on old/relocated files.
595 * @param \CRM_Queue_TaskContext $ctx
596 * @param string $postUpgradeMessageFile
599 public static function doFileCleanup(CRM_Queue_TaskContext
$ctx, $postUpgradeMessageFile) {
600 $source = new CRM_Utils_Check_Component_Source();
601 $files = $source->findOrphanedFiles();
603 foreach ($files as $file) {
604 if (is_dir($file['path'])) {
605 @rmdir
($file['path']);
608 @unlink
($file['path']);
611 if (file_exists($file['path'])) {
612 $errors[] = sprintf("<li>%s</li>", htmlentities($file['path']));
616 if (!empty($errors)) {
617 file_put_contents($postUpgradeMessageFile,
618 '<br/><br/>' . ts('Some old files could not be removed. Please remove them.')
619 . '<ul>' . implode("\n", $errors) . '</ul>',
628 * Perform an incremental version update.
630 * @param CRM_Queue_TaskContext $ctx
632 * the target (intermediate) revision e.g '3.2.alpha1'.
636 public static function doIncrementalUpgradeStart(CRM_Queue_TaskContext
$ctx, $rev) {
637 $upgrade = new CRM_Upgrade_Form();
639 // as soon as we start doing anything we append ".upgrade" to version.
640 // this also helps detect any partial upgrade issues
641 $upgrade->setVersion($rev . '.upgrade');
647 * Perform an incremental version update.
649 * @param CRM_Queue_TaskContext $ctx
651 * the target (intermediate) revision e.g '3.2.alpha1'.
652 * @param string $originalVer
653 * the original revision.
654 * @param string $latestVer
655 * the target (final) revision.
656 * @param string $postUpgradeMessageFile
657 * path of a modifiable file which lists the post-upgrade messages.
661 public static function doIncrementalUpgradeStep(CRM_Queue_TaskContext
$ctx, $rev, $originalVer, $latestVer, $postUpgradeMessageFile) {
662 $upgrade = new CRM_Upgrade_Form();
664 $phpFunctionName = 'upgrade_' . str_replace('.', '_', $rev);
666 $versionObject = $upgrade->incrementalPhpObject($rev);
668 // pre-db check for major release.
669 if ($upgrade->checkVersionRelease($rev, 'alpha1')) {
670 if (!(is_callable(array($versionObject, 'verifyPreDBstate')))) {
671 CRM_Core_Error
::fatal("verifyPreDBstate method was not found for $rev");
675 if (!($versionObject->verifyPreDBstate($error))) {
676 if (!isset($error)) {
677 $error = "post-condition failed for current upgrade for $rev";
679 CRM_Core_Error
::fatal($error);
684 $upgrade->setSchemaStructureTables($rev);
686 if (is_callable(array($versionObject, $phpFunctionName))) {
687 $versionObject->$phpFunctionName($rev, $originalVer, $latestVer);
690 $upgrade->processSQL($rev);
693 // set post-upgrade-message if any
694 if (is_callable(array($versionObject, 'setPostUpgradeMessage'))) {
695 $postUpgradeMessage = file_get_contents($postUpgradeMessageFile);
696 $versionObject->setPostUpgradeMessage($postUpgradeMessage, $rev);
697 file_put_contents($postUpgradeMessageFile, $postUpgradeMessage);
704 * Perform an incremental version update.
706 * @param CRM_Queue_TaskContext $ctx
708 * the target (intermediate) revision e.g '3.2.alpha1'.
709 * @param string $currentVer
710 * the original revision.
711 * @param string $latestVer
712 * the target (final) revision.
713 * @param string $postUpgradeMessageFile
714 * path of a modifiable file which lists the post-upgrade messages.
718 public static function doIncrementalUpgradeFinish(CRM_Queue_TaskContext
$ctx, $rev, $currentVer, $latestVer, $postUpgradeMessageFile) {
719 $upgrade = new CRM_Upgrade_Form();
720 $upgrade->setVersion($rev);
721 CRM_Utils_System
::flushCache();
723 $config = CRM_Core_Config
::singleton();
724 $config->userSystem
->flush();
728 public static function doFinish() {
729 $upgrade = new CRM_Upgrade_Form();
730 list($ignore, $latestVer) = $upgrade->getUpgradeVersions();
731 // Seems extraneous in context, but we'll preserve old behavior
732 $upgrade->setVersion($latestVer);
734 // Clear cached metadata.
735 Civi
::service('settings_manager')->flush();
737 // cleanup caches CRM-8739
738 $config = CRM_Core_Config
::singleton();
739 $config->cleanupCaches(1);
741 $versionCheck = new CRM_Utils_VersionCheck();
742 $versionCheck->flushCache();
744 // Rebuild all triggers and re-enable logging if needed
745 $logging = new CRM_Logging_Schema();
746 $logging->fixSchemaDifferences();
750 * Compute any messages which should be displayed before upgrade
751 * by calling the 'setPreUpgradeMessage' on each incremental upgrade
754 * @param string $preUpgradeMessage
759 public function setPreUpgradeMessage(&$preUpgradeMessage, $currentVer, $latestVer) {
760 // check for changed message templates
761 CRM_Upgrade_Incremental_General
::checkMessageTemplate($preUpgradeMessage, $latestVer, $currentVer);
762 // set global messages
763 CRM_Upgrade_Incremental_General
::setPreUpgradeMessage($preUpgradeMessage, $currentVer, $latestVer);
765 // Scan through all php files and see if any file is interested in setting pre-upgrade-message
766 // based on $currentVer, $latestVer.
767 // Please note, at this point upgrade hasn't started executing queries.
768 $revisions = $this->getRevisionSequence();
769 foreach ($revisions as $rev) {
770 if (version_compare($currentVer, $rev) < 0) {
771 $versionObject = $this->incrementalPhpObject($rev);
772 if (is_callable(array($versionObject, 'setPreUpgradeMessage'))) {
773 $versionObject->setPreUpgradeMessage($preUpgradeMessage, $rev, $currentVer);