Merge pull request #2347 from lcdservices/CRM-14062
[civicrm-core.git] / CRM / Upgrade / Form.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
232624b1 4 | CiviCRM version 4.4 |
6a488035
TO
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26*/
27
28/**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2013
32 * $Id$
33 *
34 */
35class CRM_Upgrade_Form extends CRM_Core_Form {
36 CONST QUEUE_NAME = 'CRM_Upgrade';
37
38 /**
39 * Minimum size of MySQL's thread_stack option
40 *
41 * @see install/index.php MINIMUM_THREAD_STACK
42 */
43 const MINIMUM_THREAD_STACK = 192;
44
45 protected $_config;
46
47 // note latestVersion is legacy code, and
48 // only used for 2.0 -> 2.1 upgrade
49 public $latestVersion;
50
51 /**
52 * Upgrade for multilingual
53 *
54 * @var boolean
55 * @public
56 */
57 public $multilingual = FALSE;
58
59 /**
60 * locales available for multilingual upgrade
61 *
62 * @var array
63 * @public
64 */
65 public $locales;
66
67 /**
68 * number to string mapper
69 *
70 * @var array
71 * @public
72 */
73 static $_numberMap = array(
74 0 => 'Zero',
75 1 => 'One',
76 2 => 'Two',
77 3 => 'Three',
78 4 => 'Four',
79 5 => 'Five',
80 6 => 'Fix',
81 7 => 'Seven',
82 8 => 'Eight',
83 9 => 'Nine',
84 );
85
86 function __construct($state = NULL,
87 $action = CRM_Core_Action::NONE,
88 $method = 'post',
89 $name = NULL
90 ) {
91 $this->_config = CRM_Core_Config::singleton();
92
93 // this->latestVersion is legacy code, only used for 2.0 -> 2.1 upgrade
94 // latest ver in 2.1 series
95 $this->latestVersion = '2.1.6';
96
97 $domain = new CRM_Core_DAO_Domain();
98 $domain->find(TRUE);
99
100 $this->multilingual = (bool) $domain->locales;
101 $this->locales = explode(CRM_Core_DAO::VALUE_SEPARATOR, $domain->locales);
102
103 $smarty = CRM_Core_Smarty::singleton();
104 $smarty->compile_dir = $this->_config->templateCompileDir;
105 $smarty->assign('multilingual', $this->multilingual);
106 $smarty->assign('locales', $this->locales);
107
108 // we didn't call CRM_Core_BAO_ConfigSetting::retrieve(), so we need to set $dbLocale by hand
109 if ($this->multilingual) {
110 global $dbLocale;
111 $dbLocale = "_{$this->_config->lcMessages}";
112 }
113
114 parent::__construct($state, $action, $method, $name);
115 }
116
117 static function &incrementalPhpObject($version) {
118 static $incrementalPhpObject = array();
119
120 $versionParts = explode('.', $version);
121 $versionName = self::$_numberMap[$versionParts[0]] . self::$_numberMap[$versionParts[1]];
122
123 if (!array_key_exists($versionName, $incrementalPhpObject)) {
0e6e8724 124 $className = "CRM_Upgrade_Incremental_php_{$versionName}";
e8cb3963 125 $incrementalPhpObject[$versionName] = new $className();
6a488035
TO
126 }
127 return $incrementalPhpObject[$versionName];
128 }
129
130 function checkVersionRelease($version, $release) {
131 $versionParts = explode('.', $version);
132 if ($versionParts[2] == $release) {
133 return TRUE;
134 }
135 return FALSE;
136 }
137
138 function checkSQLConstraints(&$constraints) {
139 $pass = $fail = 0;
140 foreach ($constraints as $constraint) {
141 if ($this->checkSQLConstraint($constraint)) {
142 $pass++;
143 }
144 else {
145 $fail++;
146 }
147 return array($pass, $fail);
148 }
149 }
150
151 function checkSQLConstraint($constraint) {
152 // check constraint here
153 return TRUE;
154 }
155
156 function source($fileName, $isQueryString = FALSE) {
157
158 CRM_Utils_File::sourceSQLFile($this->_config->dsn,
159 $fileName, NULL, $isQueryString
160 );
161 }
162
163 function preProcess() {
164 CRM_Utils_System::setTitle($this->getTitle());
165 if (!$this->verifyPreDBState($errorMessage)) {
166 if (!isset($errorMessage)) {
167 $errorMessage = 'pre-condition failed for current upgrade step';
168 }
169 CRM_Core_Error::fatal($errorMessage);
170 }
171 $this->assign('recentlyViewed', FALSE);
172 }
173
174 function buildQuickForm() {
175 $this->addDefaultButtons($this->getButtonTitle(),
176 'next',
177 NULL,
178 TRUE
179 );
180 }
181
182 function getTitle() {
183 return ts('Title not Set');
184 }
185
186 function getFieldsetTitle() {
187 return ts('');
188 }
189
190 function getButtonTitle() {
191 return ts('Continue');
192 }
193
194 function getTemplateFileName() {
195 $this->assign('title',
196 $this->getFieldsetTitle()
197 );
198 $this->assign('message',
199 $this->getTemplateMessage()
200 );
201 return 'CRM/Upgrade/Base.tpl';
202 }
203
204 function postProcess() {
205 $this->upgrade();
206
207 if (!$this->verifyPostDBState($errorMessage)) {
208 if (!isset($errorMessage)) {
209 $errorMessage = 'post-condition failed for current upgrade step';
210 }
211 CRM_Core_Error::fatal($errorMessage);
212 }
213 }
214
215 function runQuery($query) {
216 return CRM_Core_DAO::executeQuery($query,
217 CRM_Core_DAO::$_nullArray
218 );
219 }
220
221 function setVersion($version) {
222 $this->logVersion($version);
223
224 $query = "
225UPDATE civicrm_domain
226SET version = '$version'
227";
228 return $this->runQuery($query);
229 }
230
231 function logVersion($newVersion) {
232 if ($newVersion) {
233 $oldVersion = CRM_Core_BAO_Domain::version();
234
235 $session = CRM_Core_Session::singleton();
236 $logParams = array(
237 'entity_table' => 'civicrm_domain',
238 'entity_id' => 1,
239 'data' => "upgrade:{$oldVersion}->{$newVersion}",
240 // lets skip 'modified_id' for now, as it causes FK issues And
241 // is not very important for now.
242 'modified_date' => date('YmdHis'),
243 );
244 CRM_Core_BAO_Log::add($logParams);
245 return TRUE;
246 }
247
248 return FALSE;
249 }
250
251 function checkVersion($version) {
252 $domainID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Domain',
253 $version, 'id',
254 'version'
255 );
256 return $domainID ? TRUE : FALSE;
257 }
258
259 function getRevisionSequence() {
260 $revList = array();
261 $sqlDir = implode(DIRECTORY_SEPARATOR,
262 array(dirname(__FILE__), 'Incremental', 'sql')
263 );
264 $sqlFiles = scandir($sqlDir);
265
266 $sqlFilePattern = '/^((\d{1,2}\.\d{1,2})\.(\d{1,2}\.)?(\d{1,2}|\w{4,7}))\.(my)?sql(\.tpl)?$/i';
267 foreach ($sqlFiles as $file) {
268 if (preg_match($sqlFilePattern, $file, $matches)) {
269 if ($matches[2] == '4.0') {
270 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."));
271 }
272 if (!in_array($matches[1], $revList)) {
273 $revList[] = $matches[1];
274 }
275 }
276 }
277
278 // sample test list
279 /* $revList = array(
280 '2.1.0', '2.2.beta2', '2.2.beta1', '2.2.alpha1', */
281
282 /* '2.2.alpha3', '2.2.0', '2.2.2', '2.1.alpha1', '2.1.3'); */
283
284
285 usort($revList, 'version_compare');
286 return $revList;
287 }
288
289 static function getRevisionPart($rev, $index = 1) {
290 $revPattern = '/^((\d{1,2})\.\d{1,2})\.(\d{1,2}|\w{4,7})?$/i';
291 preg_match($revPattern, $rev, $matches);
292
293 return array_key_exists($index, $matches) ? $matches[$index] : NULL;
294 }
295
296 function processLocales($tplFile, $rev) {
297 $smarty = CRM_Core_Smarty::singleton();
298 $smarty->assign('domainID', CRM_Core_Config::domainID());
299
300 $this->source($smarty->fetch($tplFile), TRUE);
301
302 if ($this->multilingual) {
303 CRM_Core_I18n_Schema::rebuildMultilingualSchema($this->locales, $rev);
304 }
305 return $this->multilingual;
306 }
307
308 function setSchemaStructureTables($rev) {
309 if ($this->multilingual) {
310 CRM_Core_I18n_Schema::schemaStructureTables($rev, TRUE);
311 }
312 }
313
314 function processSQL($rev) {
315 $sqlFile = implode(DIRECTORY_SEPARATOR,
316 array(
317 dirname(__FILE__), 'Incremental',
318 'sql', $rev . '.mysql',
319 )
320 );
321 $tplFile = "$sqlFile.tpl";
322
323 if (file_exists($tplFile)) {
324 $this->processLocales($tplFile, $rev);
325 }
326 else {
327 if (!file_exists($sqlFile)) {
328 CRM_Core_Error::fatal("sqlfile - $rev.mysql not found.");
329 }
330 $this->source($sqlFile);
331 }
332 }
333
334 /**
335 * Determine the start and end version of the upgrade process
336 *
337 * @return array(0=>$currentVer, 1=>$latestVer)
338 */
339 function getUpgradeVersions() {
340 $latestVer = CRM_Utils_System::version();
341 $currentVer = CRM_Core_BAO_Domain::version(true);
342 if (!$currentVer) {
343 CRM_Core_Error::fatal(ts('Version information missing in civicrm database.'));
344 }
345 elseif (stripos($currentVer, 'upgrade')) {
346 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.'));
347 }
348 if (!$latestVer) {
349 CRM_Core_Error::fatal(ts('Version information missing in civicrm codebase.'));
350 }
351
352 // hack to make past ver compatible /w new incremental upgrade process
353 $convertVer = array(
354 '2.1' => '2.1.0',
355 '2.2' => '2.2.alpha1',
356 '2.2.alph' => '2.2.alpha3',
357 // since 3.1.1 had domain.version set as 3.1.0
358 '3.1.0' => '3.1.1',
359 );
360 if (isset($convertVer[$currentVer])) {
361 $currentVer = $convertVer[$currentVer];
362 }
363
364 return array($currentVer, $latestVer);
365 }
366
367 /**
368 * Determine if $currentVer can be upgraded to $latestVer
369 *
370 * @return mixed, a string error message or boolean 'false' if OK
371 */
372 function checkUpgradeableVersion($currentVer, $latestVer) {
373 $error = FALSE;
374 // since version is suppose to be in valid format at this point, especially after conversion ($convertVer),
375 // lets do a pattern check -
376 if (!CRM_Utils_System::isVersionFormatValid($currentVer)) {
377 $error = ts('Database is marked with invalid version format. You may want to investigate this before you proceed further.');
378 }
379 elseif (version_compare($currentVer, $latestVer) > 0) {
380 // DB version number is higher than codebase being upgraded to. This is unexpected condition-fatal error.
381 $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.',
382 array(1 => $currentVer, 2 => $latestVer, 3 => $dbToolsLink)
383 );
384 }
385 elseif (version_compare($currentVer, $latestVer) == 0) {
386 $error = ts('Your database has already been upgraded to CiviCRM %1',
387 array(1 => $latestVer)
388 );
389 }
390
391 $phpVersion = phpversion();
392 $minPhpVersion = '5.3.3';
ac05cde3 393 if (version_compare($phpVersion, $minPhpVersion) < 0) {
6a488035
TO
394 $error = ts('CiviCRM %3 requires PHP version %1 (or newer), but the current system uses %2 ',
395 array(
396 1 => $minPhpVersion,
397 2 => $phpVersion,
10a5be27 398 3 => $latestVer
6a488035
TO
399 ));
400 }
401
402 // check for mysql trigger privileges
403 if (!CRM_Core_DAO::checkTriggerViewPermission(FALSE, TRUE)) {
404 $error = ts('CiviCRM %1 requires MySQL trigger privileges.',
405 array(1 => $latestVer));
406 }
032c9d10
TO
407
408 if (CRM_Core_DAO::getGlobalSetting('thread_stack', 0) < (1024*self::MINIMUM_THREAD_STACK)) {
6a488035
TO
409 $error = ts('CiviCRM %1 requires MySQL thread stack >= %2k', array(
410 1 => $latestVer,
10a5be27 411 2 => self::MINIMUM_THREAD_STACK
6a488035
TO
412 ));
413 }
414
415 return $error;
416 }
417
418 /**
419 * Determine if $currentver already matches $latestVer
420 *
421 * @return mixed, a string error message or boolean 'false' if OK
422 */
423 function checkCurrentVersion($currentVer, $latestVer) {
424 $error = FALSE;
425
426 // since version is suppose to be in valid format at this point, especially after conversion ($convertVer),
427 // lets do a pattern check -
428 if (!CRM_Utils_System::isVersionFormatValid($currentVer)) {
429 $error = ts('Database is marked with invalid version format. You may want to investigate this before you proceed further.');
430 }
431 elseif (version_compare($currentVer, $latestVer) != 0) {
432 $error = ts('Your database is not configured for version %1',
433 array(1 => $latestVer)
434 );
435 }
436 return $error;
437 }
438
439 /**
440 * Fill the queue with upgrade tasks
441 *
442 * @param $currentVer string, the original revision
443 * @param $latestVer string, the target (final) revision
444 * @param $postUpgradeMessageFile string, path of a modifiable file which lists the post-upgrade messages
445 *
446 * @return CRM_Queue
447 */
448 static function buildQueue($currentVer, $latestVer, $postUpgradeMessageFile) {
449 $upgrade = new CRM_Upgrade_Form();
450
451 // hack to make 4.0.x (D7,J1.6) codebase go through 3.4.x (d6, J1.5) upgrade files,
452 // since schema wise they are same
453 if (CRM_Upgrade_Form::getRevisionPart($currentVer) == '4.0') {
454 $currentVer = str_replace('4.0.', '3.4.', $currentVer);
455 }
456
457 // Ensure that queue can be created
458 if (!CRM_Queue_BAO_QueueItem::findCreateTable()) {
459 CRM_Core_Error::fatal(ts('Failed to find or create queueing table'));
460 }
461 $queue = CRM_Queue_Service::singleton()->create(array(
462 'name' => self::QUEUE_NAME,
463 'type' => 'Sql',
464 'reset' => TRUE,
465 ));
466
467 $revisions = $upgrade->getRevisionSequence();
468 foreach ($revisions as $rev) {
469 // proceed only if $currentVer < $rev
470 if (version_compare($currentVer, $rev) < 0) {
471 $beginTask = new CRM_Queue_Task(
472 // callback
473 array('CRM_Upgrade_Form', 'doIncrementalUpgradeStart'),
474 // arguments
475 array($rev),
476 "Begin Upgrade to $rev"
477 );
478 $queue->createItem($beginTask);
479
480 $task = new CRM_Queue_Task(
481 // callback
482 array('CRM_Upgrade_Form', 'doIncrementalUpgradeStep'),
483 // arguments
484 array($rev, $currentVer, $latestVer, $postUpgradeMessageFile),
485 "Upgrade DB to $rev"
486 );
487 $queue->createItem($task);
488
489 $task = new CRM_Queue_Task(
490 // callback
491 array('CRM_Upgrade_Form', 'doIncrementalUpgradeFinish'),
492 // arguments
3373fe5e 493 array($rev, $currentVer, $latestVer, $postUpgradeMessageFile),
6a488035
TO
494 "Finish Upgrade DB to $rev"
495 );
496 $queue->createItem($task);
497 }
498 }
499
500 return $queue;
501 }
502
503 /**
504 * Perform an incremental version update
505 *
506 * @param $rev string, the target (intermediate) revision e.g '3.2.alpha1'
507 * @param $currentVer string, the original revision
508 * @param $latestVer string, the target (final) revision
509 * @param $postUpgradeMessageFile string, path of a modifiable file which lists the post-upgrade messages
510 */
511 static function doIncrementalUpgradeStart(CRM_Queue_TaskContext $ctx, $rev) {
512 $upgrade = new CRM_Upgrade_Form();
513
514 // as soon as we start doing anything we append ".upgrade" to version.
515 // this also helps detect any partial upgrade issues
516 $upgrade->setVersion($rev . '.upgrade');
517
518 return TRUE;
519 }
520
521 /**
522 * Perform an incremental version update
523 *
524 * @param $rev string, the target (intermediate) revision e.g '3.2.alpha1'
525 * @param $currentVer string, the original revision
526 * @param $latestVer string, the target (final) revision
527 * @param $postUpgradeMessageFile string, path of a modifiable file which lists the post-upgrade messages
528 */
529 static function doIncrementalUpgradeStep(CRM_Queue_TaskContext$ctx, $rev, $currentVer, $latestVer, $postUpgradeMessageFile) {
530 $upgrade = new CRM_Upgrade_Form();
531
532 $phpFunctionName = 'upgrade_' . str_replace('.', '_', $rev);
533
534 // follow old upgrade process for all version
535 // below 3.2.alpha1
536 if (version_compare($rev, '3.2.alpha1') < 0) {
537 if (is_callable(array(
538 'CRM_Upgrade_Incremental_Legacy', $phpFunctionName))) {
539 call_user_func(array('CRM_Upgrade_Incremental_Legacy', $phpFunctionName), $rev);
540 }
541 else {
542 $upgrade->processSQL($rev);
543 }
544 }
545 else {
546 // new upgrade process from version
547 // 3.2.alpha1
548 $versionObject = $upgrade->incrementalPhpObject($rev);
549
550 // pre-db check for major release.
551 if ($upgrade->checkVersionRelease($rev, 'alpha1')) {
552 if (!(is_callable(array(
553 $versionObject, 'verifyPreDBstate')))) {
554 CRM_Core_Error::fatal("verifyPreDBstate method was not found for $rev");
555 }
556
557 $error = NULL;
558 if (!($versionObject->verifyPreDBstate($error))) {
559 if (!isset($error)) {
560 $error = "post-condition failed for current upgrade for $rev";
561 }
562 CRM_Core_Error::fatal($error);
563 }
564
565 }
566
567 $upgrade->setSchemaStructureTables($rev);
568
569 if (is_callable(array(
570 $versionObject, $phpFunctionName))) {
571 $versionObject->$phpFunctionName($rev);
572 }
573 else {
574 $upgrade->processSQL($rev);
575 }
576
577 // set post-upgrade-message if any
578 if (is_callable(array(
579 $versionObject, 'setPostUpgradeMessage'))) {
580 $postUpgradeMessage = file_get_contents($postUpgradeMessageFile);
581 $versionObject->setPostUpgradeMessage($postUpgradeMessage, $rev);
582 file_put_contents($postUpgradeMessageFile, $postUpgradeMessage);
583 } else {
584 $postUpgradeMessage = file_get_contents($postUpgradeMessageFile);
585 CRM_Upgrade_Incremental_Legacy::setPostUpgradeMessage($postUpgradeMessage, $rev);
586 file_put_contents($postUpgradeMessageFile, $postUpgradeMessage);
587 }
588 }
589
590 return TRUE;
591 }
592
593 /**
594 * Perform an incremental version update
595 *
596 * @param $rev string, the target (intermediate) revision e.g '3.2.alpha1'
597 * @param $currentVer string, the original revision
598 * @param $latestVer string, the target (final) revision
599 * @param $postUpgradeMessageFile string, path of a modifiable file which lists the post-upgrade messages
600 */
3373fe5e 601 static function doIncrementalUpgradeFinish(CRM_Queue_TaskContext $ctx, $rev, $currentVer, $latestVer, $postUpgradeMessageFile) {
6a488035
TO
602 $upgrade = new CRM_Upgrade_Form();
603 $upgrade->setVersion($rev);
604 CRM_Utils_System::flushCache();
ac05cde3 605
d8a4acc0
C
606 $config = CRM_Core_Config::singleton();
607 $config->userSystem->flush();
6a488035
TO
608 return TRUE;
609 }
610
611 static function doFinish() {
612 $upgrade = new CRM_Upgrade_Form();
613 list($ignore, $latestVer) = $upgrade->getUpgradeVersions();
614 // Seems extraneous in context, but we'll preserve old behavior
615 $upgrade->setVersion($latestVer);
616
b597d0b1
DL
617 // lets rebuild the config array in case we've made a few changes in the
618 // code base
619 // this also helps us always store the latest version of civi in the DB
620 $params = array();
621 CRM_Core_BAO_ConfigSetting::add($params);
622
b6386d8c
PJ
623 // CRM-12804 comment-51411 : add any missing settings
624 // at the end of upgrade
625 CRM_Core_BAO_Setting::updateSettingsFromMetaData();
626
6a488035
TO
627 // cleanup caches CRM-8739
628 $config = CRM_Core_Config::singleton();
1fcf16cc 629 $config->cleanupCaches(1);
6a488035
TO
630
631 // Rebuild all triggers and re-enable logging if needed
632 $logging = new CRM_Logging_Schema();
633 $logging->fixSchemaDifferences();
634 }
635
636 /**
637 * Compute any messages which should be displayed before upgrade
638 * by calling the 'setPreUpgradeMessage' on each incremental upgrade
639 * object.
640 *
641 * @param $preUpgradeMessage string, alterable
642 */
643 function setPreUpgradeMessage(&$preUpgradeMessage, $currentVer, $latestVer) {
644 CRM_Upgrade_Incremental_Legacy::setPreUpgradeMessage($preUpgradeMessage, $currentVer, $latestVer);
645
646 // Scan through all php files and see if any file is interested in setting pre-upgrade-message
647 // based on $currentVer, $latestVer.
648 // Please note, at this point upgrade hasn't started executing queries.
649 $revisions = $this->getRevisionSequence();
650 foreach ($revisions as $rev) {
651 if (version_compare($currentVer, $rev) < 0 &&
652 version_compare($rev, '3.2.alpha1') > 0
653 ) {
654 $versionObject = $this->incrementalPhpObject($rev);
655 if (is_callable(array(
656 $versionObject, 'setPreUpgradeMessage'))) {
657 $versionObject->setPreUpgradeMessage($preUpgradeMessage, $rev, $currentVer);
658 }
659 }
660 }
661 }
662}