3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 |
9 +--------------------------------------------------------------------+
12 use Civi\Core\SettingsBag
;
15 * Base class for incremental upgrades
17 class CRM_Upgrade_Incremental_Base
{
18 const BATCH_SIZE
= 5000;
23 protected $majorMinor;
26 * Get the major and minor version for this class (based on English-style class name).
31 public function getMajorMinor() {
32 if (!$this->majorMinor
) {
33 $className = explode('_', static::CLASS);
34 $numbers = preg_split("/([[:upper:]][[:lower:]]+)/", array_pop($className), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
);
35 $major = CRM_Utils_EnglishNumber
::toInt(array_shift($numbers));
36 $minor = CRM_Utils_EnglishNumber
::toInt(implode('', $numbers));
37 $this->majorMinor
= $major . '.' . $minor;
39 return $this->majorMinor
;
43 * Get a list of revisions (PATCH releases) related to this class.
46 * Ex: ['4.5.6', '4.5.7']
47 * @throws \ReflectionException
49 public function getRevisionSequence() {
52 $sqlGlob = implode(DIRECTORY_SEPARATOR
, [dirname(__FILE__
), 'sql', $this->getMajorMinor() . '.*.mysql.tpl']);
53 $sqlFiles = glob($sqlGlob);;
54 foreach ($sqlFiles as $file) {
55 $revList[] = str_replace('.mysql.tpl', '', basename($file));
58 $c = new ReflectionClass(static::class);
59 foreach ($c->getMethods() as $method) {
60 /** @var \ReflectionMethod $method */
61 if (preg_match(';^upgrade_([0-9_alphabeta]+)$;', $method->getName(), $m)) {
62 $revList[] = str_replace('_', '.', $m[1]);
66 $revList = array_unique($revList);
67 usort($revList, 'version_compare');
72 * Compute any messages which should be displayed before upgrade.
74 * Note: This function is called iteratively for each upcoming
75 * revision to the database.
77 * @param $preUpgradeMessage
79 * a version number, e.g. '4.8.alpha1', '4.8.beta3', '4.8.0'.
80 * @param null $currentVer
82 public function setPreUpgradeMessage(&$preUpgradeMessage, $rev, $currentVer = NULL) {
86 * Compute any messages which should be displayed after upgrade.
88 * @param string $postUpgradeMessage
91 * an intermediate version; note that setPostUpgradeMessage is called repeatedly with different $revs.
93 public function setPostUpgradeMessage(&$postUpgradeMessage, $rev) {
97 * (Queue Task Callback)
99 * @param \CRM_Queue_TaskContext $ctx
104 public static function runSql(CRM_Queue_TaskContext
$ctx, $rev) {
105 $upgrade = new CRM_Upgrade_Form();
106 $upgrade->processSQL($rev);
112 * Syntactic sugar for adding a task.
114 * Task is (a) in this class and (b) has a high priority.
116 * After passing the $funcName, you can also pass parameters that will go to
117 * the function. Note that all params must be serializable.
119 * @param string $title
120 * @param string $funcName
122 protected function addTask($title, $funcName) {
123 $queue = CRM_Queue_Service
::singleton()->load([
125 'name' => CRM_Upgrade_Form
::QUEUE_NAME
,
128 $args = func_get_args();
129 $title = array_shift($args);
130 $funcName = array_shift($args);
131 $task = new CRM_Queue_Task(
132 [get_class($this), $funcName],
136 $queue->createItem($task, ['weight' => -1]);
140 * Remove a payment processor if not in use
142 * @param CRM_Queue_TaskContext $ctx
143 * @param string $name
145 * @throws \CiviCRM_API3_Exception
147 public static function removePaymentProcessorType(CRM_Queue_TaskContext
$ctx, $name) {
148 $processors = civicrm_api3('PaymentProcessor', 'getcount', ['payment_processor_type_id' => $name]);
149 if (empty($processors['result'])) {
150 $result = civicrm_api3('PaymentProcessorType', 'get', [
154 if (!empty($result['id'])) {
155 civicrm_api3('PaymentProcessorType', 'delete', ['id' => $result['id']]);
162 * @param string $table_name
163 * @param string $constraint_name
166 public static function checkFKExists($table_name, $constraint_name) {
167 return CRM_Core_BAO_SchemaHandler
::checkFKExists($table_name, $constraint_name);
171 * Add a column to a table if it doesn't already exist
173 * @param CRM_Queue_TaskContext $ctx
174 * @param string $table
175 * @param string $column
176 * @param string $properties
177 * @param bool $localizable is this a field that should be localized
178 * @param string|null $version CiviCRM version to use if rebuilding multilingual schema
179 * @param bool $triggerRebuild should we trigger the rebuild of the multilingual schema
183 public static function addColumn($ctx, $table, $column, $properties, $localizable = FALSE, $version = NULL, $triggerRebuild = TRUE) {
184 $locales = CRM_Core_I18n
::getMultilingual();
186 if (!CRM_Core_BAO_SchemaHandler
::checkIfFieldExists($table, $column, FALSE)) {
189 foreach ($locales as $locale) {
190 if (!CRM_Core_BAO_SchemaHandler
::checkIfFieldExists($table, "{$column}_{$locale}", FALSE)) {
191 $queries[] = "ALTER TABLE `$table` ADD COLUMN `{$column}_{$locale}` $properties";
196 $queries[] = "ALTER TABLE `$table` ADD COLUMN `$column` $properties";
200 $queries[] = "ALTER TABLE `$table` ADD COLUMN `$column` $properties";
202 foreach ($queries as $query) {
203 CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
206 if ($locales && $triggerRebuild) {
207 CRM_Core_I18n_Schema
::rebuildMultilingualSchema($locales, $version, TRUE);
213 * Add the specified option group, gracefully if it already exists.
215 * @param CRM_Queue_TaskContext $ctx
216 * @param array $params
217 * @param array $options
221 public static function addOptionGroup(CRM_Queue_TaskContext
$ctx, $params, $options): bool {
222 $defaults = ['is_active' => 1];
223 $optionDefaults = ['is_active' => 1];
224 $optionDefaults['option_group_id'] = \CRM_Core_BAO_OptionGroup
::ensureOptionGroupExists(array_merge($defaults, $params));
226 foreach ($options as $option) {
227 \CRM_Core_BAO_OptionValue
::ensureOptionValueExists(array_merge($optionDefaults, $option));
233 * Do any relevant message template updates.
235 * @param CRM_Queue_TaskContext $ctx
236 * @param string $version
238 public static function updateMessageTemplates($ctx, $version) {
239 $messageTemplateObject = new CRM_Upgrade_Incremental_MessageTemplates($version);
240 $messageTemplateObject->updateTemplates();
244 * Updated a message token within a template.
246 * @param CRM_Queue_TaskContext $ctx
247 * @param string $workflowName
254 public static function updateMessageToken($ctx, string $workflowName, string $old, string $new, $version):bool {
255 $messageObj = new CRM_Upgrade_Incremental_MessageTemplates($version);
256 if (!empty($workflowName)) {
257 $messageObj->replaceTokenInTemplate($workflowName, $old, $new);
260 $messageObj->replaceTokenInMessageTemplates($old, $new);
266 * Updated a message token within a scheduled reminder.
268 * @param CRM_Queue_TaskContext $ctx
275 public static function updateActionScheduleToken($ctx, string $old, string $new, $version):bool {
276 $messageObj = new CRM_Upgrade_Incremental_MessageTemplates($version);
277 $messageObj->replaceTokenInActionSchedule($old, $new);
282 * Updated a message token within a label.
284 * @param CRM_Queue_TaskContext $ctx
291 public static function updatePrintLabelToken($ctx, string $old, string $new, $version):bool {
292 $messageObj = new CRM_Upgrade_Incremental_MessageTemplates($version);
293 $messageObj->replaceTokenInPrintLabel($old, $new);
298 * Updated a message token within greeting options.
300 * @param CRM_Queue_TaskContext $ctx
307 public static function updateGreetingOptions($ctx, string $old, string $new, $version):bool {
308 $messageObj = new CRM_Upgrade_Incremental_MessageTemplates($version);
309 $messageObj->replaceTokenInGreetingOptions($old, $new);
314 * Updated a currency in civicrm_currency and related configurations
316 * @param CRM_Queue_TaskContext $ctx
317 * @param string $old_name
318 * @param string $new_name
322 public static function updateCurrencyName($ctx, string $old_name, string $new_name): bool {
323 CRM_Core_DAO
::executeQuery('UPDATE civicrm_currency SET name = %1 WHERE name = %2', [
324 1 => [$new_name, 'String'],
325 2 => [$old_name, 'String'],
328 $oid = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_option_group WHERE name = 'currencies_enabled'");
330 CRM_Core_DAO
::executeQuery('UPDATE civicrm_option_value SET value = %1 WHERE value = %2 AND option_group_id = %3', [
331 1 => [$new_name, 'String'],
332 2 => [$old_name, 'String'],
333 3 => [$oid, 'String'],
337 CRM_Core_DAO
::executeQuery('UPDATE civicrm_participant SET fee_currency = %1 WHERE fee_currency = %2', [
338 1 => [$new_name, 'String'],
339 2 => [$old_name, 'String'],
343 'civicrm_contribution',
344 'civicrm_contribution_page',
345 'civicrm_contribution_recur',
346 'civicrm_contribution_soft',
348 'civicrm_financial_item',
349 'civicrm_financial_trxn',
352 'civicrm_pledge_payment',
357 foreach ($tables as $table) {
358 CRM_Core_DAO
::executeQuery('UPDATE %3 SET currency = %1 WHERE currency = %2', [
359 1 => [$new_name, 'String'],
360 2 => [$old_name, 'String'],
361 3 => [$table, 'MysqlColumnNameOrAlias'],
369 * Re-save any valid values from contribute settings into the normal setting
372 * We render the array of contribution_invoice_settings and any that have
373 * metadata defined we add to the correct key. This is safe to run even if no
374 * settings are to be converted, per the test in
375 * testConvertUpgradeContributeSettings.
381 public static function updateContributeSettings($ctx) {
382 // Use a direct query as api now does some handling on this.
383 $settings = CRM_Core_DAO
::executeQuery("SELECT value, domain_id FROM civicrm_setting WHERE name = 'contribution_invoice_settings'");
385 while ($settings->fetch()) {
386 $contributionSettings = (array) CRM_Utils_String
::unserialize($settings->value
);
387 foreach (array_merge(SettingsBag
::getContributionInvoiceSettingKeys(), ['deferred_revenue_enabled' => 'deferred_revenue_enabled']) as $possibleKeyName => $settingName) {
388 if (!empty($contributionSettings[$possibleKeyName]) && empty(Civi
::settings($settings->domain_id
)->getExplicit($settingName))) {
389 Civi
::settings($settings->domain_id
)->set($settingName, $contributionSettings[$possibleKeyName]);
397 * Do any relevant smart group updates.
399 * @param CRM_Queue_TaskContext $ctx
400 * @param array $actions
404 public static function updateSmartGroups($ctx, $actions) {
405 $groupUpdateObject = new CRM_Upgrade_Incremental_SmartGroups();
406 $groupUpdateObject->updateGroups($actions);
411 * Drop a column from a table if it exist.
413 * @param CRM_Queue_TaskContext $ctx
414 * @param string $table
415 * @param string $column
418 public static function dropColumn($ctx, $table, $column) {
419 if (CRM_Core_BAO_SchemaHandler
::checkIfFieldExists($table, $column)) {
420 CRM_Core_DAO
::executeQuery("ALTER TABLE `$table` DROP COLUMN `$column`",
421 [], TRUE, NULL, FALSE, FALSE);
427 * Add a index to a table column.
429 * @param CRM_Queue_TaskContext $ctx
430 * @param string $table
431 * @param string|array $columns
432 * @param string $prefix
435 public static function addIndex($ctx, $table, $columns, $prefix = 'index') {
436 $tables = [$table => (array) $columns];
437 CRM_Core_BAO_SchemaHandler
::createIndexes($tables, $prefix);
443 * Drop a index from a table if it exist.
445 * @param CRM_Queue_TaskContext $ctx
446 * @param string $table
447 * @param string $indexName
450 public static function dropIndex($ctx, $table, $indexName) {
451 CRM_Core_BAO_SchemaHandler
::dropIndexIfExists($table, $indexName);
457 * Drop a table... but only if it's empty.
459 * @param CRM_Queue_TaskContext $ctx
460 * @param string $table
463 public static function dropTableIfEmpty($ctx, $table) {
464 if (CRM_Core_DAO
::checkTableExists($table)) {
465 if (!CRM_Core_DAO
::checkTableHasData($table)) {
466 CRM_Core_BAO_SchemaHandler
::dropTable($table);
469 $ctx->log
->warning("dropTableIfEmpty($table): Found data. Preserved table.");
477 * Rebuild Multilingual Schema.
478 * @param CRM_Queue_TaskContext $ctx
479 * @param string|null $version CiviCRM version to use if rebuilding multilingual schema
483 public static function rebuildMultilingalSchema($ctx, $version = NULL) {
484 $locales = CRM_Core_I18n
::getMultilingual();
486 CRM_Core_I18n_Schema
::rebuildMultilingualSchema($locales, $version);