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