Merge pull request #15670 from eileenmcnaughton/dupe_locks
[civicrm-core.git] / CRM / Upgrade / Incremental / php / FourSeven.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 /**
13 * Upgrade logic for 4.7
14 */
15 class CRM_Upgrade_Incremental_php_FourSeven extends CRM_Upgrade_Incremental_Base {
16
17 /**
18 * Compute any messages which should be displayed beforeupgrade.
19 *
20 * Note: This function is called iteratively for each upcoming
21 * revision to the database.
22 *
23 * @param string $preUpgradeMessage
24 * @param string $rev
25 * a version number, e.g. '4.4.alpha1', '4.4.beta3', '4.4.0'.
26 * @param null $currentVer
27 */
28 public function setPreUpgradeMessage(&$preUpgradeMessage, $rev, $currentVer = NULL) {
29 if ($rev == '4.7.alpha1') {
30 // CRM-16478 Remove custom fatal error template path option
31 $config = CRM_Core_Config::singleton();
32 if (!empty($config->fatalErrorTemplate) && $config->fatalErrorTemplate != 'CRM/common/fatal.tpl') {
33 $preUpgradeMessage .= '<p>' . ts('The custom fatal error template setting will be removed during the upgrade. You are currently using this custom template: %1 . Following the upgrade you will need to use the standard approach to overriding template files, as described in the documentation.', [1 => $config->fatalErrorTemplate]) . '</p>';
34 }
35 }
36 if ($rev == '4.7.alpha4') {
37 // CRM-17004 Warn of Moneris removal
38 $count = 1;
39 // Query only works in 4.3+
40 if (version_compare($currentVer, "4.3.0") > 0) {
41 $count = CRM_Core_DAO::singleValueQuery("SELECT COUNT(id) FROM civicrm_payment_processor WHERE payment_processor_type_id IN (SELECT id FROM civicrm_payment_processor_type WHERE name = 'Moneris')");
42 }
43 if ($count && !function_exists('moneris_civicrm_managed')) {
44 $preUpgradeMessage .= '<p>' . ts('The %1 payment processor is no longer bundled with CiviCRM. After upgrading you will need to install the extension to continue using it.', [1 => 'Moneris']) . '</p>';
45 }
46 }
47 if ($rev == '4.7.13') {
48 $preUpgradeMessage .= '<p>' . ts('A new permission has been added called %1 This Permission is now used to control access to the Manage Tags screen', [1 => 'manage tags']) . '</p>';
49 }
50 if ($rev == '4.7.22') {
51 // Based on support inquiries for 4.7.21, show message during 4.7.22.
52 // For affected users, this issue prevents loading the regular status screen.
53 if (!$this->checkImageUploadDir()) {
54 $preUpgradeMessage .= '<p>' . ts('There appears to be an inconsistency in the configuration of "Image Upload URL" and "Image Upload Directory".') . '</p>'
55 . '<p>'
56 . ts('Further advice will be displayed at the end of the upgrade.')
57 . '</p>';
58 }
59 }
60 if ($rev == '4.7.27') {
61 $params = [
62 1 => 'Close accounting batches created by user',
63 2 => 'Close all accounting batches',
64 3 => 'Reopen accounting batches created by user',
65 4 => 'Reopen all accounting batches',
66 5 => 'https://wiki.civicrm.org/confluence/display/CRMDOC/Default+Permissions+and+Roles',
67 ];
68 $preUpgradeMessage .= '<p>' . ts('A new set of batch permissions has been added called "%1", "%2", "%3" and "%4". These permissions are now used to control access to the Accounting Batches tasks. If your users need to be able to Reopen or Close batches you may need to give them additional permissions. <a href=%5>Read more</a>', $params) . '</p>';
69 }
70 if ($rev == '4.7.32') {
71 $preUpgradeMessage .= '<p>' . ts('A new %1 permission has been added. It is not granted by default. If you use SMS, you may wish to review your permissions.', [1 => 'send SMS']) . '</p>';
72 }
73 }
74
75 /**
76 * Compute any messages which should be displayed after upgrade.
77 *
78 * @param string $postUpgradeMessage
79 * alterable.
80 * @param string $rev
81 * an intermediate version; note that setPostUpgradeMessage is called repeatedly with different $revs.
82 */
83 public function setPostUpgradeMessage(&$postUpgradeMessage, $rev) {
84 if ($rev == '4.7.alpha1') {
85 $config = CRM_Core_Config::singleton();
86 // FIXME: Performing an upgrade step during postUpgrade message phase is probably bad
87 $editor_id = self::updateWysiwyg();
88 $msg = NULL;
89 $ext_href = 'href="' . CRM_Utils_System::url('civicrm/admin/extensions', 'reset=1') . '"';
90 $dsp_href = 'href="' . CRM_Utils_System::url('civicrm/admin/setting/preferences/display', 'reset=1') . '"';
91 $blog_href = 'href="https://civicrm.org/blogs/colemanw/big-changes-wysiwyg-editing-47"';
92 switch ($editor_id) {
93 // TinyMCE
94 case 1:
95 $msg = ts('Your configured editor "TinyMCE" is no longer part of the main CiviCRM download. To continue using it, visit the <a %1>Manage Extensions</a> page to download and install the TinyMCE extension.', [1 => $ext_href]);
96 break;
97
98 // Drupal/Joomla editor
99 case 3:
100 case 4:
101 $msg = ts('CiviCRM no longer integrates with the "%1 Default Editor." Your wysiwyg setting has been reset to the built-in CKEditor. <a %2>Learn more...</a>', [1 => $config->userFramework, 2 => $blog_href]);
102 break;
103 }
104 if ($msg) {
105 $postUpgradeMessage .= '<p>' . $msg . '</p>';
106 }
107 $postUpgradeMessage .= '<p>' . ts('CiviCRM now includes the easy-to-use CKEditor Configurator. To customize the features and display of your wysiwyg editor, visit the <a %1>Display Preferences</a> page. <a %2>Learn more...</a>', [1 => $dsp_href, 2 => $blog_href]) . '</p>';
108
109 $postUpgradeMessage .= '<br /><br />' . ts('Default version of the following System Workflow Message Templates have been modified: <ul><li>Personal Campaign Pages - Owner Notification</li></ul> If you have modified these templates, please review the new default versions and implement updates as needed to your copies (Administer > Communications > Message Templates > System Workflow Messages).');
110
111 $postUpgradeMessage .= '<p>' . ts('The custom fatal error template setting has been removed.') . '</p>';
112 }
113 //if ($rev == '4.7.11') {
114 // $postUpgradeMessage .= '<br /><br />' . ts("WARNING: For increased security, profile submissions embedded in remote sites are no longer allowed to create or edit data by default. If you need to allow users to submit profiles from external sites, you can restore this at Administer > System Settings > Misc (Undelete, PDFs, Limits, Logging, Captcha, etc.) > 'Accept profile submissions from external sites'");
115 //}
116 if ($rev == '4.7.11') {
117 $postUpgradeMessage .= '<br /><br />' . ts("By default, CiviCRM now disables the ability to import directly from SQL. To use this feature, you must explicitly grant permission 'import SQL datasource'.");
118 }
119 if ($rev == '4.7.14') {
120 $ck_href = 'href="' . CRM_Utils_System::url('civicrm/admin/ckeditor') . '"';
121 $postUpgradeMessage .= '<p>' . ts('CiviMail no longer forces CKEditor to add html/head/body tags to email content because some sites place these in the message header/footer. This was added in 4.7.5 and is now disabled by default.')
122 . '<br />' . ts('You can re-enable it by visiting the <a %1>CKEditor Config</a> screen and setting "fullPage = true" under the Advanced Options of the CiviMail preset.', [1 => $ck_href])
123 . '</p>';
124 }
125 if ($rev == '4.7.19') {
126 $postUpgradeMessage .= '<br /><br />' . ts('Default version of the following System Workflow Message Templates have been modified: <ul><li>Additional Payment Receipt or Refund Notification</li><li>Contribution Invoice</li></ul> If you have modified these templates, please review the new default versions and implement updates as needed to your copies (Administer > Communications > Message Templates > System Workflow Messages).');
127 $check = CRM_Core_DAO::singleValueQuery("SELECT count(id) FROM civicrm_domain");
128 $smsCheck = CRM_Core_DAO::singleValueQuery("SELECT count(id) FROM civicrm_sms_provider");
129 if ($check > 1 && (bool) $smsCheck) {
130 $postUpgradeMessage .= '<p>civicrm_sms_provider ' . ts('has now had a domain id column added. As there is more than 1 domains in this install you need to manually set the domain id for the providers in this install') . '</p>';
131 }
132 }
133 if ($rev == '4.7.22') {
134 // Based on support inquiries for 4.7.21, show message during 4.7.22.
135 // For affected users, this issue prevents loading the regular status screen.
136 if (!$this->checkImageUploadDir()) {
137 $config = CRM_Core_Config::singleton();
138 $postUpgradeMessage .=
139 '<h3>' . ts('Warning') . '</h3>'
140 . '<p>' . ts('There appears to be an inconsistency in the configuration of "Image Upload URL" and "Image Upload Directory".') . '</p>'
141 . sprintf("<ul><li><b>imageUploadDir</b>: <code>%s</code></li><li><b>imageUploadURL</b>: <code>%s</code></li></ul>", htmlentities($config->imageUploadDir), htmlentities($config->imageUploadURL))
142 . '<p>'
143 . ts('You may need to check that: <ul><li>(a) the path and URL match,</li><li> (b) the httpd/htaccess policy allows requests for files inside this folder,</li><li>and (c) the web domain matches the normal web domain.</ul>')
144 . '</p>'
145 . '<p><em>'
146 . ts('(Note: Although files should be readable, it is best if they are not listable or browseable.)')
147 . '</em></p>'
148 . '<p>'
149 . ts('If this remains unresolved, then some important screens may fail to load.')
150 . '</p>';
151 }
152 }
153 if ($rev == '4.7.23') {
154 $postUpgradeMessage .= '<br /><br />' . ts('Default version of the following System Workflow Message Templates have been modified: <ul><li>Contribution Invoice</li></ul> If you have modified these templates, please review the new default versions and implement updates as needed to your copies (Administer > Communications > Message Templates > System Workflow Messages).');
155 }
156 }
157
158 /**
159 * Upgrade function.
160 *
161 * @param string $rev
162 */
163 public function upgrade_4_7_alpha1($rev) {
164 $this->addTask('Drop action scheudle mapping foreign key', 'dropActionScheudleMappingForeignKey');
165 $this->addTask('Migrate \'on behalf of\' information to module_data', 'migrateOnBehalfOfInfo');
166 $this->addTask(ts('Upgrade DB to %1: SQL', [1 => $rev]), 'runSql', $rev);
167 $this->addTask(ts('Migrate Settings to %1', [1 => $rev]), 'migrateSettings', $rev);
168 $this->addTask('Add Getting Started dashlet', 'addGettingStartedDashlet', $rev);
169 }
170
171 /**
172 * Upgrade function.
173 *
174 * @param string $rev
175 */
176 public function upgrade_4_7_alpha4($rev) {
177 $this->addTask(ts('Upgrade DB to %1: SQL', [1 => $rev]), 'runSql', $rev);
178 $this->addTask(ts('Remove %1', [1 => 'Moneris']), 'removePaymentProcessorType', 'Moneris');
179 $this->addTask('Update Smart Groups', 'fixContactTypeInSmartGroups');
180 }
181
182 /**
183 * Upgrade function.
184 *
185 * @param string $rev
186 */
187 public function upgrade_4_7_beta2($rev) {
188 $this->addTask(ts('Upgrade DB to %1: SQL', [1 => $rev]), 'runSql', $rev);
189 $this->addTask('Delete unused file', 'deleteVersionCheckCacheFile');
190 }
191
192 /**
193 * Upgrade function.
194 *
195 * @param string $rev
196 */
197 public function upgrade_4_7_beta6($rev) {
198 $this->addTask(ts('Upgrade DB to %1: SQL', [1 => $rev]), 'runSql', $rev);
199 $this->addTask('Disable flexible jobs extension', 'disableFlexibleJobsExtension');
200 $this->addTask('Add Index to financial_trxn trxn_id field', 'addIndexFinancialTrxnTrxnID');
201 }
202
203 /**
204 * Upgrade function.
205 *
206 * @param string $rev
207 */
208 public function upgrade_4_7_1($rev) {
209 $this->addTask(ts('Upgrade DB to %1: SQL', [1 => $rev]), 'runSql', $rev);
210 $this->addTask('Add Index to civicrm_contribution creditnote_id field', 'addIndexContributionCreditNoteID');
211 }
212
213 /**
214 * Upgrade function.
215 *
216 * @param string $rev
217 */
218 public function upgrade_4_7_2($rev) {
219 $this->addTask(ts('Upgrade DB to %1: SQL', [1 => $rev]), 'runSql', $rev);
220 $this->addTask('Fix Index on civicrm_financial_item combined entity_id + entity_table', 'addCombinedIndexFinancialItemEntityIDEntityType');
221 $this->addTask('enable financial account relationships for chargeback & refund', 'addRefundAndChargeBackAccountsIfNotExist');
222 $this->addTask('Add Index to civicrm_contribution.source', 'addIndexContributionSource');
223 }
224
225 /**
226 * Upgrade function.
227 *
228 * @param string $rev
229 */
230 public function upgrade_4_7_3($rev) {
231 $this->addTask(ts('Upgrade DB to %1: SQL', [1 => $rev]), 'runSql', $rev);
232 $this->addTask('Add Index to civicrm_contribution.total_amount', 'addIndexContributionAmount');
233 }
234
235 /**
236 * Upgrade function.
237 *
238 * @param string $rev
239 */
240 public function upgrade_4_7_4($rev) {
241 $this->addTask(ts('Upgrade DB to %1: SQL', [1 => $rev]), 'runSql', $rev);
242 $this->addTask('Add Contact Deleted by Merge Activity Type', 'addDeletedByMergeActivityType');
243 }
244
245 /**
246 * Upgrade function.
247 *
248 * @param string $rev
249 */
250 public function upgrade_4_7_7($rev) {
251 $this->addTask(ts('Upgrade DB to %1: SQL', [1 => $rev]), 'runSql', $rev);
252 // https://issues.civicrm.org/jira/browse/CRM-18006
253 if (CRM_Core_DAO::checkTableExists('civicrm_install_canary')) {
254 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_install_canary ENGINE=InnoDB');
255 }
256 }
257
258 /**
259 * Upgrade function.
260 *
261 * @param string $rev
262 */
263 public function upgrade_4_7_8($rev) {
264 $this->addTask(ts('Upgrade DB to %1: SQL', [1 => $rev]), 'runSql', $rev);
265 $this->addTask('Upgrade mailing foreign key constraints', 'upgradeMailingFKs');
266 }
267
268 /**
269 * Upgrade function.
270 *
271 * @param string $rev
272 */
273 public function upgrade_4_7_10($rev) {
274 $this->addTask(ts('Upgrade DB to %1: SQL', [1 => $rev]), 'runSql', $rev);
275 $this->addTask('Upgrade Add Help Pre and Post Fields to price value table', 'addHelpPreAndHelpPostFieldsPriceFieldValue');
276 $this->addTask('Alter index and type for image URL', 'alterIndexAndTypeForImageURL');
277 }
278
279 /**
280 * Upgrade function.
281 *
282 * @param string $rev
283 */
284 public function upgrade_4_7_11($rev) {
285 $this->addTask(ts('Upgrade DB to %1: SQL', [1 => $rev]), 'runSql', $rev);
286 $this->addTask('Dashboard schema updates', 'dashboardSchemaUpdate');
287 $this->addTask('Fill in setting "remote_profile_submissions"', 'migrateRemoteSubmissionsSetting');
288 }
289
290 /**
291 * Upgrade function.
292 *
293 * @param string $rev
294 */
295 public function upgrade_4_7_12($rev) {
296 $this->addTask(ts('Upgrade DB to %1: SQL', [1 => $rev]), 'runSql', $rev);
297 $this->addTask('Add Data Type column to civicrm_option_group', 'addDataTypeColumnToOptionGroupTable');
298 }
299
300 /**
301 * Upgrade function.
302 *
303 * @param string $rev
304 */
305 public function upgrade_4_7_13($rev) {
306 $this->addTask(ts('Upgrade DB to %1: SQL', [1 => $rev]), 'runSql', $rev);
307 $this->addTask('CRM-19372 - Add column to allow for payment processors to set what card types are accepted', 'addColumn',
308 'civicrm_payment_processor', 'accepted_credit_cards', "text DEFAULT NULL COMMENT 'array of accepted credit card types'");
309 }
310
311 /**
312 * Upgrade function.
313 *
314 * @param string $rev
315 */
316 public function upgrade_4_7_14($rev) {
317 $this->addTask(ts('Upgrade DB to %1: SQL', [1 => $rev]), 'runSql', $rev);
318 $this->addTask('Add WYSIWYG Editor Presets', 'addWysiwygPresets');
319 }
320
321 /**
322 * Upgrade function.
323 *
324 * @param string $rev
325 */
326 public function upgrade_4_7_15($rev) {
327 $this->addTask('CRM-19626 - Add min_amount column to civicrm_price_set', 'addColumn',
328 'civicrm_price_set', 'min_amount', "INT(10) UNSIGNED DEFAULT '0' COMMENT 'Minimum Amount required for this set.'");
329 $this->addTask(ts('Upgrade DB to %1: SQL', [1 => $rev]), 'runSql', $rev);
330 }
331
332 /**
333 * Upgrade function.
334 *
335 * @param string $rev
336 */
337 public function upgrade_4_7_16($rev) {
338 $this->addTask('CRM-19723 - Add icon column to civicrm_option_value', 'addColumn',
339 'civicrm_option_value', 'icon', "varchar(255) COMMENT 'crm-i icon class' DEFAULT NULL");
340 $this->addTask('CRM-19769 - Add color column to civicrm_tag', 'addColumn',
341 'civicrm_tag', 'color', "varchar(255) COMMENT 'Hex color value e.g. #ffffff' DEFAULT NULL");
342 $this->addTask('CRM-19779 - Add color column to civicrm_option_value', 'addColumn',
343 'civicrm_option_value', 'color', "varchar(255) COMMENT 'Hex color value e.g. #ffffff' DEFAULT NULL");
344 $this->addTask('Add new CiviMail fields', 'addMailingTemplateType');
345 $this->addTask('CRM-19770 - Add is_star column to civicrm_activity', 'addColumn',
346 'civicrm_activity', 'is_star', "tinyint DEFAULT '0' COMMENT 'Activity marked as favorite.'");
347 $this->addTask(ts('Upgrade DB to %1: SQL', [1 => $rev]), 'runSql', $rev);
348 }
349
350 /**
351 * Upgrade function.
352 *
353 * @param string $rev
354 */
355 public function upgrade_4_7_18($rev) {
356 $this->addTask('Update Kenyan Provinces', 'updateKenyanProvinces');
357 $this->addTask(ts('Upgrade DB to %1: SQL', [1 => $rev]), 'runSql', $rev);
358 }
359
360 /**
361 * Upgrade function.
362 *
363 * @param string $rev
364 */
365 public function upgrade_4_7_19($rev) {
366 if (CRM_Core_BAO_SchemaHandler::checkIfFieldExists('civicrm_financial_account', 'opening_balance')) {
367 $query = "SELECT id FROM civicrm_financial_account WHERE opening_balance <> 0 OR current_period_opening_balance <> 0";
368 $result = CRM_Core_DAO::executeQuery($query);
369 if (!$result->N) {
370 $this->addTask('Drop Column current_period_opening_balance From civicrm_financial_account table.', 'dropColumn', 'civicrm_financial_account', 'current_period_opening_balance');
371 $this->addTask('Drop Column opening_balance From civicrm_financial_account table.', 'dropColumn', 'civicrm_financial_account', 'opening_balance');
372 }
373 }
374 $this->addTask('CRM-19961 - Add domain_id column to civicrm_sms_provider', 'addColumn',
375 'civicrm_sms_provider', 'domain_id', "int(10) unsigned COMMENT 'Which Domain is this sms provier for'");
376 $this->addTask('CRM-19961 - Populate domain id table and perhaps add foreign key', 'populateSMSProviderDomainId');
377 $this->addTask(ts('Upgrade DB to %1: SQL', [1 => $rev]), 'runSql', $rev);
378 $this->addTask('CRM-16633 - Add "Change Case Subject" activity', 'addChangeCaseSubjectActivityType');
379 $this->addTask('Add is_public column to civicrm_custom_group', 'addColumn',
380 'civicrm_custom_group', 'is_public', "boolean DEFAULT '1' COMMENT 'Is this property public?'");
381 }
382
383 /**
384 * Upgrade function.
385 *
386 * @param string $rev
387 */
388 public function upgrade_4_7_20($rev) {
389 $this->addtask('Fix Schema on civicrm_action_schedule', 'fixSchemaOnCiviCRMActionSchedule');
390 $this->addTask(ts('Upgrade DB to %1: SQL', [1 => $rev]), 'runSql', $rev);
391 $this->addTask('Add activity_status column to civicrm_mail_settings', 'addColumn',
392 'civicrm_mail_settings', 'activity_status', "varchar (255) DEFAULT NULL COMMENT 'Name of status to use when creating email to activity.'");
393 }
394
395 /**
396 * Upgrade function.
397 *
398 * @param string $rev
399 */
400 public function upgrade_4_7_23($rev) {
401 $this->addTask('CRM-20387 - Add invoice_number column to civicrm_contribution', 'addColumn',
402 'civicrm_contribution', 'invoice_number', "varchar(255) COMMENT 'Human readable invoice number' DEFAULT NULL");
403 $this->addTask(ts('Upgrade DB to %1: SQL', [1 => $rev]), 'runSql', $rev);
404 }
405
406 /**
407 * Upgrade function.
408 *
409 * @param string $rev
410 */
411 public function upgrade_4_7_25($rev) {
412 $this->addTask("CRM-20927 - Add column to 'civicrm_menu' for additional metadata", 'addColumn',
413 'civicrm_menu', 'module_data', "text COMMENT 'All other menu metadata not stored in other fields'");
414 $this->addTask('CRM-21052 - Determine activity revision policy', 'pickActivityRevisionPolicy');
415 $this->addTask(ts('Upgrade DB to %1: SQL', [1 => $rev]), 'runSql', $rev);
416 $this->addTask('Add cancel button text column to civicrm_uf_group', 'addColumn',
417 'civicrm_uf_group', 'cancel_button_text', "varchar(64) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Custom Text to display on the cancel button when used in create or edit mode'", TRUE);
418 $this->addTask('Add Submit button text column to civicrm_uf_group', 'addColumn',
419 'civicrm_uf_group', 'submit_button_text', "varchar(64) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Custom Text to display on the submit button on profile edit/create screens'", TRUE);
420
421 $this->addTask('CRM-20958 - Add created_date to civicrm_activity', 'addColumn',
422 'civicrm_activity', 'created_date', "timestamp NULL DEFAULT NULL COMMENT 'When was the activity was created.'");
423 $this->addTask('CRM-20958 - Add modified_date to civicrm_activity', 'addColumn',
424 'civicrm_activity', 'modified_date', "timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'When was the activity (or closely related entity) was created or modified or deleted.'");
425 $this->addTask('CRM-20958 - Add created_date to civicrm_case', 'addColumn',
426 'civicrm_case', 'created_date', "timestamp NULL DEFAULT NULL COMMENT 'When was the case was created.'");
427 $this->addTask('CRM-20958 - Add modified_date to civicrm_case', 'addColumn',
428 'civicrm_case', 'modified_date', "timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'When was the case (or closely related entity) was created or modified or deleted.'");
429 }
430
431 /**
432 * Upgrade function.
433 *
434 * @param string $rev
435 */
436 public function upgrade_4_7_27($rev) {
437 $this->addTask(ts('Upgrade DB to %1: SQL', [1 => $rev]), 'runSql', $rev);
438 $this->addTask('CRM-20892 Change created_date to default to NULL', 'civiMailingCreatedDateNull');
439 $this->addTask('CRM-21234 Missing subdivisions of Tajikistan', 'tajikistanMissingSubdivisions');
440 $this->addTask('CRM-20892 - Add modified_date to civicrm_mailing', 'addColumn',
441 'civicrm_mailing', 'modified_date', "timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'When the mailing (or closely related entity) was created or modified or deleted.'");
442 $this->addTask('CRM-21195 - Add icon field to civicrm_navigation', 'addColumn',
443 'civicrm_navigation', 'icon', "varchar(255) NULL DEFAULT NULL COMMENT 'CSS class name for an icon'");
444 $this->addTask('CRM-12167 - Add visibility column to civicrm_price_field_value', 'addColumn',
445 'civicrm_price_field_value', 'visibility_id', 'int(10) unsigned DEFAULT 1 COMMENT "Implicit FK to civicrm_option_group with name = \'visibility\'"');
446 $this->addTask('Remove broken Contribution_logging reports', 'removeContributionLoggingReports');
447 }
448
449 /**
450 * Upgrade function.
451 *
452 * @param string $rev
453 */
454 public function upgrade_4_7_28($rev) {
455 $this->addTask(ts('Upgrade DB to %1: SQL', [1 => $rev]), 'runSql', $rev);
456 $this->addTask('CRM-20572: Fix date fields in save search criteria of Contrib Sybunt custom search ', 'fixDateFieldsInSmartGroups');
457 // CRM-20868 : Update invoice_numbers (in batch) with value in [invoice prefix][contribution id] format
458 if ($invoicePrefix = CRM_Contribute_BAO_Contribution::checkContributeSettings('invoice_prefix', TRUE)) {
459 list($minId, $maxId) = CRM_Core_DAO::executeQuery("SELECT coalesce(min(id),0), coalesce(max(id),0)
460 FROM civicrm_contribution ")->getDatabaseResult()->fetchRow();
461 for ($startId = $minId; $startId <= $maxId; $startId += self::BATCH_SIZE) {
462 $endId = $startId + self::BATCH_SIZE - 1;
463 $title = ts("Upgrade DB to %1: Update Contribution Invoice number (%2 => %3)", [
464 1 => $rev,
465 2 => $startId,
466 3 => $endId,
467 ]);
468 $this->addTask($title, 'updateContributionInvoiceNumber', $startId, $endId, $invoicePrefix);
469 }
470 }
471
472 }
473
474 /**
475 * Upgrade function.
476 *
477 * @param string $rev
478 */
479 public function upgrade_4_7_31($rev) {
480 $this->addTask('CRM-21225: Add display title field to civicrm_uf_group', 'addColumn', 'civicrm_uf_group', 'frontend_title',
481 "VARCHAR(64) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL COMMENT 'Profile Form Public title'", TRUE, '4.7.31');
482 $this->addTask(ts('Upgrade DB to %1: SQL', [1 => $rev]), 'runSql', $rev);
483 $this->addTask('Rebuild Multilingual Schema', 'rebuildMultilingalSchema', '4.7.31');
484 }
485
486 /**
487 * Upgrade function.
488 *
489 * @param string $rev
490 */
491 public function upgrade_4_7_32($rev) {
492 $this->addTask(ts('Upgrade DB to %1: SQL', [1 => $rev]), 'runSql', $rev);
493
494 $this->addTask('CRM-21733: Add status_override_end_date field to civicrm_membership table', 'addColumn', 'civicrm_membership', 'status_override_end_date',
495 "date DEFAULT NULL COMMENT 'The end date of membership status override if (Override until selected date) override type is selected.'");
496 }
497
498 /*
499 * Important! All upgrade functions MUST add a 'runSql' task.
500 * Uncomment and use the following template for a new upgrade version
501 * (change the x in the function name):
502 */
503
504 // /**
505 // * Upgrade function.
506 // *
507 // * @param string $rev
508 // */
509 // public function upgrade_4_7_x($rev) {
510 // $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
511 // // Additional tasks here...
512 // // Note: do not use ts() in the addTask description because it adds unnecessary strings to transifex.
513 // // The above is an exception because 'Upgrade DB to %1: SQL' is generic & reusable.
514 // }
515
516 /**
517 * CRM-16354
518 *
519 * @return int
520 */
521 public static function updateWysiwyg() {
522 $editorID = Civi::settings()->get('editor_id');
523 // Previously a numeric value indicated one of 4 wysiwyg editors shipped in core, and no value indicated 'Textarea'
524 // Now the options are "Textarea", "CKEditor", and the rest have been dropped from core.
525 $newEditor = $editorID ? "CKEditor" : "Textarea";
526 Civi::settings()->set('editor_id', $newEditor);
527
528 return $editorID;
529 }
530
531 /**
532 * Migrate any last remaining options from `civicrm_domain.config_backend` to `civicrm_setting`.
533 * Cleanup setting schema.
534 *
535 * @param CRM_Queue_TaskContext $ctx
536 * @return bool
537 */
538 public static function migrateSettings(CRM_Queue_TaskContext $ctx) {
539 // Tip: If there are problems with adding the new uniqueness index, try inspecting:
540 // SELECT name, domain_id, contact_id, count(*) AS dupes FROM civicrm_setting cs GROUP BY name, domain_id, contact_id HAVING dupes > 1;
541
542 // Nav records are expendable. https://forum.civicrm.org/index.php?topic=36933.0
543 CRM_Core_DAO::executeQuery('DELETE FROM civicrm_setting WHERE contact_id IS NOT NULL AND name = "navigation"');
544
545 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_setting DROP INDEX index_group_name');
546 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_setting DROP COLUMN group_name');
547
548 // Handle Strange activity_tab_filter settings.
549 CRM_Core_DAO::executeQuery('CREATE TABLE civicrm_activity_setting LIKE civicrm_setting');
550 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_activity_setting ADD UNIQUE INDEX index_domain_contact_name (domain_id, contact_id, name)');
551 CRM_Core_DAO::executeQuery('INSERT INTO civicrm_activity_setting (name, contact_id, domain_id, value)
552 SELECT DISTINCT name, contact_id, domain_id, value
553 FROM civicrm_setting
554 WHERE name = "activity_tab_filter"
555 AND value is not NULL');
556 CRM_Core_DAO::executeQuery('DELETE FROM civicrm_setting WHERE name = "activity_tab_filter"');
557
558 $date = CRM_Utils_Time::getTime('Y-m-d H:i:s');
559 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_setting ADD UNIQUE INDEX index_domain_contact_name (domain_id, contact_id, name)');
560 CRM_Core_DAO::executeQuery("INSERT INTO civicrm_setting (name, contact_id, domain_id, value, is_domain, created_id, created_date)
561 SELECT name, contact_id, domain_id, value, 0, contact_id,'$date'
562 FROM civicrm_activity_setting
563 WHERE name = 'activity_tab_filter'
564 AND value is not NULL"
565 );
566 CRM_Core_DAO::executeQuery('DROP TABLE civicrm_activity_setting');
567
568 $domainDao = CRM_Core_DAO::executeQuery('SELECT id, config_backend FROM civicrm_domain');
569 while ($domainDao->fetch()) {
570 $settings = CRM_Upgrade_Incremental_php_FourSeven::convertBackendToSettings($domainDao->id, $domainDao->config_backend);
571 CRM_Core_Error::debug_var('convertBackendToSettings', [
572 'domainId' => $domainDao->id,
573 'backend' => $domainDao->config_backend,
574 'settings' => $settings,
575 ]);
576
577 foreach ($settings as $name => $value) {
578 $rowParams = [
579 1 => [$domainDao->id, 'Positive'],
580 2 => [$name, 'String'],
581 3 => [serialize($value), 'String'],
582 ];
583 $settingId = CRM_Core_DAO::singleValueQuery(
584 'SELECT id FROM civicrm_setting WHERE domain_id = %1 AND name = %2',
585 $rowParams);
586 if (!$settingId) {
587 CRM_Core_DAO::executeQuery(
588 'INSERT INTO civicrm_setting (domain_id, name, value, is_domain) VALUES (%1,%2,%3,1)',
589 $rowParams);
590 }
591 }
592 }
593
594 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_domain DROP COLUMN config_backend');
595
596 return TRUE;
597 }
598
599 /**
600 * Take a config_backend blob and produce an equivalent list of settings.
601 *
602 * @param int $domainId
603 * Domain ID.
604 * @param string $config_backend
605 * Serialized blob.
606 * @return array
607 */
608 public static function convertBackendToSettings($domainId, $config_backend) {
609 if (!$config_backend) {
610 return [];
611 }
612
613 $backend = unserialize($config_backend);
614 if (!$backend) {
615 return [];
616 }
617
618 $mappings = \CRM_Core_Config_MagicMerge::getPropertyMap();
619 $settings = [];
620 foreach ($backend as $propertyName => $propertyValue) {
621 if (isset($mappings[$propertyName][0]) && preg_match('/^setting/', $mappings[$propertyName][0])) {
622 // $mapping format: $propertyName => Array(0 => $type, 1 => $setting|NULL).
623 $settingName = isset($mappings[$propertyName][1]) ? $mappings[$propertyName][1] : $propertyName;
624 $settings[$settingName] = $propertyValue;
625 }
626 }
627
628 return $settings;
629 }
630
631 /**
632 * Update Invoice number for all completed contribution.
633 *
634 * @param \CRM_Queue_TaskContext $ctx
635 * @param int $startID
636 * @param int $endID
637 * @param string $invoicePrefix
638 *
639 * @return bool
640 */
641 public static function updateContributionInvoiceNumber(CRM_Queue_TaskContext $ctx, $startID, $endID, $invoicePrefix) {
642 CRM_Core_DAO::executeQuery("
643 UPDATE `civicrm_contribution` SET `invoice_number` = CONCAT(%1, `id`)
644 WHERE `id` >= %2 AND `id` <= %3 AND `invoice_number` IS NOT NULL",
645 [
646 1 => [$invoicePrefix, 'String'],
647 2 => [$startID, 'Integer'],
648 3 => [$endID, 'Integer'],
649 ]
650 );
651
652 return TRUE;
653 }
654
655 /**
656 * Add Getting Started dashlet to dashboard
657 *
658 * @param \CRM_Queue_TaskContext $ctx
659 *
660 * @return bool
661 */
662 public static function addGettingStartedDashlet(CRM_Queue_TaskContext $ctx) {
663 $sql = "SELECT count(*) FROM civicrm_dashboard WHERE name='getting-started'";
664 $res = CRM_Core_DAO::singleValueQuery($sql);
665 $domainId = CRM_Core_Config::domainID();
666 if ($res <= 0) {
667 $sql = "INSERT INTO `civicrm_dashboard`
668 ( `domain_id`, `name`, `label`, `url`, `permission`, `permission_operator`, `column_no`, `is_minimized`, `is_active`, `weight`, `fullscreen_url`, `is_fullscreen`, `is_reserved`) VALUES ( {$domainId}, 'getting-started', 'Getting Started', 'civicrm/dashlet/getting-started?reset=1&snippet=5', 'access CiviCRM', NULL, 0, 0, 1, 0, 'civicrm/dashlet/getting-started?reset=1&snippet=5&context=dashletFullscreen', 1, 1)";
669 CRM_Core_DAO::executeQuery($sql);
670 // Add default position for Getting Started Dashlet ( left column)
671 $sql = "INSERT INTO `civicrm_dashboard_contact` (dashboard_id, contact_id, column_no, is_active)
672 SELECT (SELECT MAX(id) FROM `civicrm_dashboard`), contact_id, 0, IF (SUM(is_active) > 0, 1, 0)
673 FROM `civicrm_dashboard_contact` JOIN `civicrm_contact` WHERE civicrm_dashboard_contact.contact_id = civicrm_contact.id GROUP BY contact_id";
674 CRM_Core_DAO::executeQuery($sql);
675 }
676 return TRUE;
677 }
678
679 /**
680 * Migrate on-behalf information to uf_join.module_data as on-behalf columns will be dropped
681 * on DB upgrade
682 *
683 * @param CRM_Queue_TaskContext $ctx
684 *
685 * @return bool
686 * TRUE for success
687 */
688 public static function migrateOnBehalfOfInfo(CRM_Queue_TaskContext $ctx) {
689 $domain = new CRM_Core_DAO_Domain();
690 $domain->find(TRUE);
691
692 // fetch onBehalf entry in UFJoin table
693 $ufGroupDAO = new CRM_Core_DAO_UFJoin();
694 $ufGroupDAO->module = 'OnBehalf';
695 $ufGroupDAO->find(TRUE);
696
697 $forOrgColums = ['is_for_organization'];
698 if ($domain->locales) {
699 $locales = explode(CRM_Core_DAO::VALUE_SEPARATOR, $domain->locales);
700 foreach ($locales as $locale) {
701 $forOrgColums[] = "for_organization_{$locale}";
702 }
703 }
704 else {
705 $forOrgColums[] = "for_organization";
706 }
707
708 $query = "
709 SELECT " . implode(", ", $forOrgColums) . ", uj.id as join_id, uj.uf_group_id as uf_group_id
710 FROM civicrm_contribution_page cp
711 INNER JOIN civicrm_uf_join uj ON uj.entity_id = cp.id AND uj.module = 'OnBehalf'";
712 $dao = CRM_Core_DAO::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
713
714 if ($dao->N) {
715 while ($dao->fetch()) {
716 $onBehalfParams['on_behalf'] = ['is_for_organization' => $dao->is_for_organization];
717 if ($domain->locales) {
718 foreach ($locales as $locale) {
719 $for_organization = "for_organization_{$locale}";
720 $onBehalfParams['on_behalf'] += [
721 $locale => [
722 'for_organization' => $dao->$for_organization,
723 ],
724 ];
725 }
726 }
727 else {
728 $onBehalfParams['on_behalf'] += [
729 'default' => [
730 'for_organization' => $dao->for_organization,
731 ],
732 ];
733 }
734 $ufJoinParam = [
735 'id' => $dao->join_id,
736 'module' => 'on_behalf',
737 'uf_group_id' => $dao->uf_group_id,
738 'module_data' => json_encode($onBehalfParams),
739 ];
740 CRM_Core_BAO_UFJoin::create($ufJoinParam);
741 }
742 }
743
744 return TRUE;
745 }
746
747 /**
748 * v4.7.11 adds a new setting "remote_profile_submissions". This is
749 * long-standing feature that existing sites may be using; however, it's
750 * a bit prone to abuse. For new sites, the default is to disable it
751 * (since that is more secure). For existing sites, the default is to
752 * enable it (since that is more compatible).
753 *
754 * @param \CRM_Queue_TaskContext $ctx
755 *
756 * @return bool
757 */
758 public static function migrateRemoteSubmissionsSetting(CRM_Queue_TaskContext $ctx) {
759 $domains = CRM_Core_DAO::executeQuery("SELECT DISTINCT d.id FROM civicrm_domain d LEFT JOIN civicrm_setting s ON d.id=s.domain_id AND s.name = 'remote_profile_submissions' WHERE s.id IS NULL");
760 while ($domains->fetch()) {
761 CRM_Core_DAO::executeQuery(
762 "INSERT INTO civicrm_setting (`name`, `value`, `domain_id`, `is_domain`, `contact_id`, `component_id`, `created_date`, `created_id`)
763 VALUES (%2, %3, %4, %5, NULL, NULL, %6, NULL)",
764 [
765 2 => ['remote_profile_submissions', 'String'],
766 3 => ['s:1:"1";', 'String'],
767 4 => [$domains->id, 'Integer'],
768 5 => [1, 'Integer'],
769 6 => [date('Y-m-d H:i:s'), 'String'],
770 ]
771 );
772 }
773 return TRUE;
774 }
775
776 /**
777 * CRM-11782 - Get rid of VALUE_SEPARATOR character in saved search form values
778 *
779 * @param \CRM_Queue_TaskContext $ctx
780 *
781 * @return bool
782 */
783 public static function fixContactTypeInSmartGroups(CRM_Queue_TaskContext $ctx) {
784 $sep = CRM_Core_DAO::VALUE_SEPARATOR;
785 $dao = CRM_Core_DAO::executeQuery("SELECT id, form_values FROM civicrm_saved_search WHERE form_values LIKE '%$sep%'");
786 while ($dao->fetch()) {
787 $formValues = unserialize($dao->form_values);
788 if (isset($formValues['contact_type']) && is_array($formValues['contact_type'])) {
789 $newVals = [];
790 foreach ($formValues['contact_type'] as $key => $val) {
791 $newVals[str_replace($sep, '__', $key)] = is_string($val) ? str_replace($sep, '__', $val) : $val;
792 }
793 $formValues['contact_type'] = $newVals;
794 }
795 CRM_Core_DAO::executeQuery("UPDATE civicrm_saved_search SET form_values = %1 WHERE id = {$dao->id}", [1 => [serialize($formValues), 'String']]);
796 }
797
798 return TRUE;
799 }
800
801 /**
802 * CRM-17637 - Ths file location has been moved; delete the old one
803 *
804 * @param \CRM_Queue_TaskContext $ctx
805 *
806 * @return bool
807 */
808 public static function deleteVersionCheckCacheFile(CRM_Queue_TaskContext $ctx) {
809 $config = CRM_Core_Config::singleton();
810 $cacheFile = $config->uploadDir . 'version-info-cache.json';
811 if (file_exists($cacheFile)) {
812 unlink($cacheFile);
813 }
814 return TRUE;
815 }
816
817 /**
818 * CRM-17669 and CRM-17686, make scheduled jobs more flexible, disable the 4.6 extension if installed
819 *
820 * @param \CRM_Queue_TaskContext $ctx
821 *
822 * @return bool
823 */
824 public static function disableFlexibleJobsExtension(CRM_Queue_TaskContext $ctx) {
825 try {
826 civicrm_api3('Extension', 'disable', ['key' => 'com.klangsoft.flexiblejobs']);
827 }
828 catch (CiviCRM_API3_Exception $e) {
829 // just ignore if the extension isn't installed
830 }
831
832 return TRUE;
833 }
834
835 /**
836 * CRM-17752 add index to civicrm_financial_trxn.trxn_id (deliberately non-unique).
837 *
838 * @param \CRM_Queue_TaskContext $ctx
839 *
840 * @return bool
841 */
842 public static function addIndexFinancialTrxnTrxnID(CRM_Queue_TaskContext $ctx) {
843 $tables = ['civicrm_financial_trxn' => ['trxn_id']];
844 CRM_Core_BAO_SchemaHandler::createIndexes($tables);
845 return TRUE;
846 }
847
848 /**
849 * CRM-17882 Add index to civicrm_contribution.credit_note_id.
850 *
851 * @param \CRM_Queue_TaskContext $ctx
852 *
853 * @return bool
854 */
855 public static function addIndexContributionCreditNoteID(CRM_Queue_TaskContext $ctx) {
856 $tables = ['civicrm_contribution' => ['creditnote_id']];
857 CRM_Core_BAO_SchemaHandler::createIndexes($tables);
858 return TRUE;
859 }
860
861 /**
862 * CRM-17775 Add correct index for table civicrm_financial_item.
863 *
864 * Note that the entity ID should always precede the entity_table as
865 * it is more unique. This is better for performance and does not cause fallback
866 * to no index if table it omitted.
867 *
868 * @return bool
869 */
870 public static function addCombinedIndexFinancialItemEntityIDEntityType() {
871 CRM_Core_BAO_SchemaHandler::dropIndexIfExists('civicrm_financial_item', 'UI_id');
872 CRM_Core_BAO_SchemaHandler::dropIndexIfExists('civicrm_financial_item', 'IX_Entity');
873 CRM_Core_BAO_SchemaHandler::createIndexes([
874 'civicrm_financial_item' => [['entity_id', 'entity_table']],
875 ]);
876 return TRUE;
877 }
878
879 /**
880 * CRM-17951 Add accounts option values for refund and chargeback.
881 *
882 * Add Chargeback contribution status and Chargeback and Contra account relationships,
883 * checking first if one exists.
884 */
885 public static function addRefundAndChargeBackAccountsIfNotExist() {
886 // First we enable and edit the record for Credit contra - this exists but is disabled for most sites.
887 // Using the ensure function (below) will not enabled a disabled option (by design).
888 CRM_Core_DAO::executeQuery("UPDATE civicrm_option_value v
889 INNER JOIN civicrm_option_group g on v.option_group_id=g.id and g.name='account_relationship'
890 SET v.is_active=1, v.label='Credit/Contra Revenue Account is', v.name='Credit/Contra Revenue Account is', v.description='Credit/Contra Revenue Account is'
891 WHERE v.name = 'Credit/Contra Account is';");
892
893 CRM_Core_BAO_OptionValue::ensureOptionValueExists([
894 'option_group_id' => 'account_relationship',
895 'name' => 'Chargeback Account is',
896 'label' => ts('Chargeback Account is'),
897 'is_active' => TRUE,
898 'component_id' => 'CiviContribute',
899 ]);
900
901 CRM_Core_BAO_OptionValue::ensureOptionValueExists([
902 'option_group_id' => 'contribution_status',
903 'name' => 'Chargeback',
904 'label' => ts('Chargeback'),
905 'is_active' => TRUE,
906 'component_id' => 'CiviContribute',
907 ]);
908 return TRUE;
909 }
910
911 /**
912 * CRM-17999 Add index to civicrm_contribution.source.
913 *
914 * @param \CRM_Queue_TaskContext $ctx
915 *
916 * @return bool
917 */
918 public static function addIndexContributionSource(CRM_Queue_TaskContext $ctx) {
919 CRM_Core_BAO_SchemaHandler::createIndexes(['civicrm_contribution' => ['source']]);
920 return TRUE;
921 }
922
923 /**
924 * CRM-18124 Add index to civicrm_contribution.total_amount.
925 *
926 * Note that I made this a combined index with receive_date because the issue included
927 * both criteria and they seemed likely to be used in conjunction to me in other cases.
928 *
929 * @param \CRM_Queue_TaskContext $ctx
930 *
931 * @return bool
932 */
933 public static function addIndexContributionAmount(CRM_Queue_TaskContext $ctx) {
934 CRM_Core_BAO_SchemaHandler::createIndexes([
935 'civicrm_contribution' => [['total_amount', 'receive_date']],
936 ]);
937 return TRUE;
938 }
939
940 /**
941 * CRM-18124 Add index to civicrm_contribution.total_amount.
942 *
943 * Note that I made this a combined index with receive_date because the issue included
944 * both criteria and they seemed likely to be used in conjunction to me in other cases.
945 *
946 * @param \CRM_Queue_TaskContext $ctx
947 *
948 * @return bool
949 */
950 public static function addDeletedByMergeActivityType(CRM_Queue_TaskContext $ctx) {
951 CRM_Core_BAO_OptionValue::ensureOptionValueExists([
952 'option_group_id' => 'activity_type',
953 'name' => 'Contact Deleted by Merge',
954 'label' => ts('Contact Deleted by Merge'),
955 'description' => ts('Contact was merged into another contact'),
956 'is_active' => TRUE,
957 'filter' => 1,
958 ]);
959 return TRUE;
960 }
961
962 /**
963 * CRM-12252 Add Help Pre and Help Post Fields for Price Field Value Table.
964 *
965 * @param \CRM_Queue_TaskContext $ctx
966 *
967 * @return bool
968 */
969 public static function addHelpPreAndHelpPostFieldsPriceFieldValue(CRM_Queue_TaskContext $ctx) {
970 $domain = new CRM_Core_DAO_Domain();
971 $domain->find(TRUE);
972 if ($domain->locales) {
973 $locales = explode(CRM_Core_DAO::VALUE_SEPARATOR, $domain->locales);
974 foreach ($locales as $locale) {
975 if (!CRM_Core_BAO_SchemaHandler::checkIfFieldExists("civicrm_price_field_value", "help_pre_{$locale}")) {
976 CRM_Core_DAO::executeQuery("ALTER TABLE `civicrm_price_field_value`
977 ADD COLUMN `help_pre_{$locale}` text COLLATE utf8_unicode_ci COMMENT 'Price field option pre help text.'", [], TRUE, NULL, FALSE, FALSE);
978 }
979 if (!CRM_Core_BAO_SchemaHandler::checkIfFieldExists("civicrm_price_field_value", "help_post_{$locale}")) {
980 CRM_Core_DAO::executeQuery("ALTER TABLE `civicrm_price_field_value`
981 ADD COLUMN `help_post_{$locale}` text COLLATE utf8_unicode_ci COMMENT 'Price field option post help text.'", [], TRUE, NULL, FALSE, FALSE);
982 }
983 }
984 CRM_Core_I18n_Schema::rebuildMultilingualSchema($locales, NULL, TRUE);
985 }
986 else {
987 if (!CRM_Core_BAO_SchemaHandler::checkIfFieldExists('civicrm_price_field_value', 'help_pre')) {
988 CRM_Core_DAO::executeQuery("ALTER TABLE `civicrm_price_field_value`
989 ADD COLUMN `help_pre` text COLLATE utf8_unicode_ci COMMENT 'Price field option pre help text.'");
990 }
991 if (!CRM_Core_BAO_SchemaHandler::checkIfFieldExists('civicrm_price_field_value', 'help_post')) {
992 CRM_Core_DAO::executeQuery("ALTER TABLE `civicrm_price_field_value`
993 ADD COLUMN `help_post` text COLLATE utf8_unicode_ci COMMENT 'Price field option post help text.'");
994 }
995 }
996 return TRUE;
997 }
998
999 /**
1000 * CRM-18464 Check if Foreign key exists and also drop any index of same name accidentially created.
1001 *
1002 * @param \CRM_Queue_TaskContext $ctx
1003 *
1004 * @return bool
1005 */
1006 public static function dropActionScheudleMappingForeignKey(CRM_Queue_TaskContext $ctx) {
1007 CRM_Core_BAO_SchemaHandler::safeRemoveFK('civicrm_action_schedule', 'FK_civicrm_action_schedule_mapping_id');
1008 return TRUE;
1009 }
1010
1011 /**
1012 * CRM-18345 Don't delete mailing data on email/phone deletion
1013 * Implemented here in CRM-18526
1014 *
1015 * @param \CRM_Queue_TaskContext $ctx
1016 *
1017 * @return bool
1018 */
1019 public static function upgradeMailingFKs(CRM_Queue_TaskContext $ctx) {
1020
1021 // Safely drop the foreign keys
1022 CRM_Core_BAO_SchemaHandler::safeRemoveFK('civicrm_mailing_event_queue', 'FK_civicrm_mailing_event_queue_email_id');
1023 CRM_Core_BAO_SchemaHandler::safeRemoveFK('civicrm_mailing_event_queue', 'FK_civicrm_mailing_event_queue_phone_id');
1024 CRM_Core_BAO_SchemaHandler::safeRemoveFK('civicrm_mailing_recipients', 'FK_civicrm_mailing_recipients_email_id');
1025 CRM_Core_BAO_SchemaHandler::safeRemoveFK('civicrm_mailing_recipients', 'FK_civicrm_mailing_recipients_phone_id');
1026
1027 // Set up the new foreign keys
1028 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
1029
1030 CRM_Core_DAO::executeQuery("
1031 ALTER TABLE `civicrm_mailing_event_queue`
1032 ADD CONSTRAINT `FK_civicrm_mailing_event_queue_email_id`
1033 FOREIGN KEY (`email_id`)
1034 REFERENCES `civicrm_email`(`id`)
1035 ON DELETE SET NULL
1036 ON UPDATE RESTRICT;
1037 ");
1038
1039 CRM_Core_DAO::executeQuery("
1040 ALTER TABLE `civicrm_mailing_event_queue`
1041 ADD CONSTRAINT `FK_civicrm_mailing_event_queue_phone_id`
1042 FOREIGN KEY (`phone_id`)
1043 REFERENCES `civicrm_phone`(`id`)
1044 ON DELETE SET NULL
1045 ON UPDATE RESTRICT;
1046 ");
1047
1048 CRM_Core_DAO::executeQuery("
1049 ALTER TABLE `civicrm_mailing_recipients`
1050 ADD CONSTRAINT `FK_civicrm_mailing_recipients_email_id`
1051 FOREIGN KEY (`email_id`)
1052 REFERENCES `civicrm_email`(`id`)
1053 ON DELETE SET NULL
1054 ON UPDATE RESTRICT;
1055 ");
1056
1057 CRM_Core_DAO::executeQuery("
1058 ALTER TABLE `civicrm_mailing_recipients`
1059 ADD CONSTRAINT `FK_civicrm_mailing_recipients_phone_id`
1060 FOREIGN KEY (`phone_id`)
1061 REFERENCES `civicrm_phone`(`id`)
1062 ON DELETE SET NULL
1063 ON UPDATE RESTRICT;
1064 ");
1065
1066 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
1067
1068 return TRUE;
1069 }
1070
1071 /**
1072 * CRM-17663 - Dashboard schema changes
1073 *
1074 * @param \CRM_Queue_TaskContext $ctx
1075 *
1076 * @return bool
1077 */
1078 public static function dashboardSchemaUpdate(CRM_Queue_TaskContext $ctx) {
1079 if (!CRM_Core_BAO_SchemaHandler::checkIfIndexExists('civicrm_dashboard_contact', 'index_dashboard_id_contact_id')) {
1080 // Delete any stray duplicate rows and add unique index to prevent new dupes and enable INSERT/UPDATE combo query
1081 CRM_Core_DAO::executeQuery('DELETE c1 FROM civicrm_dashboard_contact c1, civicrm_dashboard_contact c2 WHERE c1.contact_id = c2.contact_id AND c1.dashboard_id = c2.dashboard_id AND c1.id > c2.id');
1082 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_dashboard_contact ADD UNIQUE INDEX index_dashboard_id_contact_id (dashboard_id, contact_id);');
1083 }
1084 $domain = new CRM_Core_DAO_Domain();
1085 $domain->find(TRUE);
1086 CRM_Core_BAO_SchemaHandler::dropColumn('civicrm_dashboard_contact', 'content', FALSE, TRUE);
1087 CRM_Core_BAO_SchemaHandler::dropColumn('civicrm_dashboard_contact', 'is_minimized', FALSE, TRUE);
1088 CRM_Core_BAO_SchemaHandler::dropColumn('civicrm_dashboard_contact', 'is_fullscreen', FALSE, TRUE);
1089 CRM_Core_BAO_SchemaHandler::dropColumn('civicrm_dashboard_contact', 'created_date', FALSE, TRUE);
1090 CRM_Core_BAO_SchemaHandler::dropColumn('civicrm_dashboard', 'is_fullscreen', FALSE, TRUE);
1091 CRM_Core_BAO_SchemaHandler::dropColumn('civicrm_dashboard', 'is_minimized', FALSE, TRUE);
1092 CRM_Core_BAO_SchemaHandler::dropColumn('civicrm_dashboard', 'column_no', FALSE, TRUE);
1093 CRM_Core_BAO_SchemaHandler::dropColumn('civicrm_dashboard', 'weight', FALSE, TRUE);
1094
1095 CRM_Core_DAO::executeQuery('UPDATE civicrm_dashboard SET url = REPLACE(url, "&snippet=5", ""), fullscreen_url = REPLACE(fullscreen_url, "&snippet=5", "")');
1096
1097 if (!CRM_Core_BAO_SchemaHandler::checkIfFieldExists('civicrm_dashboard', 'cache_minutes')) {
1098 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_dashboard ADD COLUMN cache_minutes int unsigned NOT NULL DEFAULT 60 COMMENT "Number of minutes to cache dashlet content in browser localStorage."',
1099 [], TRUE, NULL, FALSE, FALSE);
1100 }
1101 if ($domain->locales) {
1102 $locales = explode(CRM_Core_DAO::VALUE_SEPARATOR, $domain->locales);
1103 CRM_Core_I18n_Schema::rebuildMultilingualSchema($locales, NULL, TRUE);
1104 }
1105
1106 CRM_Core_DAO::executeQuery('UPDATE civicrm_dashboard SET cache_minutes = 1440 WHERE name = "blog"');
1107 CRM_Core_DAO::executeQuery('UPDATE civicrm_dashboard SET cache_minutes = 7200 WHERE name IN ("activity","getting-started")');
1108 return TRUE;
1109 }
1110
1111 /**
1112 * CRM-19100 - Alter Index and Type for Image URL
1113 * @return bool
1114 */
1115 public static function alterIndexAndTypeForImageURL() {
1116 $length = [];
1117 CRM_Core_BAO_SchemaHandler::dropIndexIfExists('civicrm_contact', 'index_image_url');
1118 CRM_Core_DAO::executeQuery("ALTER TABLE `civicrm_contact` CHANGE `image_URL` `image_URL` TEXT CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL COMMENT 'optional URL for preferred image (photo, logo, etc.) to display for this contact.'");
1119
1120 $length['civicrm_contact']['image_URL'] = 128;
1121 CRM_Core_BAO_SchemaHandler::createIndexes(['civicrm_contact' => ['image_URL']], 'index', $length);
1122
1123 return TRUE;
1124 }
1125
1126 /**
1127 * Add mailing template type.
1128 *
1129 * @return bool
1130 */
1131 public static function addMailingTemplateType() {
1132 if (!CRM_Core_BAO_SchemaHandler::checkIfFieldExists('civicrm_mailing', 'template_type', FALSE)) {
1133 CRM_Core_DAO::executeQuery('
1134 ALTER TABLE civicrm_mailing
1135 ADD COLUMN `template_type` varchar(64) NOT NULL DEFAULT \'traditional\' COMMENT \'The language/processing system used for email templates.\',
1136 ADD COLUMN `template_options` longtext COMMENT \'Advanced options used by the email templating system. (JSON encoded)\'
1137 ');
1138 }
1139 return TRUE;
1140 }
1141
1142 /**
1143 * CRM-18651 Add DataType column to Option Group Table
1144 * @return bool
1145 */
1146 public static function addDataTypeColumnToOptionGroupTable() {
1147 if (!CRM_Core_BAO_SchemaHandler::checkIfFieldExists('civicrm_option_group', 'data_type')) {
1148 CRM_Core_DAO::executeQuery("ALTER TABLE `civicrm_option_group` ADD COLUMN `data_type` varchar(128) COLLATE utf8_unicode_ci DEFAULT NULL comment 'Data Type of Option Group.'",
1149 [], TRUE, NULL, FALSE, FALSE);
1150 }
1151 $domain = new CRM_Core_DAO_Domain();
1152 $domain->find(TRUE);
1153 if ($domain->locales) {
1154 $locales = explode(CRM_Core_DAO::VALUE_SEPARATOR, $domain->locales);
1155 CRM_Core_I18n_Schema::rebuildMultilingualSchema($locales, NULL, TRUE);
1156 }
1157
1158 CRM_Core_DAO::executeQuery("UPDATE `civicrm_option_group` SET `data_type` = 'Integer'
1159 WHERE name IN ('activity_type', 'gender', 'payment_instrument', 'participant_role', 'event_type')");
1160 return TRUE;
1161 }
1162
1163 /**
1164 * CRM-19372 Add field to store accepted credit credit cards for a payment processor.
1165 * @return bool
1166 */
1167 public static function addWysiwygPresets() {
1168 CRM_Core_BAO_OptionGroup::ensureOptionGroupExists([
1169 'name' => 'wysiwyg_presets',
1170 'title' => ts('WYSIWYG Editor Presets'),
1171 'is_reserved' => 1,
1172 ]);
1173 $values = [
1174 'default' => ['label' => ts('Default'), 'is_default' => 1],
1175 'civimail' => ['label' => ts('CiviMail'), 'component_id' => 'CiviMail'],
1176 'civievent' => ['label' => ts('CiviEvent'), 'component_id' => 'CiviEvent'],
1177 ];
1178 foreach ($values as $name => $value) {
1179 CRM_Core_BAO_OptionValue::ensureOptionValueExists($value + [
1180 'name' => $name,
1181 'option_group_id' => 'wysiwyg_presets',
1182 ]);
1183 }
1184 $fileName = Civi::paths()->getPath('[civicrm.files]/persist/crm-ckeditor-config.js');
1185 // Ensure the config file contains the allowedContent setting
1186 if (file_exists($fileName)) {
1187 $config = file_get_contents($fileName);
1188 $pos = strrpos($config, '};');
1189 $setting = "\n\tconfig.allowedContent = true;\n";
1190 $config = substr_replace($config, $setting, $pos, 0);
1191 unlink($fileName);
1192 $newFileName = Civi::paths()->getPath('[civicrm.files]/persist/crm-ckeditor-default.js');
1193 file_put_contents($newFileName, $config);
1194 }
1195 return TRUE;
1196 }
1197
1198 /**
1199 * Update Kenyan Provinces to reflect changes per CRM-20062
1200 *
1201 * @param \CRM_Queue_TaskContext $ctx
1202 */
1203 public static function updateKenyanProvinces(CRM_Queue_TaskContext $ctx) {
1204 $kenyaCountryID = CRM_Core_DAO::singleValueQuery('SELECT max(id) from civicrm_country where iso_code = "KE"');
1205 $oldProvinces = [
1206 'Nairobi Municipality',
1207 'Coast',
1208 'North-Eastern Kaskazini Mashariki',
1209 'Rift Valley',
1210 'Western Magharibi',
1211 ];
1212 self::deprecateStateProvinces($kenyaCountryID, $oldProvinces);
1213 return TRUE;
1214 }
1215
1216 /**
1217 * Deprecate provinces that no longer exist.
1218 *
1219 * @param int $countryID
1220 * @param array $provinces
1221 */
1222 public static function deprecateStateProvinces($countryID, $provinces) {
1223 foreach ($provinces as $province) {
1224 $existingStateID = CRM_Core_DAO::singleValueQuery("
1225 SELECT id FROM civicrm_state_province
1226 WHERE country_id = %1
1227 AND name = %2
1228 ",
1229 [1 => [$countryID, 'Int'], 2 => [$province, 'String']]);
1230
1231 if (!$existingStateID) {
1232 continue;
1233 }
1234 if (!CRM_Core_DAO::singleValueQuery("
1235 SELECT count(*) FROM civicrm_address
1236 WHERE state_province_id = %1
1237 ", [1 => [$existingStateID, 'Int']])
1238 ) {
1239 CRM_Core_DAO::executeQuery("DELETE FROM civicrm_state_province WHERE id = %1", [1 => [$existingStateID, 'Int']]);
1240 }
1241 else {
1242 $params = ['1' => [ts("Former - $province"), 'String']];
1243 CRM_Core_DAO::executeQuery("
1244 UPDATE civicrm_state_province SET name = %1 WHERE id = $existingStateID
1245 ", $params);
1246 }
1247 }
1248 }
1249
1250 /**
1251 * CRM-19961
1252 * Poputate newly added domain id column and add foriegn key onto table.
1253 */
1254 public static function populateSMSProviderDomainId() {
1255 $count = CRM_Core_DAO::singleValueQuery("SELECT count(id) FROM civicrm_domain");
1256 if ($count == 1) {
1257 CRM_Core_DAO::executeQuery("UPDATE civicrm_sms_provider SET domain_id = (SELECT id FROM civicrm_domain)");
1258 }
1259 if (!parent::checkFKExists('civicrm_sms_provider', 'FK_civicrm_sms_provider_domain_id')) {
1260 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
1261 CRM_Core_DAO::executeQuery("ALTER TABLE `civicrm_sms_provider`
1262 ADD CONSTRAINT FK_civicrm_sms_provider_domain_id
1263 FOREIGN KEY (`domain_id`) REFERENCES `civicrm_domain`(`id`)
1264 ON DELETE SET NULL");
1265
1266 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
1267 }
1268 return TRUE;
1269 }
1270
1271 /**
1272 * CRM-16633 - Add activity type for Change Case Status
1273 *
1274 * @param \CRM_Queue_TaskContext $ctx
1275 *
1276 * @return bool
1277 */
1278 public static function addChangeCaseSubjectActivityType(CRM_Queue_TaskContext $ctx) {
1279 CRM_Core_BAO_OptionValue::ensureOptionValueExists([
1280 'option_group_id' => 'activity_type',
1281 'name' => 'Change Case Subject',
1282 'label' => ts('Change Case Subject'),
1283 'is_active' => TRUE,
1284 'component_id' => 'CiviCase',
1285 'icon' => 'fa-pencil-square-o',
1286 ]);
1287 return TRUE;
1288 }
1289
1290 /**
1291 * CRM-19986 fix schema differnces in civicrm_action_schedule
1292 */
1293 public static function fixSchemaOnCiviCRMActionSchedule() {
1294 if (!parent::checkFKExists('civicrm_action_schedule', 'FK_civicrm_action_schedule_sms_template_id')) {
1295 CRM_Core_DAO::executeQuery("ALTER TABLE `civicrm_action_schedule`
1296 ADD CONSTRAINT FK_civicrm_action_schedule_sms_template_id
1297 FOREIGN KEY (`sms_template_id`) REFERENCES `civicrm_msg_template`(`id`)
1298 ON DELETE SET NULL");
1299 }
1300 CRM_Core_DAO::executeQuery("ALTER TABLE `civicrm_action_schedule`
1301 CHANGE `mapping_id` `mapping_id` varchar(64) COLLATE
1302 utf8_unicode_ci DEFAULT NULL COMMENT 'Name/ID of the mapping to use on this table'");
1303 return TRUE;
1304 }
1305
1306 public static function pickActivityRevisionPolicy(CRM_Queue_TaskContext $ctx) {
1307 // CRM-21052 - If site is using activity revisions, continue doing so. Otherwise, switch out.
1308 $count = CRM_Core_DAO::singleValueQuery('SELECT count(*) FROM civicrm_activity WHERE is_current_revision = 0 OR original_id IS NOT NULL');
1309 Civi::settings()->set('civicaseActivityRevisions', $count > 0);
1310 return TRUE;
1311 }
1312
1313 /**
1314 * Add in missing Tajikistan Subdivisions
1315 *
1316 * @param \CRM_Queue_TaskContext $ctx
1317 *
1318 * @return bool
1319 */
1320 public static function tajikistanMissingSubdivisions(CRM_Queue_TaskContext $ctx) {
1321 $sql = 'INSERT INTO civicrm_state_province (id, country_id, abbreviation, name) VALUES';
1322 $updates = [];
1323 if (!CRM_Core_DAO::singleValueQuery("Select id FROM civicrm_state_province WHERE country_id = 1209 AND name = 'Dushanbe'")) {
1324 $updates[] = '(NULL, 1209, "DU", "Dushanbe")';
1325 }
1326 if (!CRM_Core_DAO::singleValueQuery("Select id FROM civicrm_state_province WHERE country_id = 1209 AND name = 'Nohiyahoi Tobei JumhurĂ­'")) {
1327 $updates[] = '(NULL, 1209, "RA", "Nohiyahoi Tobei JumhurĂ­")';
1328 }
1329 if (!empty($updates)) {
1330 CRM_Core_DAO::executeQuery($sql . implode(', ', $updates));
1331 }
1332 return TRUE;
1333 }
1334
1335 /**
1336 * Remove the contribution logging reports which have been broken for a very long time.
1337 *
1338 * @param \CRM_Queue_TaskContext $ctx
1339 *
1340 * @return bool
1341 */
1342 public static function removeContributionLoggingReports(CRM_Queue_TaskContext $ctx) {
1343 if (class_exists('CRM_Report_Form_Contribute_LoggingDetail') || class_exists('CRM_Report_Form_Contribute_LoggingSummary')) {
1344 // Perhaps the site has overridden these classes. The core ones are broken but they
1345 // may have functional ones.
1346 return TRUE;
1347 }
1348 $options = civicrm_api3('OptionValue', 'get', ['option_group_id' => 'report_template', 'options' => ['limit' => 0]]);
1349 foreach ($options['values'] as $option) {
1350 if ($option['name'] === 'CRM_Report_Form_Contribute_LoggingDetail' || $option['name'] === 'CRM_Report_Form_Contribute_LoggingSummary') {
1351 $instances = civicrm_api3('ReportInstance', 'get', ['report_id' => $option['value']]);
1352 if ($instances['count']) {
1353 foreach ($instances['values'] as $instance) {
1354 if ($instance['navigation_id']) {
1355 civicrm_api3('Navigation', 'delete', ['id' => $instance['navigation_id']]);
1356 }
1357 civicrm_api3('ReportInstance', 'delete', ['id' => $instance['id']]);
1358 }
1359 }
1360 civicrm_api3('OptionValue', 'delete', ['id' => $option['id']]);
1361 }
1362 }
1363 return TRUE;
1364 }
1365
1366 /**
1367 * @return bool
1368 */
1369 protected function checkImageUploadDir() {
1370 $config = CRM_Core_Config::singleton();
1371 $check = new CRM_Utils_Check_Component_Security();
1372 return $config->imageUploadDir && $config->imageUploadURL && $check->isDirAccessible($config->imageUploadDir, $config->imageUploadURL);
1373 }
1374
1375 /**
1376 * CRM-20572 - Format date fields in Contrib Sybunt custom search's saved criteria.
1377 *
1378 * @param \CRM_Queue_TaskContext $ctx
1379 *
1380 * @return bool
1381 */
1382 public static function fixDateFieldsInSmartGroups(CRM_Queue_TaskContext $ctx) {
1383 $dao = CRM_Core_DAO::executeQuery("SELECT id, form_values FROM civicrm_saved_search WHERE form_values LIKE '%CRM_Contact_Form_Search_Custom_ContribSYBNT%'");
1384 while ($dao->fetch()) {
1385 $formValues = unserialize($dao->form_values);
1386 CRM_Contact_Form_Search_Custom_ContribSYBNT::formatSavedSearchFields($formValues);
1387 CRM_Core_DAO::executeQuery("UPDATE civicrm_saved_search SET form_values = %1 WHERE id = {$dao->id}", [1 => [serialize($formValues), 'String']]);
1388 }
1389 return TRUE;
1390 }
1391
1392 /**
1393 * CRM-20892 Convert default of created_date in civicrm_mailing table to NULL
1394 * @return bool
1395 */
1396 public static function civiMailingCreatedDateNull(CRM_Queue_TaskContext $ctx) {
1397 $dataType = 'timestamp';
1398 if (CRM_Utils_Check_Component_Timestamps::isFieldType('civicrm_mailing', 'created_date', 'datetime')) {
1399 $dataType = 'datetime';
1400 }
1401 CRM_Core_DAO::executeQuery("ALTER TABLE civicrm_mailing CHANGE created_date created_date {$dataType} NULL DEFAULT NULL COMMENT 'Date and time this mailing was created.'");
1402 return TRUE;
1403 }
1404
1405 }