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 State associated with this form
86 * @param \const|\enum $action The mode the form is operating in (None/Create/View/Update/Delete)
87 * @param string $method The type of http method used (GET/POST)
88 * @param string $name The name of the form if different from class name
90 * @return \CRM_Core_Form
94 * @param null|object $state
95 * @param const|enum|int $action
96 * @param string $method
97 * @param null|string $name
99 function __construct($state = NULL,
100 $action = CRM_Core_Action
::NONE
,
104 $this->_config
= CRM_Core_Config
::singleton();
106 $domain = new CRM_Core_DAO_Domain();
109 $this->multilingual
= (bool) $domain->locales
;
110 $this->locales
= explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $domain->locales
);
112 $smarty = CRM_Core_Smarty
::singleton();
113 $smarty->compile_dir
= $this->_config
->templateCompileDir
;
114 $smarty->assign('multilingual', $this->multilingual
);
115 $smarty->assign('locales', $this->locales
);
117 // we didn't call CRM_Core_BAO_ConfigSetting::retrieve(), so we need to set $dbLocale by hand
118 if ($this->multilingual
) {
120 $dbLocale = "_{$this->_config->lcMessages}";
123 parent
::__construct($state, $action, $method, $name);
131 public static function &incrementalPhpObject($version) {
132 static $incrementalPhpObject = array();
134 $versionParts = explode('.', $version);
135 $versionName = self
::$_numberMap[$versionParts[0]] . self
::$_numberMap[$versionParts[1]];
137 if (!array_key_exists($versionName, $incrementalPhpObject)) {
138 $className = "CRM_Upgrade_Incremental_php_{$versionName}";
139 $incrementalPhpObject[$versionName] = new $className();
141 return $incrementalPhpObject[$versionName];
150 public function checkVersionRelease($version, $release) {
151 $versionParts = explode('.', $version);
152 if ($versionParts[2] == $release) {
159 * @param $constraints
163 public function checkSQLConstraints(&$constraints) {
165 foreach ($constraints as $constraint) {
166 if ($this->checkSQLConstraint($constraint)) {
172 return array($pass, $fail);
181 public function checkSQLConstraint($constraint) {
182 // check constraint here
187 * @param string $fileName
188 * @param bool $isQueryString
190 public function source($fileName, $isQueryString = FALSE) {
192 CRM_Utils_File
::sourceSQLFile($this->_config
->dsn
,
193 $fileName, NULL, $isQueryString
197 public function preProcess() {
198 CRM_Utils_System
::setTitle($this->getTitle());
199 if (!$this->verifyPreDBState($errorMessage)) {
200 if (!isset($errorMessage)) {
201 $errorMessage = 'pre-condition failed for current upgrade step';
203 CRM_Core_Error
::fatal($errorMessage);
205 $this->assign('recentlyViewed', FALSE);
208 public function buildQuickForm() {
209 $this->addDefaultButtons($this->getButtonTitle(),
217 * Getter function for title. Should be over-ridden by derived class
224 public function getTitle() {
225 return ts('Title not Set');
231 public function getFieldsetTitle() {
238 public function getButtonTitle() {
239 return ts('Continue');
243 * Use the form name to create the tpl file name
250 public function getTemplateFileName() {
251 $this->assign('title',
252 $this->getFieldsetTitle()
254 $this->assign('message',
255 $this->getTemplateMessage()
257 return 'CRM/Upgrade/Base.tpl';
260 public function postProcess() {
263 if (!$this->verifyPostDBState($errorMessage)) {
264 if (!isset($errorMessage)) {
265 $errorMessage = 'post-condition failed for current upgrade step';
267 CRM_Core_Error
::fatal($errorMessage);
276 public function runQuery($query) {
277 return CRM_Core_DAO
::executeQuery($query,
278 CRM_Core_DAO
::$_nullArray
287 public function setVersion($version) {
288 $this->logVersion($version);
291 UPDATE civicrm_domain
292 SET version = '$version'
294 return $this->runQuery($query);
302 public function logVersion($newVersion) {
304 $oldVersion = CRM_Core_BAO_Domain
::version();
306 $session = CRM_Core_Session
::singleton();
308 'entity_table' => 'civicrm_domain',
310 'data' => "upgrade:{$oldVersion}->{$newVersion}",
311 // lets skip 'modified_id' for now, as it causes FK issues And
312 // is not very important for now.
313 'modified_date' => date('YmdHis'),
315 CRM_Core_BAO_Log
::add($logParams);
327 public function checkVersion($version) {
328 $domainID = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Domain',
332 return $domainID ?
TRUE : FALSE;
339 public function getRevisionSequence() {
341 $sqlDir = implode(DIRECTORY_SEPARATOR
,
342 array(dirname(__FILE__
), 'Incremental', 'sql')
344 $sqlFiles = scandir($sqlDir);
346 $sqlFilePattern = '/^((\d{1,2}\.\d{1,2})\.(\d{1,2}\.)?(\d{1,2}|\w{4,7}))\.(my)?sql(\.tpl)?$/i';
347 foreach ($sqlFiles as $file) {
348 if (preg_match($sqlFilePattern, $file, $matches)) {
349 if ($matches[2] == '4.0') {
350 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."));
352 if (!in_array($matches[1], $revList)) {
353 $revList[] = $matches[1];
360 '2.1.0', '2.2.beta2', '2.2.beta1', '2.2.alpha1', */
362 /* '2.2.alpha3', '2.2.0', '2.2.2', '2.1.alpha1', '2.1.3'); */
365 usort($revList, 'version_compare');
375 public static function getRevisionPart($rev, $index = 1) {
376 $revPattern = '/^((\d{1,2})\.\d{1,2})\.(\d{1,2}|\w{4,7})?$/i';
377 preg_match($revPattern, $rev, $matches);
379 return array_key_exists($index, $matches) ?
$matches[$index] : NULL;
388 public function processLocales($tplFile, $rev) {
389 $smarty = CRM_Core_Smarty
::singleton();
390 $smarty->assign('domainID', CRM_Core_Config
::domainID());
392 $this->source($smarty->fetch($tplFile), TRUE);
394 if ($this->multilingual
) {
395 CRM_Core_I18n_Schema
::rebuildMultilingualSchema($this->locales
, $rev);
397 return $this->multilingual
;
403 public function setSchemaStructureTables($rev) {
404 if ($this->multilingual
) {
405 CRM_Core_I18n_Schema
::schemaStructureTables($rev, TRUE);
414 public function processSQL($rev) {
415 $sqlFile = implode(DIRECTORY_SEPARATOR
,
417 dirname(__FILE__
), 'Incremental',
418 'sql', $rev . '.mysql',
421 $tplFile = "$sqlFile.tpl";
423 if (file_exists($tplFile)) {
424 $this->processLocales($tplFile, $rev);
427 if (!file_exists($sqlFile)) {
428 CRM_Core_Error
::fatal("sqlfile - $rev.mysql not found.");
430 $this->source($sqlFile);
435 * Determine the start and end version of the upgrade process
437 * @return array(0=>$currentVer, 1=>$latestVer)
439 public function getUpgradeVersions() {
440 $latestVer = CRM_Utils_System
::version();
441 $currentVer = CRM_Core_BAO_Domain
::version(true);
443 CRM_Core_Error
::fatal(ts('Version information missing in civicrm database.'));
445 elseif (stripos($currentVer, 'upgrade')) {
446 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.'));
449 CRM_Core_Error
::fatal(ts('Version information missing in civicrm codebase.'));
452 // hack to make past ver compatible /w new incremental upgrade process
455 '2.2' => '2.2.alpha1',
456 '2.2.alph' => '2.2.alpha3',
457 // since 3.1.1 had domain.version set as 3.1.0
460 if (isset($convertVer[$currentVer])) {
461 $currentVer = $convertVer[$currentVer];
464 return array($currentVer, $latestVer);
468 * Determine if $currentVer can be upgraded to $latestVer
473 * @return mixed, a string error message or boolean 'false' if OK
475 public function checkUpgradeableVersion($currentVer, $latestVer) {
477 // since version is suppose to be in valid format at this point, especially after conversion ($convertVer),
478 // lets do a pattern check -
479 if (!CRM_Utils_System
::isVersionFormatValid($currentVer)) {
480 $error = ts('Database is marked with invalid version format. You may want to investigate this before you proceed further.');
482 elseif (version_compare($currentVer, $latestVer) > 0) {
483 // DB version number is higher than codebase being upgraded to. This is unexpected condition-fatal error.
484 $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.',
485 array(1 => $currentVer, 2 => $latestVer, 3 => $dbToolsLink)
488 elseif (version_compare($currentVer, $latestVer) == 0) {
489 $error = ts('Your database has already been upgraded to CiviCRM %1',
490 array(1 => $latestVer)
494 $phpVersion = phpversion();
495 $minPhpVersion = '5.3.3';
496 if (version_compare($phpVersion, $minPhpVersion) < 0) {
497 $error = ts('CiviCRM %3 requires PHP version %1 (or newer), but the current system uses %2 ',
505 // check for mysql trigger privileges
506 if (!CRM_Core_DAO
::checkTriggerViewPermission(FALSE, TRUE)) {
507 $error = ts('CiviCRM %1 requires MySQL trigger privileges.',
508 array(1 => $latestVer));
511 if (CRM_Core_DAO
::getGlobalSetting('thread_stack', 0) < (1024*self
::MINIMUM_THREAD_STACK
)) {
512 $error = ts('CiviCRM %1 requires MySQL thread stack >= %2k', array(
514 2 => self
::MINIMUM_THREAD_STACK
522 * Determine if $currentver already matches $latestVer
527 * @return mixed, a string error message or boolean 'false' if OK
529 public function checkCurrentVersion($currentVer, $latestVer) {
532 // since version is suppose to be in valid format at this point, especially after conversion ($convertVer),
533 // lets do a pattern check -
534 if (!CRM_Utils_System
::isVersionFormatValid($currentVer)) {
535 $error = ts('Database is marked with invalid version format. You may want to investigate this before you proceed further.');
537 elseif (version_compare($currentVer, $latestVer) != 0) {
538 $error = ts('Your database is not configured for version %1',
539 array(1 => $latestVer)
546 * Fill the queue with upgrade tasks
548 * @param $currentVer string, the original revision
549 * @param $latestVer string, the target (final) revision
550 * @param $postUpgradeMessageFile string, path of a modifiable file which lists the post-upgrade messages
554 public static function buildQueue($currentVer, $latestVer, $postUpgradeMessageFile) {
555 $upgrade = new CRM_Upgrade_Form();
557 // hack to make 4.0.x (D7,J1.6) codebase go through 3.4.x (d6, J1.5) upgrade files,
558 // since schema wise they are same
559 if (CRM_Upgrade_Form
::getRevisionPart($currentVer) == '4.0') {
560 $currentVer = str_replace('4.0.', '3.4.', $currentVer);
563 // Ensure that queue can be created
564 if (!CRM_Queue_BAO_QueueItem
::findCreateTable()) {
565 CRM_Core_Error
::fatal(ts('Failed to find or create queueing table'));
567 $queue = CRM_Queue_Service
::singleton()->create(array(
568 'name' => self
::QUEUE_NAME
,
573 $revisions = $upgrade->getRevisionSequence();
574 foreach ($revisions as $rev) {
575 // proceed only if $currentVer < $rev
576 if (version_compare($currentVer, $rev) < 0) {
577 $beginTask = new CRM_Queue_Task(
579 array('CRM_Upgrade_Form', 'doIncrementalUpgradeStart'),
582 "Begin Upgrade to $rev"
584 $queue->createItem($beginTask);
586 $task = new CRM_Queue_Task(
588 array('CRM_Upgrade_Form', 'doIncrementalUpgradeStep'),
590 array($rev, $currentVer, $latestVer, $postUpgradeMessageFile),
593 $queue->createItem($task);
595 $task = new CRM_Queue_Task(
597 array('CRM_Upgrade_Form', 'doIncrementalUpgradeFinish'),
599 array($rev, $currentVer, $latestVer, $postUpgradeMessageFile),
600 "Finish Upgrade DB to $rev"
602 $queue->createItem($task);
610 * Perform an incremental version update
612 * @param CRM_Queue_TaskContext $ctx
613 * @param $rev string, the target (intermediate) revision e.g '3.2.alpha1'
617 public static function doIncrementalUpgradeStart(CRM_Queue_TaskContext
$ctx, $rev) {
618 $upgrade = new CRM_Upgrade_Form();
620 // as soon as we start doing anything we append ".upgrade" to version.
621 // this also helps detect any partial upgrade issues
622 $upgrade->setVersion($rev . '.upgrade');
628 * Perform an incremental version update
630 * @param CRM_Queue_TaskContext $ctx
631 * @param $rev string, the target (intermediate) revision e.g '3.2.alpha1'
632 * @param $originalVer string, the original revision
633 * @param $latestVer string, the target (final) revision
634 * @param $postUpgradeMessageFile string, path of a modifiable file which lists the post-upgrade messages
638 public static function doIncrementalUpgradeStep(CRM_Queue_TaskContext
$ctx, $rev, $originalVer, $latestVer, $postUpgradeMessageFile) {
639 $upgrade = new CRM_Upgrade_Form();
641 $phpFunctionName = 'upgrade_' . str_replace('.', '_', $rev);
643 $versionObject = $upgrade->incrementalPhpObject($rev);
645 // pre-db check for major release.
646 if ($upgrade->checkVersionRelease($rev, 'alpha1')) {
647 if (!(is_callable(array(
648 $versionObject, 'verifyPreDBstate')))) {
649 CRM_Core_Error
::fatal("verifyPreDBstate method was not found for $rev");
653 if (!($versionObject->verifyPreDBstate($error))) {
654 if (!isset($error)) {
655 $error = "post-condition failed for current upgrade for $rev";
657 CRM_Core_Error
::fatal($error);
662 $upgrade->setSchemaStructureTables($rev);
664 if (is_callable(array(
665 $versionObject, $phpFunctionName))) {
666 $versionObject->$phpFunctionName($rev, $originalVer, $latestVer);
669 $upgrade->processSQL($rev);
672 // set post-upgrade-message if any
673 if (is_callable(array(
674 $versionObject, 'setPostUpgradeMessage'))) {
675 $postUpgradeMessage = file_get_contents($postUpgradeMessageFile);
676 $versionObject->setPostUpgradeMessage($postUpgradeMessage, $rev);
677 file_put_contents($postUpgradeMessageFile, $postUpgradeMessage);
679 $postUpgradeMessage = file_get_contents($postUpgradeMessageFile);
680 CRM_Upgrade_Incremental_Legacy
::setPostUpgradeMessage($postUpgradeMessage, $rev);
681 file_put_contents($postUpgradeMessageFile, $postUpgradeMessage);
688 * Perform an incremental version update
690 * @param CRM_Queue_TaskContext $ctx
691 * @param $rev string, the target (intermediate) revision e.g '3.2.alpha1'
692 * @param $currentVer string, the original revision
693 * @param $latestVer string, the target (final) revision
694 * @param $postUpgradeMessageFile string, path of a modifiable file which lists the post-upgrade messages
698 public static function doIncrementalUpgradeFinish(CRM_Queue_TaskContext
$ctx, $rev, $currentVer, $latestVer, $postUpgradeMessageFile) {
699 $upgrade = new CRM_Upgrade_Form();
700 $upgrade->setVersion($rev);
701 CRM_Utils_System
::flushCache();
703 $config = CRM_Core_Config
::singleton();
704 $config->userSystem
->flush();
708 public static function doFinish() {
709 $upgrade = new CRM_Upgrade_Form();
710 list($ignore, $latestVer) = $upgrade->getUpgradeVersions();
711 // Seems extraneous in context, but we'll preserve old behavior
712 $upgrade->setVersion($latestVer);
714 // lets rebuild the config array in case we've made a few changes in the
716 // this also helps us always store the latest version of civi in the DB
718 CRM_Core_BAO_ConfigSetting
::add($params);
720 // CRM-12804 comment-51411 : add any missing settings
721 // at the end of upgrade
722 CRM_Core_BAO_Setting
::updateSettingsFromMetaData();
724 // cleanup caches CRM-8739
725 $config = CRM_Core_Config
::singleton();
726 $config->cleanupCaches(1);
728 // Rebuild all triggers and re-enable logging if needed
729 $logging = new CRM_Logging_Schema();
730 $logging->fixSchemaDifferences();
734 * Compute any messages which should be displayed before upgrade
735 * by calling the 'setPreUpgradeMessage' on each incremental upgrade
738 * @param $preUpgradeMessage string, alterable
742 public function setPreUpgradeMessage(&$preUpgradeMessage, $currentVer, $latestVer) {
743 CRM_Upgrade_Incremental_Legacy
::setPreUpgradeMessage($preUpgradeMessage, $currentVer, $latestVer);
745 // Scan through all php files and see if any file is interested in setting pre-upgrade-message
746 // based on $currentVer, $latestVer.
747 // Please note, at this point upgrade hasn't started executing queries.
748 $revisions = $this->getRevisionSequence();
749 foreach ($revisions as $rev) {
750 if (version_compare($currentVer, $rev) < 0 &&
751 version_compare($rev, '3.2.alpha1') > 0
753 $versionObject = $this->incrementalPhpObject($rev);
754 if (is_callable(array(
755 $versionObject, 'setPreUpgradeMessage'))) {
756 $versionObject->setPreUpgradeMessage($preUpgradeMessage, $rev, $currentVer);