Merge pull request #21555 from eileenmcnaughton/money
[civicrm-core.git] / CRM / Upgrade / Incremental / Base.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12 use Civi\Core\SettingsBag;
13
14 /**
15 * Base class for incremental upgrades
16 */
17 class CRM_Upgrade_Incremental_Base {
18 const BATCH_SIZE = 5000;
19
20 /**
21 * @var string|null
22 */
23 protected $majorMinor;
24
25 /**
26 * Get the major and minor version for this class (based on English-style class name).
27 *
28 * @return string
29 * Ex: '5.34' or '4.7'
30 */
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;
38 }
39 return $this->majorMinor;
40 }
41
42 /**
43 * Get a list of revisions (PATCH releases) related to this class.
44 *
45 * @return array
46 * Ex: ['4.5.6', '4.5.7']
47 * @throws \ReflectionException
48 */
49 public function getRevisionSequence() {
50 $revList = [];
51
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));
56 }
57
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]);
63 }
64 }
65
66 $revList = array_unique($revList);
67 usort($revList, 'version_compare');
68 return $revList;
69 }
70
71 /**
72 * Verify DB state.
73 *
74 * @param $errors
75 *
76 * @return bool
77 */
78 public function verifyPreDBstate(&$errors) {
79 return TRUE;
80 }
81
82 /**
83 * Compute any messages which should be displayed before upgrade.
84 *
85 * Note: This function is called iteratively for each upcoming
86 * revision to the database.
87 *
88 * @param $preUpgradeMessage
89 * @param string $rev
90 * a version number, e.g. '4.8.alpha1', '4.8.beta3', '4.8.0'.
91 * @param null $currentVer
92 */
93 public function setPreUpgradeMessage(&$preUpgradeMessage, $rev, $currentVer = NULL) {
94 }
95
96 /**
97 * Compute any messages which should be displayed after upgrade.
98 *
99 * @param string $postUpgradeMessage
100 * alterable.
101 * @param string $rev
102 * an intermediate version; note that setPostUpgradeMessage is called repeatedly with different $revs.
103 */
104 public function setPostUpgradeMessage(&$postUpgradeMessage, $rev) {
105 }
106
107 /**
108 * (Queue Task Callback)
109 *
110 * @param \CRM_Queue_TaskContext $ctx
111 * @param string $rev
112 *
113 * @return bool
114 */
115 public static function runSql(CRM_Queue_TaskContext $ctx, $rev) {
116 $upgrade = new CRM_Upgrade_Form();
117 $upgrade->processSQL($rev);
118
119 return TRUE;
120 }
121
122 /**
123 * Syntactic sugar for adding a task.
124 *
125 * Task is (a) in this class and (b) has a high priority.
126 *
127 * After passing the $funcName, you can also pass parameters that will go to
128 * the function. Note that all params must be serializable.
129 *
130 * @param string $title
131 * @param string $funcName
132 */
133 protected function addTask($title, $funcName) {
134 $queue = CRM_Queue_Service::singleton()->load([
135 'type' => 'Sql',
136 'name' => CRM_Upgrade_Form::QUEUE_NAME,
137 ]);
138
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],
144 $args,
145 $title
146 );
147 $queue->createItem($task, ['weight' => -1]);
148 }
149
150 /**
151 * Remove a payment processor if not in use
152 *
153 * @param CRM_Queue_TaskContext $ctx
154 * @param string $name
155 * @return bool
156 * @throws \CiviCRM_API3_Exception
157 */
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', [
162 'name' => $name,
163 'return' => 'id',
164 ]);
165 if (!empty($result['id'])) {
166 civicrm_api3('PaymentProcessorType', 'delete', ['id' => $result['id']]);
167 }
168 }
169 return TRUE;
170 }
171
172 /**
173 * @param string $table_name
174 * @param string $constraint_name
175 * @return bool
176 */
177 public static function checkFKExists($table_name, $constraint_name) {
178 return CRM_Core_BAO_SchemaHandler::checkFKExists($table_name, $constraint_name);
179 }
180
181 /**
182 * Add a column to a table if it doesn't already exist
183 *
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
191 *
192 * @return bool
193 */
194 public static function addColumn($ctx, $table, $column, $properties, $localizable = FALSE, $version = NULL, $triggerRebuild = TRUE) {
195 $locales = CRM_Core_I18n::getMultilingual();
196 $queries = [];
197 if (!CRM_Core_BAO_SchemaHandler::checkIfFieldExists($table, $column, FALSE)) {
198 if ($locales) {
199 if ($localizable) {
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";
203 }
204 }
205 }
206 else {
207 $queries[] = "ALTER TABLE `$table` ADD COLUMN `$column` $properties";
208 }
209 }
210 else {
211 $queries[] = "ALTER TABLE `$table` ADD COLUMN `$column` $properties";
212 }
213 foreach ($queries as $query) {
214 CRM_Core_DAO::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
215 }
216 }
217 if ($locales && $triggerRebuild) {
218 CRM_Core_I18n_Schema::rebuildMultilingualSchema($locales, $version, TRUE);
219 }
220 return TRUE;
221 }
222
223 /**
224 * Add the specified option group, gracefully if it already exists.
225 *
226 * @param CRM_Queue_TaskContext $ctx
227 * @param array $params
228 * @param array $options
229 *
230 * @return bool
231 */
232 public static function addOptionGroup(CRM_Queue_TaskContext $ctx, $params, $options): bool {
233 $defaults = ['is_active' => 1];
234 $optionDefaults = ['is_active' => 1];
235 $optionDefaults['option_group_id'] = \CRM_Core_BAO_OptionGroup::ensureOptionGroupExists(array_merge($defaults, $params));
236
237 foreach ($options as $option) {
238 \CRM_Core_BAO_OptionValue::ensureOptionValueExists(array_merge($optionDefaults, $option));
239 }
240 return TRUE;
241 }
242
243 /**
244 * Do any relevant message template updates.
245 *
246 * @param CRM_Queue_TaskContext $ctx
247 * @param string $version
248 */
249 public static function updateMessageTemplates($ctx, $version) {
250 $messageTemplateObject = new CRM_Upgrade_Incremental_MessageTemplates($version);
251 $messageTemplateObject->updateTemplates();
252 }
253
254 /**
255 * Updated a message token within a template.
256 *
257 * @param CRM_Queue_TaskContext $ctx
258 * @param string $workflowName
259 * @param string $old
260 * @param string $new
261 * @param $version
262 *
263 * @return bool
264 */
265 public static function updateMessageToken($ctx, string $workflowName, string $old, string $new, $version):bool {
266 $messageObj = new CRM_Upgrade_Incremental_MessageTemplates($version);
267 $messageObj->replaceTokenInTemplate($workflowName, $old, $new);
268 return TRUE;
269 }
270
271 /**
272 * Updated a message token within a scheduled reminder.
273 *
274 * @param CRM_Queue_TaskContext $ctx
275 * @param string $old
276 * @param string $new
277 * @param $version
278 *
279 * @return bool
280 */
281 public static function updateActionScheduleToken($ctx, string $old, string $new, $version):bool {
282 $messageObj = new CRM_Upgrade_Incremental_MessageTemplates($version);
283 $messageObj->replaceTokenInActionSchedule($old, $new);
284 return TRUE;
285 }
286
287 /**
288 * Updated a message token within a template.
289 *
290 * @param CRM_Queue_TaskContext $ctx
291 * @param string $old
292 * @param string $new
293 * @param $version
294 *
295 * @return bool
296 */
297 public static function updatePrintLabelToken($ctx, string $old, string $new, $version):bool {
298 $messageObj = new CRM_Upgrade_Incremental_MessageTemplates($version);
299 $messageObj->replaceTokenInPrintLabel($old, $new);
300 return TRUE;
301 }
302
303 /**
304 * Re-save any valid values from contribute settings into the normal setting
305 * format.
306 *
307 * We render the array of contribution_invoice_settings and any that have
308 * metadata defined we add to the correct key. This is safe to run even if no
309 * settings are to be converted, per the test in
310 * testConvertUpgradeContributeSettings.
311 *
312 * @param $ctx
313 *
314 * @return bool
315 */
316 public static function updateContributeSettings($ctx) {
317 // Use a direct query as api now does some handling on this.
318 $settings = CRM_Core_DAO::executeQuery("SELECT value, domain_id FROM civicrm_setting WHERE name = 'contribution_invoice_settings'");
319
320 while ($settings->fetch()) {
321 $contributionSettings = (array) CRM_Utils_String::unserialize($settings->value);
322 foreach (array_merge(SettingsBag::getContributionInvoiceSettingKeys(), ['deferred_revenue_enabled' => 'deferred_revenue_enabled']) as $possibleKeyName => $settingName) {
323 if (!empty($contributionSettings[$possibleKeyName]) && empty(Civi::settings($settings->domain_id)->getExplicit($settingName))) {
324 Civi::settings($settings->domain_id)->set($settingName, $contributionSettings[$possibleKeyName]);
325 }
326 }
327 }
328 return TRUE;
329 }
330
331 /**
332 * Do any relevant smart group updates.
333 *
334 * @param CRM_Queue_TaskContext $ctx
335 * @param array $actions
336 *
337 * @return bool
338 */
339 public static function updateSmartGroups($ctx, $actions) {
340 $groupUpdateObject = new CRM_Upgrade_Incremental_SmartGroups();
341 $groupUpdateObject->updateGroups($actions);
342 return TRUE;
343 }
344
345 /**
346 * Drop a column from a table if it exist.
347 *
348 * @param CRM_Queue_TaskContext $ctx
349 * @param string $table
350 * @param string $column
351 * @return bool
352 */
353 public static function dropColumn($ctx, $table, $column) {
354 if (CRM_Core_BAO_SchemaHandler::checkIfFieldExists($table, $column)) {
355 CRM_Core_DAO::executeQuery("ALTER TABLE `$table` DROP COLUMN `$column`",
356 [], TRUE, NULL, FALSE, FALSE);
357 }
358 return TRUE;
359 }
360
361 /**
362 * Add a index to a table column.
363 *
364 * @param CRM_Queue_TaskContext $ctx
365 * @param string $table
366 * @param string|array $columns
367 * @param string $prefix
368 * @return bool
369 */
370 public static function addIndex($ctx, $table, $columns, $prefix = 'index') {
371 $tables = [$table => (array) $columns];
372 CRM_Core_BAO_SchemaHandler::createIndexes($tables, $prefix);
373
374 return TRUE;
375 }
376
377 /**
378 * Drop a index from a table if it exist.
379 *
380 * @param CRM_Queue_TaskContext $ctx
381 * @param string $table
382 * @param string $indexName
383 * @return bool
384 */
385 public static function dropIndex($ctx, $table, $indexName) {
386 CRM_Core_BAO_SchemaHandler::dropIndexIfExists($table, $indexName);
387
388 return TRUE;
389 }
390
391 /**
392 * Drop a table... but only if it's empty.
393 *
394 * @param CRM_Queue_TaskContext $ctx
395 * @param string $table
396 * @return bool
397 */
398 public static function dropTableIfEmpty($ctx, $table) {
399 if (CRM_Core_DAO::checkTableExists($table)) {
400 if (!CRM_Core_DAO::checkTableHasData($table)) {
401 CRM_Core_BAO_SchemaHandler::dropTable($table);
402 }
403 else {
404 $ctx->log->warning("dropTableIfEmpty($table): Found data. Preserved table.");
405 }
406 }
407
408 return TRUE;
409 }
410
411 /**
412 * Rebuild Multilingual Schema.
413 * @param CRM_Queue_TaskContext $ctx
414 * @param string|null $version CiviCRM version to use if rebuilding multilingual schema
415 *
416 * @return bool
417 */
418 public static function rebuildMultilingalSchema($ctx, $version = NULL) {
419 $locales = CRM_Core_I18n::getMultilingual();
420 if ($locales) {
421 CRM_Core_I18n_Schema::rebuildMultilingualSchema($locales, $version);
422 }
423 return TRUE;
424 }
425
426 }