Merge pull request #9353 from adixon/CRM-19601
[civicrm-core.git] / CRM / Upgrade / Incremental / php / FourSeven.php
CommitLineData
6cc25669
CW
1<?php
2/*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
fa938177 6 | Copyright CiviCRM LLC (c) 2004-2016 |
6cc25669
CW
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/**
bf6a5362 28 * Upgrade logic for 4.7
6cc25669 29 */
bf6a5362 30class CRM_Upgrade_Incremental_php_FourSeven extends CRM_Upgrade_Incremental_Base {
6cc25669 31
f431d51f
J
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 *
3bdf1f3a 38 * @param string $preUpgradeMessage
f431d51f
J
39 * @param string $rev
40 * a version number, e.g. '4.4.alpha1', '4.4.beta3', '4.4.0'.
41 * @param null $currentVer
f431d51f
J
42 */
43 public function setPreUpgradeMessage(&$preUpgradeMessage, $rev, $currentVer = NULL) {
44 if ($rev == '4.7.alpha1') {
f431d51f
J
45 // CRM-16478 Remove custom fatal error template path option
46 $config = CRM_Core_Config::singleton();
18b3bef6 47 if (!empty($config->fatalErrorTemplate) && $config->fatalErrorTemplate != 'CRM/common/fatal.tpl') {
f431d51f
J
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.', array(1 => $config->fatalErrorTemplate)) . '</p>';
49 }
f431d51f 50 }
a40fd1ac
CW
51 if ($rev == '4.7.alpha4') {
52 // CRM-17004 Warn of Moneris removal
87a33a95
CW
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')) {
a40fd1ac
CW
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.', array(1 => 'Moneris')) . '</p>';
60 }
61 }
f431d51f
J
62 }
63
6cc25669
CW
64 /**
65 * Compute any messages which should be displayed after upgrade.
66 *
67 * @param string $postUpgradeMessage
68 * alterable.
69 * @param string $rev
70 * an intermediate version; note that setPostUpgradeMessage is called repeatedly with different $revs.
6cc25669
CW
71 */
72 public function setPostUpgradeMessage(&$postUpgradeMessage, $rev) {
6dbe2c23
CW
73 if ($rev == '4.7.alpha1') {
74 $config = CRM_Core_Config::singleton();
bf6a5362 75 // FIXME: Performing an upgrade step during postUpgrade message phase is probably bad
6dbe2c23
CW
76 $editor_id = self::updateWysiwyg();
77 $msg = NULL;
78 $ext_href = 'href="' . CRM_Utils_System::url('civicrm/admin/extensions', 'reset=1') . '"';
79 $dsp_href = 'href="' . CRM_Utils_System::url('civicrm/admin/setting/preferences/display', 'reset=1') . '"';
80 $blog_href = 'href="https://civicrm.org/blogs/colemanw/big-changes-wysiwyg-editing-47"';
81 switch ($editor_id) {
82 // TinyMCE
83 case 1:
84 $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.', array(1 => $ext_href));
85 break;
86
87 // Drupal/Joomla editor
88 case 3:
89 case 4:
90 $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>', array(1 => $config->userFramework, 2 => $blog_href));
91 break;
92 }
93 if ($msg) {
94 $postUpgradeMessage .= '<p>' . $msg . '</p>';
95 }
96 $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>', array(1 => $dsp_href, 2 => $blog_href)) . '</p>';
dd55005c 97
98 $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).');
f431d51f
J
99
100 $postUpgradeMessage .= '<p>' . ts('The custom fatal error template setting has been removed.') . '</p>';
6dbe2c23 101 }
a742ee50
TO
102 //if ($rev == '4.7.11') {
103 // $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'");
104 //}
11769bd1 105 if ($rev == '4.7.11') {
9867e465 106 $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'.");
11769bd1 107 }
6cc25669
CW
108 }
109
6cc25669
CW
110 /**
111 * Upgrade function.
112 *
113 * @param string $rev
114 */
115 public function upgrade_4_7_alpha1($rev) {
b604d7ec 116 $this->addTask('Migrate \'on behalf of\' information to module_data', 'migrateOnBehalfOfInfo');
bf6a5362 117 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
f806379b 118 $this->addTask(ts('Migrate Settings to %1', array(1 => $rev)), 'migrateSettings', $rev);
b604d7ec 119 $this->addTask('Add Getting Started dashlet', 'addGettingStartedDashlet', $rev);
a40fd1ac
CW
120 }
121
122 /**
123 * Upgrade function.
124 *
125 * @param string $rev
126 */
127 public function upgrade_4_7_alpha4($rev) {
128 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
058b8a5e 129 $this->addTask(ts('Remove %1', array(1 => 'Moneris')), 'removePaymentProcessorType', 'Moneris');
b2222b9f 130 $this->addTask('Update Smart Groups', 'fixContactTypeInSmartGroups');
6cc25669
CW
131 }
132
0094ac08
CW
133 /**
134 * Upgrade function.
135 *
136 * @param string $rev
137 */
138 public function upgrade_4_7_beta2($rev) {
139 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
140 $this->addTask('Delete unused file', 'deleteVersionCheckCacheFile');
141 }
142
fb1f3850
DRJ
143 /**
144 * Upgrade function.
145 *
146 * @param string $rev
147 */
902e557f 148 public function upgrade_4_7_beta6($rev) {
13599400 149 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
fb1f3850 150 $this->addTask('Disable flexible jobs extension', 'disableFlexibleJobsExtension');
20d5377e 151 $this->addTask('Add Index to financial_trxn trxn_id field', 'addIndexFinancialTrxnTrxnID');
fb1f3850
DRJ
152 }
153
8ca47f5c 154 /**
155 * Upgrade function.
156 *
157 * @param string $rev
158 */
159 public function upgrade_4_7_1($rev) {
2af0b023 160 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
8ca47f5c 161 $this->addTask('Add Index to civicrm_contribution creditnote_id field', 'addIndexContributionCreditNoteID');
162 }
163
2179c899 164 /**
165 * Upgrade function.
166 *
167 * @param string $rev
168 */
169 public function upgrade_4_7_2($rev) {
2af0b023 170 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
2179c899 171 $this->addTask('Fix Index on civicrm_financial_item combined entity_id + entity_table', 'addCombinedIndexFinancialItemEntityIDEntityType');
1f395432 172 $this->addTask('enable financial account relationships for chargeback & refund', 'addRefundAndChargeBackAccountsIfNotExist');
3fe26f4c 173 $this->addTask('Add Index to civicrm_contribution.source', 'addIndexContributionSource');
2179c899 174 }
175
fd28b6a0 176 /**
177 * Upgrade function.
178 *
179 * @param string $rev
180 */
181 public function upgrade_4_7_3($rev) {
2af0b023 182 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
fd28b6a0 183 $this->addTask('Add Index to civicrm_contribution.total_amount', 'addIndexContributionAmount');
184 }
185
6eb752fa 186 /**
187 * Upgrade function.
188 *
189 * @param string $rev
190 */
191 public function upgrade_4_7_4($rev) {
2af0b023 192 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
6eb752fa 193 $this->addTask('Add Contact Deleted by Merge Activity Type', 'addDeletedByMergeActivityType');
194 }
195
2cbdd085
J
196 /**
197 * Upgrade function.
198 *
199 * @param string $rev
200 */
6a2d3987 201 public function upgrade_4_7_7($rev) {
2cbdd085 202 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
6a2d3987
J
203 // https://issues.civicrm.org/jira/browse/CRM-18006
204 if (CRM_Core_DAO::checkTableExists('civicrm_install_canary')) {
205 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_install_canary ENGINE=InnoDB');
206 }
2cbdd085
J
207 }
208
2af0b023
CW
209 /**
210 * Upgrade function.
211 *
212 * @param string $rev
213 */
6a2d3987 214 public function upgrade_4_7_8($rev) {
2af0b023 215 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
6a2d3987 216 $this->addTask('Upgrade mailing foreign key constraints', 'upgradeMailingFKs');
065ffec9
TO
217 }
218
da1ecd73
SL
219 /**
220 * Upgrade function.
221 *
222 * @param string $rev
223 */
e8a4535e 224 public function upgrade_4_7_10($rev) {
da1ecd73 225 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
e8a4535e 226 $this->addTask(ts('Upgrade Add Help Pre and Post Fields to price value table'), 'addHelpPreAndHelpPostFieldsPriceFieldValue');
8e2e96a5 227 $this->addTask(ts('Alter index and type for image URL'), 'alterIndexAndTypeForImageURL');
da1ecd73
SL
228 }
229
00c27b41
CW
230 /**
231 * Upgrade function.
232 *
233 * @param string $rev
234 */
235 public function upgrade_4_7_11($rev) {
236 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
237 $this->addTask('Dashboard schema updates', 'dashboardSchemaUpdate');
9e42a501 238 $this->addTask(ts('Fill in setting "remote_profile_submissions"'), 'migrateRemoteSubmissionsSetting');
00c27b41
CW
239 }
240
7c61320c
SL
241 /**
242 * Upgrade function.
243 *
244 * @param string $rev
245 */
246 public function upgrade_4_7_12($rev) {
247 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
248 $this->addTask(ts('Add Data Type column to civicrm_option_group'), 'addDataTypeColumnToOptionGroupTable');
249 }
cb5962bd
SL
250 /**
251 * Upgrade function.
252 *
253 * @param string $rev
254 */
255 public function upgrade_4_7_13($rev) {
256 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
6ba2d3a0 257 $this->addTask(ts('Add column to allow for payment processors to set what card types are accepted'), 'addAcceptedCardTypesField');
cb5962bd
SL
258 }
259
7c61320c 260
2af0b023 261 /*
2cbdbcef 262 * Important! All upgrade functions MUST add a 'runSql' task.
2af0b023
CW
263 * Uncomment and use the following template for a new upgrade version
264 * (change the x in the function name):
265 */
266
267 // /**
268 // * Upgrade function.
269 // *
270 // * @param string $rev
271 // */
272 // public function upgrade_4_7_x($rev) {
273 // $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
274 // // Additional tasks here...
275 // }
276
6cc25669
CW
277 /**
278 * CRM-16354
279 *
6dbe2c23 280 * @return int
6cc25669 281 */
6dbe2c23 282 public static function updateWysiwyg() {
aaffa79f 283 $editorID = Civi::settings()->get('editor_id');
6dbe2c23
CW
284 // Previously a numeric value indicated one of 4 wysiwyg editors shipped in core, and no value indicated 'Textarea'
285 // Now the options are "Textarea", "CKEditor", and the rest have been dropped from core.
286 $newEditor = $editorID ? "CKEditor" : "Textarea";
08ef4ddd 287 Civi::settings()->set('editor_id', $newEditor);
6cc25669 288
6dbe2c23 289 return $editorID;
6cc25669
CW
290 }
291
f806379b
TO
292 /**
293 * Migrate any last remaining options from `civicrm_domain.config_backend` to `civicrm_setting`.
294 * Cleanup setting schema.
295 *
296 * @param CRM_Queue_TaskContext $ctx
297 * @return bool
298 */
5c9edd99 299 public static function migrateSettings(CRM_Queue_TaskContext $ctx) {
4cc9e637
TO
300 // Tip: If there are problems with adding the new uniqueness index, try inspecting:
301 // SELECT name, domain_id, contact_id, count(*) AS dupes FROM civicrm_setting cs GROUP BY name, domain_id, contact_id HAVING dupes > 1;
302
303 // Nav records are expendable. https://forum.civicrm.org/index.php?topic=36933.0
304 CRM_Core_DAO::executeQuery('DELETE FROM civicrm_setting WHERE contact_id IS NOT NULL AND name = "navigation"');
3ddd2901 305
726e6261
SL
306 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_setting DROP INDEX index_group_name');
307 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_setting DROP COLUMN group_name');
308
3ddd2901
SL
309 // Handle Strange activity_tab_filter settings.
310 CRM_Core_DAO::executeQuery('CREATE TABLE civicrm_activity_setting LIKE civicrm_setting');
726e6261 311 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_activity_setting ADD UNIQUE INDEX index_domain_contact_name (domain_id, contact_id, name)');
3ddd2901 312 CRM_Core_DAO::executeQuery('INSERT INTO civicrm_activity_setting (name, contact_id, domain_id, value)
726e6261 313 SELECT DISTINCT name, contact_id, domain_id, value
3ddd2901
SL
314 FROM civicrm_setting
315 WHERE name = "activity_tab_filter"
316 AND value is not NULL');
ee4d8422 317 CRM_Core_DAO::executeQuery('DELETE FROM civicrm_setting WHERE name = "activity_tab_filter"');
4cc9e637 318
e6a2c901 319 $date = CRM_Utils_Time::getTime('Y-m-d H:i:s');
f806379b 320 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_setting ADD UNIQUE INDEX index_domain_contact_name (domain_id, contact_id, name)');
e6a2c901
SL
321 CRM_Core_DAO::executeQuery("INSERT INTO civicrm_setting (name, contact_id, domain_id, value, is_domain, created_id, created_date)
322 SELECT name, contact_id, domain_id, value, 0, contact_id,'$date'
3ddd2901 323 FROM civicrm_activity_setting
e6a2c901
SL
324 WHERE name = 'activity_tab_filter'
325 AND value is not NULL"
d09d52ce 326 );
3ddd2901 327 CRM_Core_DAO::executeQuery('DROP TABLE civicrm_activity_setting');
f806379b
TO
328
329 $domainDao = CRM_Core_DAO::executeQuery('SELECT id, config_backend FROM civicrm_domain');
330 while ($domainDao->fetch()) {
331 $settings = CRM_Upgrade_Incremental_php_FourSeven::convertBackendToSettings($domainDao->id, $domainDao->config_backend);
332 CRM_Core_Error::debug_var('convertBackendToSettings', array(
333 'domainId' => $domainDao->id,
334 'backend' => $domainDao->config_backend,
335 'settings' => $settings,
336 ));
337
338 foreach ($settings as $name => $value) {
339 $rowParams = array(
340 1 => array($domainDao->id, 'Positive'),
341 2 => array($name, 'String'),
342 3 => array(serialize($value), 'String'),
343 );
344 $settingId = CRM_Core_DAO::singleValueQuery(
345 'SELECT id FROM civicrm_setting WHERE domain_id = %1 AND name = %2',
346 $rowParams);
347 if (!$settingId) {
348 CRM_Core_DAO::executeQuery(
349 'INSERT INTO civicrm_setting (domain_id, name, value, is_domain) VALUES (%1,%2,%3,1)',
350 $rowParams);
351 }
352 }
353 }
354
9e726168 355 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_domain DROP COLUMN config_backend');
f806379b
TO
356
357 return TRUE;
358 }
359
360 /**
361 * Take a config_backend blob and produce an equivalent list of settings.
362 *
363 * @param int $domainId
364 * Domain ID.
365 * @param string $config_backend
366 * Serialized blob.
367 * @return array
368 */
369 public static function convertBackendToSettings($domainId, $config_backend) {
370 if (!$config_backend) {
371 return array();
372 }
373
374 $backend = unserialize($config_backend);
375 if (!$backend) {
376 return array();
377 }
378
379 $mappings = \CRM_Core_Config_MagicMerge::getPropertyMap();
380 $settings = array();
381 foreach ($backend as $propertyName => $propertyValue) {
382 if (isset($mappings[$propertyName][0]) && preg_match('/^setting/', $mappings[$propertyName][0])) {
383 // $mapping format: $propertyName => Array(0 => $type, 1 => $setting|NULL).
384 $settingName = isset($mappings[$propertyName][1]) ? $mappings[$propertyName][1] : $propertyName;
385 $settings[$settingName] = $propertyValue;
386 }
387 }
388
389 return $settings;
390 }
391
0a95c936 392 /**
393 * Add Getting Started dashlet to dashboard
394 *
395 * @param \CRM_Queue_TaskContext $ctx
396 *
397 * @return bool
398 */
5c9edd99 399 public static function addGettingStartedDashlet(CRM_Queue_TaskContext $ctx) {
9c4a04f2 400 $sql = "SELECT count(*) FROM civicrm_dashboard WHERE name='getting-started'";
e1674273 401 $res = CRM_Core_DAO::singleValueQuery($sql);
402 $domainId = CRM_Core_Config::domainID();
403 if ($res <= 0) {
404 $sql = "INSERT INTO `civicrm_dashboard`
a8b704c5 405 ( `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)";
e1674273 406 CRM_Core_DAO::executeQuery($sql);
407 // Add default position for Getting Started Dashlet ( left column)
408 $sql = "INSERT INTO `civicrm_dashboard_contact` (dashboard_id, contact_id, column_no, is_active)
409SELECT (SELECT MAX(id) FROM `civicrm_dashboard`), contact_id, 0, IF (SUM(is_active) > 0, 1, 0)
429da6a1 410FROM `civicrm_dashboard_contact` JOIN `civicrm_contact` WHERE civicrm_dashboard_contact.contact_id = civicrm_contact.id GROUP BY contact_id";
e1674273 411 CRM_Core_DAO::executeQuery($sql);
412 }
0a95c936 413 return TRUE;
e1674273 414 }
4175ee03 415
6b1e1a2c 416 /**
417 * Migrate on-behalf information to uf_join.module_data as on-behalf columns will be dropped
418 * on DB upgrade
419 *
420 * @param CRM_Queue_TaskContext $ctx
421 *
422 * @return bool
423 * TRUE for success
424 */
425 public static function migrateOnBehalfOfInfo(CRM_Queue_TaskContext $ctx) {
d3e92c88 426 $domain = new CRM_Core_DAO_Domain();
427 $domain->find(TRUE);
6b1e1a2c 428
d3e92c88 429 // fetch onBehalf entry in UFJoin table
6b1e1a2c 430 $ufGroupDAO = new CRM_Core_DAO_UFJoin();
431 $ufGroupDAO->module = 'OnBehalf';
432 $ufGroupDAO->find(TRUE);
433
f635ab77 434 $forOrgColums = array('is_for_organization');
d3e92c88 435 if ($domain->locales) {
436 $locales = explode(CRM_Core_DAO::VALUE_SEPARATOR, $domain->locales);
437 foreach ($locales as $locale) {
438 $forOrgColums[] = "for_organization_{$locale}";
439 }
440 }
441 else {
442 $forOrgColums[] = "for_organization";
443 }
444
445 $query = "
446 SELECT " . implode(", ", $forOrgColums) . ", uj.id as join_id, uj.uf_group_id as uf_group_id
447 FROM civicrm_contribution_page cp
448 INNER JOIN civicrm_uf_join uj ON uj.entity_id = cp.id AND uj.module = 'OnBehalf'";
449 $dao = CRM_Core_DAO::executeQuery($query, array(), TRUE, NULL, FALSE, FALSE);
6b1e1a2c 450
451 if ($dao->N) {
6b1e1a2c 452 while ($dao->fetch()) {
453 $onBehalfParams['on_behalf'] = array('is_for_organization' => $dao->is_for_organization);
454 if ($domain->locales) {
6b1e1a2c 455 foreach ($locales as $locale) {
456 $for_organization = "for_organization_{$locale}";
457 $onBehalfParams['on_behalf'] += array(
458 $locale => array(
459 'for_organization' => $dao->$for_organization,
460 ),
461 );
462 }
463 }
464 else {
465 $onBehalfParams['on_behalf'] += array(
466 'default' => array(
467 'for_organization' => $dao->for_organization,
468 ),
469 );
470 }
471 $ufJoinParam = array(
472 'id' => $dao->join_id,
473 'module' => 'on_behalf',
d3e92c88 474 'uf_group_id' => $dao->uf_group_id,
6b1e1a2c 475 'module_data' => json_encode($onBehalfParams),
476 );
477 CRM_Core_BAO_UFJoin::create($ufJoinParam);
478 }
479 }
480
481 return TRUE;
9e42a501
TO
482 }
483
484 /**
485 * v4.7.11 adds a new setting "remote_profile_submissions". This is
486 * long-standing feature that existing sites may be using; however, it's
487 * a bit prone to abuse. For new sites, the default is to disable it
488 * (since that is more secure). For existing sites, the default is to
489 * enable it (since that is more compatible).
490 *
491 * @param \CRM_Queue_TaskContext $ctx
492 *
493 * @return bool
494 */
5c9edd99 495 public static function migrateRemoteSubmissionsSetting(CRM_Queue_TaskContext $ctx) {
9e42a501
TO
496 $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");
497 while ($domains->fetch()) {
498 CRM_Core_DAO::executeQuery(
499 "INSERT INTO civicrm_setting (`name`, `value`, `domain_id`, `is_domain`, `contact_id`, `component_id`, `created_date`, `created_id`)
500 VALUES (%2, %3, %4, %5, NULL, NULL, %6, NULL)",
501 array(
502 2 => array('remote_profile_submissions', 'String'),
503 3 => array('s:1:"1";', 'String'),
504 4 => array($domains->id, 'Integer'),
505 5 => array(1, 'Integer'),
506 6 => array(date('Y-m-d H:i:s'), 'String'),
507 )
508 );
509 }
510 return TRUE;
6b1e1a2c 511 }
cb804cd9 512
b2222b9f
CW
513 /**
514 * CRM-11782 - Get rid of VALUE_SEPARATOR character in saved search form values
515 *
516 * @param \CRM_Queue_TaskContext $ctx
517 *
518 * @return bool
519 */
5c9edd99 520 public static function fixContactTypeInSmartGroups(CRM_Queue_TaskContext $ctx) {
b2222b9f
CW
521 $sep = CRM_Core_DAO::VALUE_SEPARATOR;
522 $dao = CRM_Core_DAO::executeQuery("SELECT id, form_values FROM civicrm_saved_search WHERE form_values LIKE '%$sep%'");
523 while ($dao->fetch()) {
524 $formValues = unserialize($dao->form_values);
525 if (isset($formValues['contact_type']) && is_array($formValues['contact_type'])) {
526 $newVals = array();
527 foreach ($formValues['contact_type'] as $key => $val) {
528 $newVals[str_replace($sep, '__', $key)] = is_string($val) ? str_replace($sep, '__', $val) : $val;
529 }
530 $formValues['contact_type'] = $newVals;
531 }
532 CRM_Core_DAO::executeQuery("UPDATE civicrm_saved_search SET form_values = %1 WHERE id = {$dao->id}", array(1 => array(serialize($formValues), 'String')));
533 }
534
535 return TRUE;
536 }
537
0094ac08
CW
538 /**
539 * CRM-17637 - Ths file location has been moved; delete the old one
540 *
541 * @param \CRM_Queue_TaskContext $ctx
542 *
543 * @return bool
544 */
5c9edd99 545 public static function deleteVersionCheckCacheFile(CRM_Queue_TaskContext $ctx) {
0094ac08
CW
546 $config = CRM_Core_Config::singleton();
547 $cacheFile = $config->uploadDir . 'version-info-cache.json';
548 if (file_exists($cacheFile)) {
549 unlink($cacheFile);
550 }
551 return TRUE;
552 }
553
fb1f3850
DRJ
554 /**
555 * CRM-17669 and CRM-17686, make scheduled jobs more flexible, disable the 4.6 extension if installed
556 *
557 * @param \CRM_Queue_TaskContext $ctx
558 *
559 * @return bool
560 */
5c9edd99 561 public static function disableFlexibleJobsExtension(CRM_Queue_TaskContext $ctx) {
d357221c
DRJ
562 try {
563 civicrm_api3('Extension', 'disable', array('key' => 'com.klangsoft.flexiblejobs'));
564 }
565 catch (CiviCRM_API3_Exception $e) {
566 // just ignore if the extension isn't installed
567 }
fb1f3850
DRJ
568
569 return TRUE;
570 }
571
20d5377e 572 /**
573 * CRM-17752 add index to civicrm_financial_trxn.trxn_id (deliberately non-unique).
574 *
575 * @param \CRM_Queue_TaskContext $ctx
576 *
577 * @return bool
578 */
5c9edd99 579 public static function addIndexFinancialTrxnTrxnID(CRM_Queue_TaskContext $ctx) {
20d5377e 580 $tables = array('civicrm_financial_trxn' => array('trxn_id'));
581 CRM_Core_BAO_SchemaHandler::createIndexes($tables);
582 return TRUE;
583 }
584
8ca47f5c 585 /**
586 * CRM-17882 Add index to civicrm_contribution.credit_note_id.
587 *
588 * @param \CRM_Queue_TaskContext $ctx
589 *
590 * @return bool
591 */
5c9edd99 592 public static function addIndexContributionCreditNoteID(CRM_Queue_TaskContext $ctx) {
8ca47f5c 593 $tables = array('civicrm_contribution' => array('creditnote_id'));
594 CRM_Core_BAO_SchemaHandler::createIndexes($tables);
595 return TRUE;
596 }
597
2179c899 598 /**
599 * CRM-17775 Add correct index for table civicrm_financial_item.
600 *
601 * Note that the entity ID should always precede the entity_table as
602 * it is more unique. This is better for performance and does not cause fallback
603 * to no index if table it omitted.
604 *
605 * @return bool
606 */
5c9edd99 607 public static function addCombinedIndexFinancialItemEntityIDEntityType() {
2179c899 608 CRM_Core_BAO_SchemaHandler::dropIndexIfExists('civicrm_financial_item', 'UI_id');
609 CRM_Core_BAO_SchemaHandler::dropIndexIfExists('civicrm_financial_item', 'IX_Entity');
610 CRM_Core_BAO_SchemaHandler::createIndexes(array(
611 'civicrm_financial_item' => array(array('entity_id', 'entity_table')),
612 ));
613 return TRUE;
614 }
615
1f395432 616 /**
617 * CRM-17951 Add accounts option values for refund and chargeback.
618 *
619 * Add Chargeback contribution status and Chargeback and Contra account relationships,
620 * checking first if one exists.
621 */
5c9edd99 622 public static function addRefundAndChargeBackAccountsIfNotExist() {
1f395432 623 // First we enable and edit the record for Credit contra - this exists but is disabled for most sites.
624 // Using the ensure function (below) will not enabled a disabled option (by design).
625 CRM_Core_DAO::executeQuery("UPDATE civicrm_option_value v
626 INNER JOIN civicrm_option_group g on v.option_group_id=g.id and g.name='account_relationship'
627 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'
628 WHERE v.name = 'Credit/Contra Account is';");
629
630 CRM_Core_BAO_OptionValue::ensureOptionValueExists(array(
631 'option_group_id' => 'account_relationship',
4a907feb
EM
632 'name' => 'Chargeback Account is',
633 'label' => ts('Chargeback Account is'),
1f395432 634 'is_active' => TRUE,
635 'component_id' => 'CiviContribute',
636 ));
637
638 CRM_Core_BAO_OptionValue::ensureOptionValueExists(array(
639 'option_group_id' => 'contribution_status',
640 'name' => 'Chargeback',
641 'label' => ts('Chargeback'),
642 'is_active' => TRUE,
643 'component_id' => 'CiviContribute',
644 ));
645 return TRUE;
646 }
647
3fe26f4c 648 /**
649 * CRM-17999 Add index to civicrm_contribution.source.
650 *
651 * @param \CRM_Queue_TaskContext $ctx
652 *
653 * @return bool
654 */
5c9edd99 655 public static function addIndexContributionSource(CRM_Queue_TaskContext $ctx) {
3fe26f4c 656 CRM_Core_BAO_SchemaHandler::createIndexes(array('civicrm_contribution' => array('source')));
657 return TRUE;
658 }
659
fd28b6a0 660 /**
661 * CRM-18124 Add index to civicrm_contribution.total_amount.
662 *
663 * Note that I made this a combined index with receive_date because the issue included
664 * both criteria and they seemed likely to be used in conjunction to me in other cases.
665 *
666 * @param \CRM_Queue_TaskContext $ctx
667 *
668 * @return bool
669 */
5c9edd99 670 public static function addIndexContributionAmount(CRM_Queue_TaskContext $ctx) {
fd28b6a0 671 CRM_Core_BAO_SchemaHandler::createIndexes(array(
672 'civicrm_contribution' => array(array('total_amount', 'receive_date')),
673 ));
674 return TRUE;
675 }
676
6eb752fa 677 /**
678 * CRM-18124 Add index to civicrm_contribution.total_amount.
679 *
680 * Note that I made this a combined index with receive_date because the issue included
681 * both criteria and they seemed likely to be used in conjunction to me in other cases.
682 *
683 * @param \CRM_Queue_TaskContext $ctx
684 *
685 * @return bool
686 */
5c9edd99 687 public static function addDeletedByMergeActivityType(CRM_Queue_TaskContext $ctx) {
6eb752fa 688 CRM_Core_BAO_OptionValue::ensureOptionValueExists(array(
689 'option_group_id' => 'activity_type',
690 'name' => 'Contact Deleted by Merge',
691 'label' => ts('Contact Deleted by Merge'),
692 'description' => ts('Contact was merged into another contact'),
693 'is_active' => TRUE,
e14e412b 694 'filter' => 1,
6eb752fa 695 ));
696 return TRUE;
697 }
698
da1ecd73
SL
699 /**
700 * CRM-12252 Add Help Pre and Help Post Fields for Price Field Value Table.
701 *
702 * @param \CRM_Queue_TaskContext $ctx
703 *
704 * @return bool
705 */
5c9edd99 706 public static function addHelpPreAndHelpPostFieldsPriceFieldValue(CRM_Queue_TaskContext $ctx) {
da1ecd73
SL
707 $domain = new CRM_Core_DAO_Domain();
708 $domain->find(TRUE);
709 if ($domain->locales) {
710 $locales = explode(CRM_Core_DAO::VALUE_SEPARATOR, $domain->locales);
711 foreach ($locales as $locale) {
01ee8ba6 712 if (!CRM_Core_BAO_SchemaHandler::checkIfFieldExists("civicrm_price_field_value", "help_pre_{$locale}")) {
3dc870a2
SL
713 CRM_Core_DAO::executeQuery("ALTER TABLE `civicrm_price_field_value`
714 ADD COLUMN `help_pre_{$locale}` text COLLATE utf8_unicode_ci COMMENT 'Price field option pre help text.'", array(), TRUE, NULL, FALSE, FALSE);
da1ecd73 715 }
01ee8ba6 716 if (!CRM_Core_BAO_SchemaHandler::checkIfFieldExists("civicrm_price_field_value", "help_post_{$locale}")) {
3dc870a2
SL
717 CRM_Core_DAO::executeQuery("ALTER TABLE `civicrm_price_field_value`
718 ADD COLUMN `help_post_{$locale}` text COLLATE utf8_unicode_ci COMMENT 'Price field option post help text.'", array(), TRUE, NULL, FALSE, FALSE);
da1ecd73
SL
719 }
720 }
01ee8ba6 721 CRM_Core_I18n_Schema::rebuildMultilingualSchema($locales, NULL);
da1ecd73
SL
722 }
723 else {
724 if (!CRM_Core_BAO_SchemaHandler::checkIfFieldExists('civicrm_price_field_value', 'help_pre')) {
3dc870a2
SL
725 CRM_Core_DAO::executeQuery("ALTER TABLE `civicrm_price_field_value`
726 ADD COLUMN `help_pre` text COLLATE utf8_unicode_ci COMMENT 'Price field option pre help text.'");
da1ecd73
SL
727 }
728 if (!CRM_Core_BAO_SchemaHandler::checkIfFieldExists('civicrm_price_field_value', 'help_post')) {
3dc870a2
SL
729 CRM_Core_DAO::executeQuery("ALTER TABLE `civicrm_price_field_value`
730 ADD COLUMN `help_post` text COLLATE utf8_unicode_ci COMMENT 'Price field option post help text.'");
da1ecd73
SL
731 }
732 }
733 return TRUE;
734 }
735
2cbdd085
J
736 /**
737 * CRM-18345 Don't delete mailing data on email/phone deletion
738 * Implemented here in CRM-18526
739 *
740 * @param \CRM_Queue_TaskContext $ctx
741 *
742 * @return bool
743 */
5c9edd99 744 public static function upgradeMailingFKs(CRM_Queue_TaskContext $ctx) {
2cbdd085
J
745
746 // Safely drop the foreign keys
169475b7
SL
747 CRM_Core_BAO_SchemaHandler::safeRemoveFK('civicrm_mailing_event_queue', 'FK_civicrm_mailing_event_queue_email_id');
748 CRM_Core_BAO_SchemaHandler::safeRemoveFK('civicrm_mailing_event_queue', 'FK_civicrm_mailing_event_queue_phone_id');
749 CRM_Core_BAO_SchemaHandler::safeRemoveFK('civicrm_mailing_recipients', 'FK_civicrm_mailing_recipients_email_id');
750 CRM_Core_BAO_SchemaHandler::safeRemoveFK('civicrm_mailing_recipients', 'FK_civicrm_mailing_recipients_phone_id');
2cbdd085
J
751
752 // Set up the new foreign keys
753 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
754
755 CRM_Core_DAO::executeQuery("
756 ALTER TABLE `civicrm_mailing_event_queue`
757 ADD CONSTRAINT `FK_civicrm_mailing_event_queue_email_id`
758 FOREIGN KEY (`email_id`)
759 REFERENCES `civicrm_email`(`id`)
760 ON DELETE SET NULL
761 ON UPDATE RESTRICT;
762 ");
763
764 CRM_Core_DAO::executeQuery("
765 ALTER TABLE `civicrm_mailing_event_queue`
766 ADD CONSTRAINT `FK_civicrm_mailing_event_queue_phone_id`
767 FOREIGN KEY (`phone_id`)
768 REFERENCES `civicrm_phone`(`id`)
769 ON DELETE SET NULL
770 ON UPDATE RESTRICT;
771 ");
772
773 CRM_Core_DAO::executeQuery("
774 ALTER TABLE `civicrm_mailing_recipients`
775 ADD CONSTRAINT `FK_civicrm_mailing_recipients_email_id`
776 FOREIGN KEY (`email_id`)
777 REFERENCES `civicrm_email`(`id`)
778 ON DELETE SET NULL
779 ON UPDATE RESTRICT;
780 ");
781
782 CRM_Core_DAO::executeQuery("
783 ALTER TABLE `civicrm_mailing_recipients`
784 ADD CONSTRAINT `FK_civicrm_mailing_recipients_phone_id`
785 FOREIGN KEY (`phone_id`)
786 REFERENCES `civicrm_phone`(`id`)
787 ON DELETE SET NULL
788 ON UPDATE RESTRICT;
789 ");
790
791 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
792
793 return TRUE;
794 }
795
00c27b41
CW
796 /**
797 * CRM-17663 - Dashboard schema changes
798 *
799 * @param \CRM_Queue_TaskContext $ctx
800 *
801 * @return bool
802 */
5c9edd99 803 public static function dashboardSchemaUpdate(CRM_Queue_TaskContext $ctx) {
00c27b41
CW
804 if (!CRM_Core_BAO_SchemaHandler::checkIfIndexExists('civicrm_dashboard_contact', 'index_dashboard_id_contact_id')) {
805 // Delete any stray duplicate rows and add unique index to prevent new dupes and enable INSERT/UPDATE combo query
806 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');
807 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_dashboard_contact ADD UNIQUE INDEX index_dashboard_id_contact_id (dashboard_id, contact_id);');
808 }
87568e34
SL
809 $domain = new CRM_Core_DAO_Domain();
810 $domain->find(TRUE);
242055d3
CW
811 CRM_Core_BAO_SchemaHandler::dropColumn('civicrm_dashboard_contact', 'content');
812 CRM_Core_BAO_SchemaHandler::dropColumn('civicrm_dashboard_contact', 'is_minimized');
813 CRM_Core_BAO_SchemaHandler::dropColumn('civicrm_dashboard_contact', 'is_fullscreen');
814 CRM_Core_BAO_SchemaHandler::dropColumn('civicrm_dashboard_contact', 'created_date');
815 CRM_Core_BAO_SchemaHandler::dropColumn('civicrm_dashboard', 'is_fullscreen');
816 CRM_Core_BAO_SchemaHandler::dropColumn('civicrm_dashboard', 'is_minimized');
817 CRM_Core_BAO_SchemaHandler::dropColumn('civicrm_dashboard', 'column_no');
818 CRM_Core_BAO_SchemaHandler::dropColumn('civicrm_dashboard', 'weight');
819
820 CRM_Core_DAO::executeQuery('UPDATE civicrm_dashboard SET url = REPLACE(url, "&snippet=5", ""), fullscreen_url = REPLACE(fullscreen_url, "&snippet=5", "")');
a8f56d71
CW
821
822 if (!CRM_Core_BAO_SchemaHandler::checkIfFieldExists('civicrm_dashboard', 'cache_minutes')) {
8c3f9072
SL
823 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."',
824 array(), TRUE, NULL, FALSE, FALSE);
825 }
826 if ($domain->locales) {
827 $locales = explode(CRM_Core_DAO::VALUE_SEPARATOR, $domain->locales);
828 CRM_Core_I18n_Schema::rebuildMultilingualSchema($locales, NULL);
a8f56d71
CW
829 }
830
831 CRM_Core_DAO::executeQuery('UPDATE civicrm_dashboard SET cache_minutes = 1440 WHERE name = "blog"');
832 CRM_Core_DAO::executeQuery('UPDATE civicrm_dashboard SET cache_minutes = 7200 WHERE name IN ("activity","getting-started")');
242055d3 833 return TRUE;
00c27b41
CW
834 }
835
8e2e96a5 836 /**
837 * CRM-19100 - Alter Index and Type for Image URL
838 * @return bool
839 */
840 public static function alterIndexAndTypeForImageURL() {
98daafd5 841 $length = array();
842 CRM_Core_BAO_SchemaHandler::dropIndexIfExists('civicrm_contact', 'index_image_url');
8e2e96a5 843 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.'");
98daafd5 844
845 $length['civicrm_contact']['image_URL'] = 128;
846 CRM_Core_BAO_SchemaHandler::createIndexes(array('civicrm_contact' => array('image_URL')), 'index', $length);
8e2e96a5 847
848 return TRUE;
849 }
850
d0e7e124
SL
851 /**
852 * CRM-18651 Add DataType column to Option Group Table
853 * @return bool
854 */
855 public static function addDataTypeColumnToOptionGroupTable() {
7c61320c 856 if (!CRM_Core_BAO_SchemaHandler::checkIfFieldExists('civicrm_option_group', 'data_type')) {
a37e4e6c
SL
857 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.'",
858 array(), TRUE, NULL, FALSE, FALSE);
859 }
860 $domain = new CRM_Core_DAO_Domain();
861 $domain->find(TRUE);
862 if ($domain->locales) {
863 $locales = explode(CRM_Core_DAO::VALUE_SEPARATOR, $domain->locales);
864 CRM_Core_I18n_Schema::rebuildMultilingualSchema($locales, NULL);
d0e7e124 865 }
a37e4e6c 866
d0e7e124
SL
867 CRM_Core_DAO::executeQuery("UPDATE `civicrm_option_group` SET `data_type` = 'Integer'
868 WHERE name IN ('activity_type', 'gender', 'payment_instrument', 'participant_role', 'event_type')");
869 return TRUE;
870 }
871
cb5962bd
SL
872 /**
873 * CRM-19372 Add field to store accepted credit credit cards for a payment processor.
874 * @return bool
875 */
876 public static function addAcceptedCardTypesField() {
877 if (!CRM_Core_BAO_SchemaHandler::checkIfFieldExists('civicrm_payment_processor', 'accepted_credit_cards')) {
878 CRM_Core_DAO::executeQuery("ALTER TABLE civicrm_payment_processor ADD COLUMN `accepted_credit_cards` text DEFAULT NULL COMMENT 'array of accepted credit card types'");
879 }
880 return TRUE;
881 }
882
6cc25669 883}