Merge pull request #17940 from eileenmcnaughton/abort
[civicrm-core.git] / CRM / Upgrade / Form.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
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 |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035
TO
11
12/**
016d95d3 13 * Class CRM_Upgrade_Form
6a488035
TO
14 */
15class CRM_Upgrade_Form extends CRM_Core_Form {
7da04cde 16 const QUEUE_NAME = 'CRM_Upgrade';
6a488035
TO
17
18 /**
19 * Minimum size of MySQL's thread_stack option
20 *
21 * @see install/index.php MINIMUM_THREAD_STACK
22 */
23 const MINIMUM_THREAD_STACK = 192;
24
304c1a5a
CW
25 /**
26 * Minimum previous CiviCRM version we can directly upgrade from
27 */
fdc2e63a 28 const MINIMUM_UPGRADABLE_VERSION = '4.4.7';
304c1a5a 29
3655bea4
SL
30 /**
31 * @var \CRM_Core_Config
32 */
6a488035
TO
33 protected $_config;
34
6a488035 35 /**
fe482240 36 * Upgrade for multilingual.
6a488035 37 *
b67daa72 38 * @var bool
6a488035
TO
39 */
40 public $multilingual = FALSE;
41
42 /**
fe482240 43 * Locales available for multilingual upgrade.
6a488035
TO
44 *
45 * @var array
6a488035
TO
46 */
47 public $locales;
48
624e56fa 49 /**
fe482240 50 * Constructor for the basic form page.
624e56fa
EM
51 *
52 * We should not use QuickForm directly. This class provides a lot
53 * of default convenient functions, rules and buttons
54 *
c68f8bfa
TO
55 * @param object $state
56 * State associated with this form.
e8e8f3ad 57 * @param const|\enum|int $action The mode the form is operating in (None/Create/View/Update/Delete)
c68f8bfa
TO
58 * @param string $method
59 * The type of http method used (GET/POST).
60 * @param string $name
61 * The name of the form if different from class name.
624e56fa 62 */
ae5ffbb7 63 public function __construct(
4e66d748 64 $state = NULL,
6a488035
TO
65 $action = CRM_Core_Action::NONE,
66 $method = 'post',
e418776c 67 $name = NULL
6a488035
TO
68 ) {
69 $this->_config = CRM_Core_Config::singleton();
70
394d18d3 71 $locales = CRM_Core_I18n::getMultilingual();
6a488035 72
394d18d3
CW
73 $this->multilingual = (bool) $locales;
74 $this->locales = $locales;
6a488035
TO
75
76 $smarty = CRM_Core_Smarty::singleton();
635f0b86 77 //$smarty->compile_dir = $this->_config->templateCompileDir;
6a488035
TO
78 $smarty->assign('multilingual', $this->multilingual);
79 $smarty->assign('locales', $this->locales);
80
81 // we didn't call CRM_Core_BAO_ConfigSetting::retrieve(), so we need to set $dbLocale by hand
82 if ($this->multilingual) {
83 global $dbLocale;
84 $dbLocale = "_{$this->_config->lcMessages}";
85 }
86
87 parent::__construct($state, $action, $method, $name);
88 }
89
624e56fa
EM
90 /**
91 * @param $version
92 *
93 * @return mixed
94 */
00be9182 95 public static function &incrementalPhpObject($version) {
be2fb01f 96 static $incrementalPhpObject = [];
6a488035
TO
97
98 $versionParts = explode('.', $version);
0ae8b1af 99 $versionName = CRM_Utils_EnglishNumber::toCamelCase($versionParts[0]) . CRM_Utils_EnglishNumber::toCamelCase($versionParts[1]);
6a488035
TO
100
101 if (!array_key_exists($versionName, $incrementalPhpObject)) {
0e6e8724 102 $className = "CRM_Upgrade_Incremental_php_{$versionName}";
e8cb3963 103 $incrementalPhpObject[$versionName] = new $className();
6a488035
TO
104 }
105 return $incrementalPhpObject[$versionName];
106 }
107
624e56fa
EM
108 /**
109 * @param $version
110 * @param $release
111 *
112 * @return bool
113 */
00be9182 114 public function checkVersionRelease($version, $release) {
6a488035 115 $versionParts = explode('.', $version);
bf6a5362 116 return ($versionParts[2] == $release);
6a488035
TO
117 }
118
624e56fa
EM
119 /**
120 * @param $constraints
121 *
122 * @return array
123 */
00be9182 124 public function checkSQLConstraints(&$constraints) {
6a488035
TO
125 $pass = $fail = 0;
126 foreach ($constraints as $constraint) {
127 if ($this->checkSQLConstraint($constraint)) {
128 $pass++;
129 }
130 else {
131 $fail++;
132 }
be2fb01f 133 return [$pass, $fail];
6a488035
TO
134 }
135 }
136
624e56fa
EM
137 /**
138 * @param $constraint
139 *
140 * @return bool
141 */
00be9182 142 public function checkSQLConstraint($constraint) {
6a488035
TO
143 // check constraint here
144 return TRUE;
145 }
146
624e56fa 147 /**
100fef9d 148 * @param string $fileName
624e56fa
EM
149 * @param bool $isQueryString
150 */
00be9182 151 public function source($fileName, $isQueryString = FALSE) {
c0e4c31d
JK
152 if ($isQueryString) {
153 CRM_Utils_File::runSqlQuery($this->_config->dsn,
154 $fileName, NULL
155 );
156 }
157 else {
158 CRM_Utils_File::sourceSQLFile($this->_config->dsn,
159 $fileName, NULL
160 );
161 }
6a488035
TO
162 }
163
00be9182 164 public function preProcess() {
6a488035
TO
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';
169 }
800dad43 170 throw new CRM_Core_Exception($errorMessage);
6a488035
TO
171 }
172 $this->assign('recentlyViewed', FALSE);
173 }
174
00be9182 175 public function buildQuickForm() {
6a488035
TO
176 $this->addDefaultButtons($this->getButtonTitle(),
177 'next',
178 NULL,
179 TRUE
180 );
181 }
182
624e56fa 183 /**
100fef9d 184 * Getter function for title. Should be over-ridden by derived class
624e56fa
EM
185 *
186 * @return string
624e56fa 187 */
3655bea4 188
624e56fa
EM
189 /**
190 * @return string
191 */
00be9182 192 public function getTitle() {
6a488035
TO
193 return ts('Title not Set');
194 }
195
624e56fa
EM
196 /**
197 * @return string
198 */
00be9182 199 public function getFieldsetTitle() {
ba8f6a69 200 return '';
6a488035
TO
201 }
202
624e56fa
EM
203 /**
204 * @return string
205 */
00be9182 206 public function getButtonTitle() {
6a488035
TO
207 return ts('Continue');
208 }
209
624e56fa 210 /**
fe482240 211 * Use the form name to create the tpl file name.
624e56fa
EM
212 *
213 * @return string
624e56fa 214 */
3655bea4 215
624e56fa
EM
216 /**
217 * @return string
218 */
00be9182 219 public function getTemplateFileName() {
6a488035
TO
220 $this->assign('title',
221 $this->getFieldsetTitle()
222 );
223 $this->assign('message',
224 $this->getTemplateMessage()
225 );
226 return 'CRM/Upgrade/Base.tpl';
227 }
228
00be9182 229 public function postProcess() {
6a488035
TO
230 $this->upgrade();
231
232 if (!$this->verifyPostDBState($errorMessage)) {
233 if (!isset($errorMessage)) {
234 $errorMessage = 'post-condition failed for current upgrade step';
235 }
800dad43 236 throw new CRM_Core_Exception($errorMessage);
6a488035
TO
237 }
238 }
239
624e56fa
EM
240 /**
241 * @param $query
242 *
243 * @return Object
244 */
00be9182 245 public function runQuery($query) {
e03e1641 246 return CRM_Core_DAO::executeQuery($query);
6a488035
TO
247 }
248
624e56fa
EM
249 /**
250 * @param $version
251 *
252 * @return Object
253 */
00be9182 254 public function setVersion($version) {
6a488035
TO
255 $this->logVersion($version);
256
257 $query = "
258UPDATE civicrm_domain
259SET version = '$version'
260";
261 return $this->runQuery($query);
262 }
263
624e56fa
EM
264 /**
265 * @param $newVersion
266 *
267 * @return bool
268 */
00be9182 269 public function logVersion($newVersion) {
6a488035
TO
270 if ($newVersion) {
271 $oldVersion = CRM_Core_BAO_Domain::version();
272
273 $session = CRM_Core_Session::singleton();
be2fb01f 274 $logParams = [
6a488035
TO
275 'entity_table' => 'civicrm_domain',
276 'entity_id' => 1,
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'),
be2fb01f 281 ];
6a488035
TO
282 CRM_Core_BAO_Log::add($logParams);
283 return TRUE;
284 }
285
286 return FALSE;
287 }
288
624e56fa
EM
289 /**
290 * @param $version
291 *
292 * @return bool
293 */
00be9182 294 public function checkVersion($version) {
6a488035
TO
295 $domainID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Domain',
296 $version, 'id',
297 'version'
298 );
f7dbf5d9 299 return (bool) $domainID;
6a488035
TO
300 }
301
624e56fa
EM
302 /**
303 * @return array
304 * @throws Exception
305 */
00be9182 306 public function getRevisionSequence() {
be2fb01f 307 $revList = [];
6a488035 308 $sqlDir = implode(DIRECTORY_SEPARATOR,
be2fb01f 309 [dirname(__FILE__), 'Incremental', 'sql']
6a488035
TO
310 );
311 $sqlFiles = scandir($sqlDir);
312
313 $sqlFilePattern = '/^((\d{1,2}\.\d{1,2})\.(\d{1,2}\.)?(\d{1,2}|\w{4,7}))\.(my)?sql(\.tpl)?$/i';
314 foreach ($sqlFiles as $file) {
315 if (preg_match($sqlFilePattern, $file, $matches)) {
6a488035
TO
316 if (!in_array($matches[1], $revList)) {
317 $revList[] = $matches[1];
318 }
319 }
320 }
321
6a488035
TO
322 usort($revList, 'version_compare');
323 return $revList;
324 }
325
624e56fa
EM
326 /**
327 * @param $rev
328 * @param int $index
329 *
330 * @return null
331 */
00be9182 332 public static function getRevisionPart($rev, $index = 1) {
6a488035
TO
333 $revPattern = '/^((\d{1,2})\.\d{1,2})\.(\d{1,2}|\w{4,7})?$/i';
334 preg_match($revPattern, $rev, $matches);
335
336 return array_key_exists($index, $matches) ? $matches[$index] : NULL;
337 }
338
624e56fa
EM
339 /**
340 * @param $tplFile
341 * @param $rev
342 *
343 * @return bool
344 */
00be9182 345 public function processLocales($tplFile, $rev) {
6a488035
TO
346 $smarty = CRM_Core_Smarty::singleton();
347 $smarty->assign('domainID', CRM_Core_Config::domainID());
348
349 $this->source($smarty->fetch($tplFile), TRUE);
350
351 if ($this->multilingual) {
352 CRM_Core_I18n_Schema::rebuildMultilingualSchema($this->locales, $rev);
353 }
354 return $this->multilingual;
355 }
356
624e56fa
EM
357 /**
358 * @param $rev
359 */
00be9182 360 public function setSchemaStructureTables($rev) {
6a488035
TO
361 if ($this->multilingual) {
362 CRM_Core_I18n_Schema::schemaStructureTables($rev, TRUE);
363 }
364 }
365
624e56fa
EM
366 /**
367 * @param $rev
368 *
369 * @throws Exception
370 */
00be9182 371 public function processSQL($rev) {
6a488035 372 $sqlFile = implode(DIRECTORY_SEPARATOR,
be2fb01f 373 [
353ffa53
TO
374 dirname(__FILE__),
375 'Incremental',
376 'sql',
377 $rev . '.mysql',
be2fb01f 378 ]
6a488035
TO
379 );
380 $tplFile = "$sqlFile.tpl";
381
382 if (file_exists($tplFile)) {
383 $this->processLocales($tplFile, $rev);
384 }
385 else {
386 if (!file_exists($sqlFile)) {
800dad43 387 throw new CRM_Core_Exception("sqlfile - $rev.mysql not found.");
6a488035
TO
388 }
389 $this->source($sqlFile);
390 }
391 }
392
393 /**
fe482240 394 * Determine the start and end version of the upgrade process.
6a488035
TO
395 *
396 * @return array(0=>$currentVer, 1=>$latestVer)
397 */
00be9182 398 public function getUpgradeVersions() {
6a488035 399 $latestVer = CRM_Utils_System::version();
e418776c 400 $currentVer = CRM_Core_BAO_Domain::version(TRUE);
6a488035 401 if (!$currentVer) {
800dad43 402 throw new CRM_Core_Exception(ts('Version information missing in civicrm database.'));
6a488035
TO
403 }
404 elseif (stripos($currentVer, 'upgrade')) {
800dad43 405 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.'));
6a488035
TO
406 }
407 if (!$latestVer) {
800dad43 408 throw new CRM_Core_Exception(ts('Version information missing in civicrm codebase.'));
6a488035
TO
409 }
410
be2fb01f 411 return [$currentVer, $latestVer];
6a488035
TO
412 }
413
414 /**
415 * Determine if $currentVer can be upgraded to $latestVer
416 *
77b97be7
EM
417 * @param $currentVer
418 * @param $latestVer
419 *
6a488035
TO
420 * @return mixed, a string error message or boolean 'false' if OK
421 */
00be9182 422 public function checkUpgradeableVersion($currentVer, $latestVer) {
6a488035
TO
423 $error = FALSE;
424 // since version is suppose to be in valid format at this point, especially after conversion ($convertVer),
425 // lets do a pattern check -
426 if (!CRM_Utils_System::isVersionFormatValid($currentVer)) {
427 $error = ts('Database is marked with invalid version format. You may want to investigate this before you proceed further.');
428 }
429 elseif (version_compare($currentVer, $latestVer) > 0) {
430 // DB version number is higher than codebase being upgraded to. This is unexpected condition-fatal error.
431 $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.',
be2fb01f 432 [1 => $currentVer, 2 => $latestVer]
6a488035
TO
433 );
434 }
435 elseif (version_compare($currentVer, $latestVer) == 0) {
436 $error = ts('Your database has already been upgraded to CiviCRM %1',
be2fb01f 437 [1 => $latestVer]
6a488035
TO
438 );
439 }
304c1a5a
CW
440 elseif (version_compare($currentVer, self::MINIMUM_UPGRADABLE_VERSION) < 0) {
441 $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.',
be2fb01f 442 [1 => self::MINIMUM_UPGRADABLE_VERSION, 2 => $latestVer]
304c1a5a
CW
443 );
444 }
6a488035 445
243b25d9 446 if (version_compare(phpversion(), CRM_Upgrade_Incremental_General::MIN_INSTALL_PHP_VER) < 0) {
6a488035 447 $error = ts('CiviCRM %3 requires PHP version %1 (or newer), but the current system uses %2 ',
be2fb01f 448 [
243b25d9 449 1 => CRM_Upgrade_Incremental_General::MIN_INSTALL_PHP_VER,
304c1a5a 450 2 => phpversion(),
353ffa53 451 3 => $latestVer,
be2fb01f 452 ]);
6a488035
TO
453 }
454
b1634834
SL
455 if (version_compare(CRM_Utils_SQL::getDatabaseVersion(), CRM_Upgrade_Incremental_General::MIN_INSTALL_MYSQL_VER) < 0) {
456 $error = ts('CiviCRM %4 requires MySQL version v%1 or MariaDB v%3 (or newer), but the current system uses %2 ',
457 [
458 1 => CRM_Upgrade_Incremental_General::MIN_INSTALL_MYSQL_VER,
459 2 => CRM_Utils_SQL::getDatabaseVersion(),
460 3 => '10.1',
461 4 => $latestVer,
462 ]);
463 }
464
6a488035 465 // check for mysql trigger privileges
509e50b7 466 if (!\Civi::settings()->get('logging_no_trigger_permission') && !CRM_Core_DAO::checkTriggerViewPermission(FALSE, TRUE)) {
6a488035 467 $error = ts('CiviCRM %1 requires MySQL trigger privileges.',
be2fb01f 468 [1 => $latestVer]);
6a488035 469 }
032c9d10 470
e418776c 471 if (CRM_Core_DAO::getGlobalSetting('thread_stack', 0) < (1024 * self::MINIMUM_THREAD_STACK)) {
be2fb01f 472 $error = ts('CiviCRM %1 requires MySQL thread stack >= %2k', [
6a488035 473 1 => $latestVer,
21dfd5f5 474 2 => self::MINIMUM_THREAD_STACK,
be2fb01f 475 ]);
6a488035
TO
476 }
477
478 return $error;
479 }
480
481 /**
482 * Determine if $currentver already matches $latestVer
483 *
77b97be7
EM
484 * @param $currentVer
485 * @param $latestVer
486 *
6a488035
TO
487 * @return mixed, a string error message or boolean 'false' if OK
488 */
00be9182 489 public function checkCurrentVersion($currentVer, $latestVer) {
6a488035
TO
490 $error = FALSE;
491
492 // since version is suppose to be in valid format at this point, especially after conversion ($convertVer),
493 // lets do a pattern check -
494 if (!CRM_Utils_System::isVersionFormatValid($currentVer)) {
495 $error = ts('Database is marked with invalid version format. You may want to investigate this before you proceed further.');
496 }
497 elseif (version_compare($currentVer, $latestVer) != 0) {
498 $error = ts('Your database is not configured for version %1',
be2fb01f 499 [1 => $latestVer]
6a488035
TO
500 );
501 }
502 return $error;
503 }
504
505 /**
fe482240 506 * Fill the queue with upgrade tasks.
6a488035 507 *
5a4f6742
CW
508 * @param string $currentVer
509 * the original revision.
510 * @param string $latestVer
511 * the target (final) revision.
512 * @param string $postUpgradeMessageFile
513 * path of a modifiable file which lists the post-upgrade messages.
6a488035 514 *
bf6a5362 515 * @return CRM_Queue_Service
6a488035 516 */
00be9182 517 public static function buildQueue($currentVer, $latestVer, $postUpgradeMessageFile) {
6a488035
TO
518 $upgrade = new CRM_Upgrade_Form();
519
6a488035
TO
520 // Ensure that queue can be created
521 if (!CRM_Queue_BAO_QueueItem::findCreateTable()) {
800dad43 522 throw new CRM_Core_Exception(ts('Failed to find or create queueing table'));
6a488035 523 }
be2fb01f 524 $queue = CRM_Queue_Service::singleton()->create([
353ffa53
TO
525 'name' => self::QUEUE_NAME,
526 'type' => 'Sql',
527 'reset' => TRUE,
be2fb01f 528 ]);
6a488035 529
9e799b1d 530 $task = new CRM_Queue_Task(
be2fb01f
CW
531 ['CRM_Upgrade_Form', 'doFileCleanup'],
532 [$postUpgradeMessageFile],
9e799b1d
TO
533 "Cleanup old files"
534 );
535 $queue->createItem($task);
536
e4c4f267 537 $task = new CRM_Queue_Task(
be2fb01f
CW
538 ['CRM_Upgrade_Form', 'disableOldExtensions'],
539 [$postUpgradeMessageFile],
e4c4f267
CW
540 "Checking extensions"
541 );
542 $queue->createItem($task);
543
6a488035
TO
544 $revisions = $upgrade->getRevisionSequence();
545 foreach ($revisions as $rev) {
546 // proceed only if $currentVer < $rev
547 if (version_compare($currentVer, $rev) < 0) {
548 $beginTask = new CRM_Queue_Task(
353ffa53 549 // callback
be2fb01f 550 ['CRM_Upgrade_Form', 'doIncrementalUpgradeStart'],
6a488035 551 // arguments
be2fb01f 552 [$rev],
6a488035
TO
553 "Begin Upgrade to $rev"
554 );
555 $queue->createItem($beginTask);
556
557 $task = new CRM_Queue_Task(
353ffa53 558 // callback
be2fb01f 559 ['CRM_Upgrade_Form', 'doIncrementalUpgradeStep'],
6a488035 560 // arguments
be2fb01f 561 [$rev, $currentVer, $latestVer, $postUpgradeMessageFile],
6a488035
TO
562 "Upgrade DB to $rev"
563 );
564 $queue->createItem($task);
565
566 $task = new CRM_Queue_Task(
353ffa53 567 // callback
be2fb01f 568 ['CRM_Upgrade_Form', 'doIncrementalUpgradeFinish'],
6a488035 569 // arguments
be2fb01f 570 [$rev, $currentVer, $latestVer, $postUpgradeMessageFile],
6a488035
TO
571 "Finish Upgrade DB to $rev"
572 );
573 $queue->createItem($task);
574 }
575 }
576
577 return $queue;
578 }
579
9e799b1d
TO
580 /**
581 * Find any old, orphaned files that should have been deleted.
582 *
583 * These files can get left behind, eg, if you use the Joomla
584 * upgrade procedure.
585 *
586 * The earlier we can do this, the better - don't want upgrade logic
587 * to inadvertently rely on old/relocated files.
588 *
589 * @param \CRM_Queue_TaskContext $ctx
590 * @param string $postUpgradeMessageFile
591 * @return bool
592 */
593 public static function doFileCleanup(CRM_Queue_TaskContext $ctx, $postUpgradeMessageFile) {
594 $source = new CRM_Utils_Check_Component_Source();
595 $files = $source->findOrphanedFiles();
be2fb01f 596 $errors = [];
9e799b1d
TO
597 foreach ($files as $file) {
598 if (is_dir($file['path'])) {
599 @rmdir($file['path']);
600 }
601 else {
602 @unlink($file['path']);
603 }
604
605 if (file_exists($file['path'])) {
606 $errors[] = sprintf("<li>%s</li>", htmlentities($file['path']));
607 }
608 }
609
610 if (!empty($errors)) {
611 file_put_contents($postUpgradeMessageFile,
612 '<br/><br/>' . ts('Some old files could not be removed. Please remove them.')
613 . '<ul>' . implode("\n", $errors) . '</ul>',
614 FILE_APPEND
615 );
616 }
617
618 return TRUE;
619 }
620
e4c4f267 621 /**
df7a1988 622 * Disable/uninstall any extensions not compatible with this new version.
e4c4f267
CW
623 *
624 * @param \CRM_Queue_TaskContext $ctx
625 * @param string $postUpgradeMessageFile
626 * @return bool
627 */
628 public static function disableOldExtensions(CRM_Queue_TaskContext $ctx, $postUpgradeMessageFile) {
df7a1988 629 $messages = [];
e4c4f267 630 $manager = CRM_Extension_System::singleton()->getManager();
df7a1988
CW
631 foreach ($manager->getStatuses() as $key => $status) {
632 $obsolete = $manager->isIncompatible($key);
633 if ($obsolete) {
634 if (!empty($obsolete['disable']) && in_array($status, [$manager::STATUS_INSTALLED, $manager::STATUS_INSTALLED_MISSING])) {
635 try {
636 $manager->disable($key);
637 // Update the status for the sake of uninstall below.
638 $status = $status == $manager::STATUS_INSTALLED ? $manager::STATUS_DISABLED : $manager::STATUS_DISABLED_MISSING;
639 // This message is intentionally overwritten by uninstall below as it would be redundant
640 $messages[$key] = ts('The extension %1 is now obsolete and has been disabled.', [1 => $key]);
641 }
642 catch (CRM_Extension_Exception $e) {
643 $messages[] = ts('The obsolete extension %1 could not be removed due to an error. It is recommended to remove this extension manually.', [1 => $key]);
644 }
645 }
646 if (!empty($obsolete['uninstall']) && in_array($status, [$manager::STATUS_DISABLED, $manager::STATUS_DISABLED_MISSING])) {
647 try {
648 $manager->uninstall($key);
649 $messages[$key] = ts('The extension %1 is now obsolete and has been uninstalled.', [1 => $key]);
650 if ($status == $manager::STATUS_DISABLED) {
651 $messages[$key] .= ' ' . ts('You can remove it from your extensions directory.');
652 }
653 }
654 catch (CRM_Extension_Exception $e) {
655 $messages[] = ts('The obsolete extension %1 could not be removed due to an error. It is recommended to remove this extension manually.', [1 => $key]);
656 }
657 }
8a0199a3
TO
658 if (!empty($obsolete['force-uninstall'])) {
659 CRM_Core_DAO::executeQuery('UPDATE civicrm_extension SET is_active = 0 WHERE full_name = %1', [
660 1 => [$key, 'String'],
661 ]);
662 }
e4c4f267
CW
663 }
664 }
df7a1988 665 if ($messages) {
e4c4f267 666 file_put_contents($postUpgradeMessageFile,
df7a1988 667 '<br/><br/><ul><li>' . implode("</li>\n<li>", $messages) . '</li></ul>',
e4c4f267
CW
668 FILE_APPEND
669 );
670 }
671
672 return TRUE;
673 }
674
6a488035 675 /**
fe482240 676 * Perform an incremental version update.
6a488035 677 *
77b97be7 678 * @param CRM_Queue_TaskContext $ctx
5a4f6742
CW
679 * @param string $rev
680 * the target (intermediate) revision e.g '3.2.alpha1'.
77b97be7
EM
681 *
682 * @return bool
6a488035 683 */
00be9182 684 public static function doIncrementalUpgradeStart(CRM_Queue_TaskContext $ctx, $rev) {
6a488035
TO
685 $upgrade = new CRM_Upgrade_Form();
686
687 // as soon as we start doing anything we append ".upgrade" to version.
688 // this also helps detect any partial upgrade issues
689 $upgrade->setVersion($rev . '.upgrade');
690
691 return TRUE;
692 }
693
694 /**
fe482240 695 * Perform an incremental version update.
6a488035 696 *
77b97be7 697 * @param CRM_Queue_TaskContext $ctx
5a4f6742
CW
698 * @param string $rev
699 * the target (intermediate) revision e.g '3.2.alpha1'.
700 * @param string $originalVer
701 * the original revision.
702 * @param string $latestVer
703 * the target (final) revision.
704 * @param string $postUpgradeMessageFile
705 * path of a modifiable file which lists the post-upgrade messages.
77b97be7
EM
706 *
707 * @return bool
6a488035 708 */
e418776c 709 public static function doIncrementalUpgradeStep(CRM_Queue_TaskContext $ctx, $rev, $originalVer, $latestVer, $postUpgradeMessageFile) {
6a488035
TO
710 $upgrade = new CRM_Upgrade_Form();
711
712 $phpFunctionName = 'upgrade_' . str_replace('.', '_', $rev);
713
bd00780f
CW
714 $versionObject = $upgrade->incrementalPhpObject($rev);
715
716 // pre-db check for major release.
717 if ($upgrade->checkVersionRelease($rev, 'alpha1')) {
be2fb01f 718 if (!(is_callable([$versionObject, 'verifyPreDBstate']))) {
800dad43 719 throw new CRM_Core_Exception("verifyPreDBstate method was not found for $rev");
6a488035 720 }
6a488035 721
bd00780f
CW
722 $error = NULL;
723 if (!($versionObject->verifyPreDBstate($error))) {
724 if (!isset($error)) {
725 $error = "post-condition failed for current upgrade for $rev";
6a488035 726 }
800dad43 727 throw new CRM_Core_Exception($error);
6a488035
TO
728 }
729
bd00780f 730 }
6a488035 731
bd00780f 732 $upgrade->setSchemaStructureTables($rev);
6a488035 733
be2fb01f 734 if (is_callable([$versionObject, $phpFunctionName])) {
bd00780f
CW
735 $versionObject->$phpFunctionName($rev, $originalVer, $latestVer);
736 }
737 else {
738 $upgrade->processSQL($rev);
739 }
740
741 // set post-upgrade-message if any
be2fb01f 742 if (is_callable([$versionObject, 'setPostUpgradeMessage'])) {
bd00780f
CW
743 $postUpgradeMessage = file_get_contents($postUpgradeMessageFile);
744 $versionObject->setPostUpgradeMessage($postUpgradeMessage, $rev);
bd00780f 745 file_put_contents($postUpgradeMessageFile, $postUpgradeMessage);
6a488035
TO
746 }
747
748 return TRUE;
749 }
750
751 /**
fe482240 752 * Perform an incremental version update.
6a488035 753 *
77b97be7 754 * @param CRM_Queue_TaskContext $ctx
5a4f6742
CW
755 * @param string $rev
756 * the target (intermediate) revision e.g '3.2.alpha1'.
757 * @param string $currentVer
758 * the original revision.
759 * @param string $latestVer
760 * the target (final) revision.
761 * @param string $postUpgradeMessageFile
762 * path of a modifiable file which lists the post-upgrade messages.
77b97be7
EM
763 *
764 * @return bool
6a488035 765 */
00be9182 766 public static function doIncrementalUpgradeFinish(CRM_Queue_TaskContext $ctx, $rev, $currentVer, $latestVer, $postUpgradeMessageFile) {
6a488035
TO
767 $upgrade = new CRM_Upgrade_Form();
768 $upgrade->setVersion($rev);
769 CRM_Utils_System::flushCache();
ac05cde3 770
d8a4acc0
C
771 $config = CRM_Core_Config::singleton();
772 $config->userSystem->flush();
6a488035
TO
773 return TRUE;
774 }
775
00be9182 776 public static function doFinish() {
ecb0ae5d
TO
777 Civi::dispatcher()->setDispatchPolicy(\CRM_Upgrade_DispatchPolicy::get('upgrade.finish'));
778 $restore = \CRM_Utils_AutoClean::with(function() {
779 Civi::dispatcher()->setDispatchPolicy(\CRM_Upgrade_DispatchPolicy::get('upgrade.main'));
780 });
781
6a488035
TO
782 $upgrade = new CRM_Upgrade_Form();
783 list($ignore, $latestVer) = $upgrade->getUpgradeVersions();
784 // Seems extraneous in context, but we'll preserve old behavior
785 $upgrade->setVersion($latestVer);
786
3af5c3fe
TO
787 CRM_Core_Invoke::rebuildMenuAndCaches(FALSE, TRUE);
788 // NOTE: triggerRebuild is FALSE becaues it will run again in a moment (via fixSchemaDifferences).
6a488035 789
6b4bec74
CW
790 $versionCheck = new CRM_Utils_VersionCheck();
791 $versionCheck->flushCache();
792
6a488035
TO
793 // Rebuild all triggers and re-enable logging if needed
794 $logging = new CRM_Logging_Schema();
795 $logging->fixSchemaDifferences();
796 }
797
798 /**
799 * Compute any messages which should be displayed before upgrade
800 * by calling the 'setPreUpgradeMessage' on each incremental upgrade
801 * object.
802 *
5a4f6742
CW
803 * @param string $preUpgradeMessage
804 * alterable.
77b97be7
EM
805 * @param $currentVer
806 * @param $latestVer
6a488035 807 */
00be9182 808 public function setPreUpgradeMessage(&$preUpgradeMessage, $currentVer, $latestVer) {
49368097
CW
809 // check for changed message templates
810 CRM_Upgrade_Incremental_General::checkMessageTemplate($preUpgradeMessage, $latestVer, $currentVer);
811 // set global messages
812 CRM_Upgrade_Incremental_General::setPreUpgradeMessage($preUpgradeMessage, $currentVer, $latestVer);
6a488035
TO
813
814 // Scan through all php files and see if any file is interested in setting pre-upgrade-message
815 // based on $currentVer, $latestVer.
816 // Please note, at this point upgrade hasn't started executing queries.
817 $revisions = $this->getRevisionSequence();
818 foreach ($revisions as $rev) {
49368097 819 if (version_compare($currentVer, $rev) < 0) {
6a488035 820 $versionObject = $this->incrementalPhpObject($rev);
fe83c251 821 CRM_Upgrade_Incremental_General::updateMessageTemplate($preUpgradeMessage, $rev);
be2fb01f 822 if (is_callable([$versionObject, 'setPreUpgradeMessage'])) {
e418776c
TO
823 $versionObject->setPreUpgradeMessage($preUpgradeMessage, $rev, $currentVer);
824 }
6a488035
TO
825 }
826 }
827 }
96025800 828
6a488035 829}