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');
78 public function verifyPreDBstate(&$errors) {
83 * Compute any messages which should be displayed before upgrade.
85 * Note: This function is called iteratively for each upcoming
86 * revision to the database.
88 * @param $preUpgradeMessage
90 * a version number, e.g. '4.8.alpha1', '4.8.beta3', '4.8.0'.
91 * @param null $currentVer
93 public function setPreUpgradeMessage(&$preUpgradeMessage, $rev, $currentVer = NULL) {
97 * Compute any messages which should be displayed after upgrade.
99 * @param string $postUpgradeMessage
102 * an intermediate version; note that setPostUpgradeMessage is called repeatedly with different $revs.
104 public function setPostUpgradeMessage(&$postUpgradeMessage, $rev) {
108 * (Queue Task Callback)
110 * @param \CRM_Queue_TaskContext $ctx
115 public static function runSql(CRM_Queue_TaskContext
$ctx, $rev) {
116 $upgrade = new CRM_Upgrade_Form();
117 $upgrade->processSQL($rev);
123 * Syntactic sugar for adding a task.
125 * Task is (a) in this class and (b) has a high priority.
127 * After passing the $funcName, you can also pass parameters that will go to
128 * the function. Note that all params must be serializable.
130 * @param string $title
131 * @param string $funcName
133 protected function addTask($title, $funcName) {
134 $queue = CRM_Queue_Service
::singleton()->load([
136 'name' => CRM_Upgrade_Form
::QUEUE_NAME
,
139 $args = func_get_args();
140 $title = array_shift($args);
141 $funcName = array_shift($args);
142 $task = new CRM_Queue_Task(
143 [get_class($this), $funcName],
147 $queue->createItem($task, ['weight' => -1]);
151 * Remove a payment processor if not in use
153 * @param CRM_Queue_TaskContext $ctx
154 * @param string $name
156 * @throws \CiviCRM_API3_Exception
158 public static function removePaymentProcessorType(CRM_Queue_TaskContext
$ctx, $name) {
159 $processors = civicrm_api3('PaymentProcessor', 'getcount', ['payment_processor_type_id' => $name]);
160 if (empty($processors['result'])) {
161 $result = civicrm_api3('PaymentProcessorType', 'get', [
165 if (!empty($result['id'])) {
166 civicrm_api3('PaymentProcessorType', 'delete', ['id' => $result['id']]);
173 * @param string $table_name
174 * @param string $constraint_name
177 public static function checkFKExists($table_name, $constraint_name) {
178 return CRM_Core_BAO_SchemaHandler
::checkFKExists($table_name, $constraint_name);
182 * Add a column to a table if it doesn't already exist
184 * @param CRM_Queue_TaskContext $ctx
185 * @param string $table
186 * @param string $column
187 * @param string $properties
188 * @param bool $localizable is this a field that should be localized
189 * @param string|null $version CiviCRM version to use if rebuilding multilingual schema
190 * @param bool $triggerRebuild should we trigger the rebuild of the multilingual schema
194 public static function addColumn($ctx, $table, $column, $properties, $localizable = FALSE, $version = NULL, $triggerRebuild = TRUE) {
195 $locales = CRM_Core_I18n
::getMultilingual();
197 if (!CRM_Core_BAO_SchemaHandler
::checkIfFieldExists($table, $column, FALSE)) {
200 foreach ($locales as $locale) {
201 if (!CRM_Core_BAO_SchemaHandler
::checkIfFieldExists($table, "{$column}_{$locale}", FALSE)) {
202 $queries[] = "ALTER TABLE `$table` ADD COLUMN `{$column}_{$locale}` $properties";
207 $queries[] = "ALTER TABLE `$table` ADD COLUMN `$column` $properties";
211 $queries[] = "ALTER TABLE `$table` ADD COLUMN `$column` $properties";
213 foreach ($queries as $query) {
214 CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
217 if ($locales && $triggerRebuild) {
218 CRM_Core_I18n_Schema
::rebuildMultilingualSchema($locales, $version, TRUE);
224 * Do any relevant message template updates.
226 * @param CRM_Queue_TaskContext $ctx
227 * @param string $version
229 public static function updateMessageTemplates($ctx, $version) {
230 $messageTemplateObject = new CRM_Upgrade_Incremental_MessageTemplates($version);
231 $messageTemplateObject->updateTemplates();
236 * Re-save any valid values from contribute settings into the normal setting
239 * We render the array of contribution_invoice_settings and any that have
240 * metadata defined we add to the correct key. This is safe to run even if no
241 * settings are to be converted, per the test in
242 * testConvertUpgradeContributeSettings.
248 public static function updateContributeSettings($ctx) {
249 // Use a direct query as api now does some handling on this.
250 $settings = CRM_Core_DAO
::executeQuery("SELECT value, domain_id FROM civicrm_setting WHERE name = 'contribution_invoice_settings'");
252 while ($settings->fetch()) {
253 $contributionSettings = (array) CRM_Utils_String
::unserialize($settings->value
);
254 foreach (array_merge(SettingsBag
::getContributionInvoiceSettingKeys(), ['deferred_revenue_enabled' => 'deferred_revenue_enabled']) as $possibleKeyName => $settingName) {
255 if (!empty($contributionSettings[$possibleKeyName]) && empty(Civi
::settings($settings->domain_id
)->getExplicit($settingName))) {
256 Civi
::settings($settings->domain_id
)->set($settingName, $contributionSettings[$possibleKeyName]);
264 * Do any relevant smart group updates.
266 * @param CRM_Queue_TaskContext $ctx
267 * @param array $actions
271 public static function updateSmartGroups($ctx, $actions) {
272 $groupUpdateObject = new CRM_Upgrade_Incremental_SmartGroups();
273 $groupUpdateObject->updateGroups($actions);
278 * Drop a column from a table if it exist.
280 * @param CRM_Queue_TaskContext $ctx
281 * @param string $table
282 * @param string $column
285 public static function dropColumn($ctx, $table, $column) {
286 if (CRM_Core_BAO_SchemaHandler
::checkIfFieldExists($table, $column)) {
287 CRM_Core_DAO
::executeQuery("ALTER TABLE `$table` DROP COLUMN `$column`",
288 [], TRUE, NULL, FALSE, FALSE);
294 * Add a index to a table column.
296 * @param CRM_Queue_TaskContext $ctx
297 * @param string $table
298 * @param string|array $columns
299 * @param string $prefix
302 public static function addIndex($ctx, $table, $columns, $prefix = 'index') {
303 $tables = [$table => (array) $columns];
304 CRM_Core_BAO_SchemaHandler
::createIndexes($tables, $prefix);
310 * Drop a index from a table if it exist.
312 * @param CRM_Queue_TaskContext $ctx
313 * @param string $table
314 * @param string $indexName
317 public static function dropIndex($ctx, $table, $indexName) {
318 CRM_Core_BAO_SchemaHandler
::dropIndexIfExists($table, $indexName);
324 * Drop a table... but only if it's empty.
326 * @param CRM_Queue_TaskContext $ctx
327 * @param string $table
330 public static function dropTableIfEmpty($ctx, $table) {
331 if (CRM_Core_DAO
::checkTableExists($table)) {
332 if (!CRM_Core_DAO
::checkTableHasData($table)) {
333 CRM_Core_BAO_SchemaHandler
::dropTable($table);
336 $ctx->log
->warning("dropTableIfEmpty($table): Found data. Preserved table.");
344 * Rebuild Multilingual Schema.
345 * @param CRM_Queue_TaskContext $ctx
346 * @param string|null $version CiviCRM version to use if rebuilding multilingual schema
350 public static function rebuildMultilingalSchema($ctx, $version = NULL) {
351 $locales = CRM_Core_I18n
::getMultilingual();
353 CRM_Core_I18n_Schema
::rebuildMultilingualSchema($locales, $version);