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