6a33eceda470d5564e6c68e5abf31014e43848da
[civicrm-core.git] / CRM / Upgrade / Incremental / php / FourSeven.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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.', array(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.', array(1 => 'Moneris')) . '</p>';
60 }
61 }
62 }
63
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.
71 */
72 public function setPostUpgradeMessage(&$postUpgradeMessage, $rev) {
73 if ($rev == '4.7.alpha1') {
74 $config = CRM_Core_Config::singleton();
75 // FIXME: Performing an upgrade step during postUpgrade message phase is probably bad
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>';
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).');
99
100 $postUpgradeMessage .= '<p>' . ts('The custom fatal error template setting has been removed.') . '</p>';
101 }
102 }
103
104 /**
105 * Upgrade function.
106 *
107 * @param string $rev
108 */
109 public function upgrade_4_7_alpha1($rev) {
110 $this->addTask('Migrate \'on behalf of\' information to module_data', 'migrateOnBehalfOfInfo');
111 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
112 $this->addTask(ts('Migrate Settings to %1', array(1 => $rev)), 'migrateSettings', $rev);
113 $this->addTask('Add Getting Started dashlet', 'addGettingStartedDashlet', $rev);
114 }
115
116 /**
117 * Upgrade function.
118 *
119 * @param string $rev
120 */
121 public function upgrade_4_7_alpha4($rev) {
122 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
123 $this->addTask(ts('Remove %1', array(1 => 'Moneris')), 'removePaymentProcessorType', 'Moneris');
124 $this->addTask('Update Smart Groups', 'fixContactTypeInSmartGroups');
125 }
126
127 /**
128 * Upgrade function.
129 *
130 * @param string $rev
131 */
132 public function upgrade_4_7_beta2($rev) {
133 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
134 $this->addTask('Delete unused file', 'deleteVersionCheckCacheFile');
135 }
136
137 /**
138 * Upgrade function.
139 *
140 * @param string $rev
141 */
142 public function upgrade_4_7_beta6($rev) {
143 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
144 $this->addTask('Disable flexible jobs extension', 'disableFlexibleJobsExtension');
145 $this->addTask('Add Index to financial_trxn trxn_id field', 'addIndexFinancialTrxnTrxnID');
146 }
147
148 /**
149 * Upgrade function.
150 *
151 * @param string $rev
152 */
153 public function upgrade_4_7_1($rev) {
154 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
155 $this->addTask('Add Index to civicrm_contribution creditnote_id field', 'addIndexContributionCreditNoteID');
156 }
157
158 /**
159 * Upgrade function.
160 *
161 * @param string $rev
162 */
163 public function upgrade_4_7_2($rev) {
164 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
165 $this->addTask('Fix Index on civicrm_financial_item combined entity_id + entity_table', 'addCombinedIndexFinancialItemEntityIDEntityType');
166 $this->addTask('enable financial account relationships for chargeback & refund', 'addRefundAndChargeBackAccountsIfNotExist');
167 $this->addTask('Add Index to civicrm_contribution.source', 'addIndexContributionSource');
168 }
169
170 /**
171 * Upgrade function.
172 *
173 * @param string $rev
174 */
175 public function upgrade_4_7_3($rev) {
176 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
177 $this->addTask('Add Index to civicrm_contribution.total_amount', 'addIndexContributionAmount');
178 }
179
180 /**
181 * Upgrade function.
182 *
183 * @param string $rev
184 */
185 public function upgrade_4_7_4($rev) {
186 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
187 $this->addTask('Add Contact Deleted by Merge Activity Type', 'addDeletedByMergeActivityType');
188 }
189
190 /**
191 * Upgrade function.
192 *
193 * @param string $rev
194 */
195 public function upgrade_4_7_7($rev) {
196 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
197 // https://issues.civicrm.org/jira/browse/CRM-18006
198 if (CRM_Core_DAO::checkTableExists('civicrm_install_canary')) {
199 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_install_canary ENGINE=InnoDB');
200 }
201 }
202
203 /**
204 * Upgrade function.
205 *
206 * @param string $rev
207 */
208 public function upgrade_4_7_8($rev) {
209 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
210 $this->addTask('Upgrade mailing foreign key constraints', 'upgradeMailingFKs');
211 }
212
213 /*
214 * Important! All upgrade functions MUST call the 'runSql' task.
215 * Uncomment and use the following template for a new upgrade version
216 * (change the x in the function name):
217 */
218
219 // /**
220 // * Upgrade function.
221 // *
222 // * @param string $rev
223 // */
224 // public function upgrade_4_7_x($rev) {
225 // $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
226 // // Additional tasks here...
227 // }
228
229 /**
230 * CRM-16354
231 *
232 * @return int
233 */
234 public static function updateWysiwyg() {
235 $editorID = Civi::settings()->get('editor_id');
236 // Previously a numeric value indicated one of 4 wysiwyg editors shipped in core, and no value indicated 'Textarea'
237 // Now the options are "Textarea", "CKEditor", and the rest have been dropped from core.
238 $newEditor = $editorID ? "CKEditor" : "Textarea";
239 Civi::settings()->set('editor_id', $newEditor);
240
241 return $editorID;
242 }
243
244 /**
245 * Migrate any last remaining options from `civicrm_domain.config_backend` to `civicrm_setting`.
246 * Cleanup setting schema.
247 *
248 * @param CRM_Queue_TaskContext $ctx
249 * @return bool
250 */
251 public function migrateSettings(CRM_Queue_TaskContext $ctx) {
252 // Tip: If there are problems with adding the new uniqueness index, try inspecting:
253 // SELECT name, domain_id, contact_id, count(*) AS dupes FROM civicrm_setting cs GROUP BY name, domain_id, contact_id HAVING dupes > 1;
254
255 // Nav records are expendable. https://forum.civicrm.org/index.php?topic=36933.0
256 CRM_Core_DAO::executeQuery('DELETE FROM civicrm_setting WHERE contact_id IS NOT NULL AND name = "navigation"');
257
258 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_setting DROP INDEX index_group_name');
259 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_setting DROP COLUMN group_name');
260 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_setting ADD UNIQUE INDEX index_domain_contact_name (domain_id, contact_id, name)');
261
262 $domainDao = CRM_Core_DAO::executeQuery('SELECT id, config_backend FROM civicrm_domain');
263 while ($domainDao->fetch()) {
264 $settings = CRM_Upgrade_Incremental_php_FourSeven::convertBackendToSettings($domainDao->id, $domainDao->config_backend);
265 CRM_Core_Error::debug_var('convertBackendToSettings', array(
266 'domainId' => $domainDao->id,
267 'backend' => $domainDao->config_backend,
268 'settings' => $settings,
269 ));
270
271 foreach ($settings as $name => $value) {
272 $rowParams = array(
273 1 => array($domainDao->id, 'Positive'),
274 2 => array($name, 'String'),
275 3 => array(serialize($value), 'String'),
276 );
277 $settingId = CRM_Core_DAO::singleValueQuery(
278 'SELECT id FROM civicrm_setting WHERE domain_id = %1 AND name = %2',
279 $rowParams);
280 if (!$settingId) {
281 CRM_Core_DAO::executeQuery(
282 'INSERT INTO civicrm_setting (domain_id, name, value, is_domain) VALUES (%1,%2,%3,1)',
283 $rowParams);
284 }
285 }
286 }
287
288 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_domain DROP COLUMN config_backend');
289
290 return TRUE;
291 }
292
293 /**
294 * Take a config_backend blob and produce an equivalent list of settings.
295 *
296 * @param int $domainId
297 * Domain ID.
298 * @param string $config_backend
299 * Serialized blob.
300 * @return array
301 */
302 public static function convertBackendToSettings($domainId, $config_backend) {
303 if (!$config_backend) {
304 return array();
305 }
306
307 $backend = unserialize($config_backend);
308 if (!$backend) {
309 return array();
310 }
311
312 $mappings = \CRM_Core_Config_MagicMerge::getPropertyMap();
313 $settings = array();
314 foreach ($backend as $propertyName => $propertyValue) {
315 if (isset($mappings[$propertyName][0]) && preg_match('/^setting/', $mappings[$propertyName][0])) {
316 // $mapping format: $propertyName => Array(0 => $type, 1 => $setting|NULL).
317 $settingName = isset($mappings[$propertyName][1]) ? $mappings[$propertyName][1] : $propertyName;
318 $settings[$settingName] = $propertyValue;
319 }
320 }
321
322 return $settings;
323 }
324
325 /**
326 * Add Getting Started dashlet to dashboard
327 *
328 * @param \CRM_Queue_TaskContext $ctx
329 *
330 * @return bool
331 */
332 public function addGettingStartedDashlet(CRM_Queue_TaskContext $ctx) {
333 $sql = "SELECT count(*) FROM civicrm_dashboard WHERE name='getting-started'";
334 $res = CRM_Core_DAO::singleValueQuery($sql);
335 $domainId = CRM_Core_Config::domainID();
336 if ($res <= 0) {
337 $sql = "INSERT INTO `civicrm_dashboard`
338 ( `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)";
339 CRM_Core_DAO::executeQuery($sql);
340 // Add default position for Getting Started Dashlet ( left column)
341 $sql = "INSERT INTO `civicrm_dashboard_contact` (dashboard_id, contact_id, column_no, is_active)
342 SELECT (SELECT MAX(id) FROM `civicrm_dashboard`), contact_id, 0, IF (SUM(is_active) > 0, 1, 0)
343 FROM `civicrm_dashboard_contact` JOIN `civicrm_contact` WHERE civicrm_dashboard_contact.contact_id = civicrm_contact.id GROUP BY contact_id";
344 CRM_Core_DAO::executeQuery($sql);
345 }
346 return TRUE;
347 }
348
349 /**
350 * Migrate on-behalf information to uf_join.module_data as on-behalf columns will be dropped
351 * on DB upgrade
352 *
353 * @param CRM_Queue_TaskContext $ctx
354 *
355 * @return bool
356 * TRUE for success
357 */
358 public static function migrateOnBehalfOfInfo(CRM_Queue_TaskContext $ctx) {
359 $domain = new CRM_Core_DAO_Domain();
360 $domain->find(TRUE);
361
362 // fetch onBehalf entry in UFJoin table
363 $ufGroupDAO = new CRM_Core_DAO_UFJoin();
364 $ufGroupDAO->module = 'OnBehalf';
365 $ufGroupDAO->find(TRUE);
366
367 $forOrgColums = array();
368 if ($domain->locales) {
369 $locales = explode(CRM_Core_DAO::VALUE_SEPARATOR, $domain->locales);
370 foreach ($locales as $locale) {
371 $forOrgColums[] = "for_organization_{$locale}";
372 }
373 }
374 else {
375 $forOrgColums[] = "for_organization";
376 }
377
378 $query = "
379 SELECT " . implode(", ", $forOrgColums) . ", uj.id as join_id, uj.uf_group_id as uf_group_id
380 FROM civicrm_contribution_page cp
381 INNER JOIN civicrm_uf_join uj ON uj.entity_id = cp.id AND uj.module = 'OnBehalf'";
382 $dao = CRM_Core_DAO::executeQuery($query, array(), TRUE, NULL, FALSE, FALSE);
383
384 if ($dao->N) {
385 while ($dao->fetch()) {
386 $onBehalfParams['on_behalf'] = array('is_for_organization' => $dao->is_for_organization);
387 if ($domain->locales) {
388 foreach ($locales as $locale) {
389 $for_organization = "for_organization_{$locale}";
390 $onBehalfParams['on_behalf'] += array(
391 $locale => array(
392 'for_organization' => $dao->$for_organization,
393 ),
394 );
395 }
396 }
397 else {
398 $onBehalfParams['on_behalf'] += array(
399 'default' => array(
400 'for_organization' => $dao->for_organization,
401 ),
402 );
403 }
404 $ufJoinParam = array(
405 'id' => $dao->join_id,
406 'module' => 'on_behalf',
407 'uf_group_id' => $dao->uf_group_id,
408 'module_data' => json_encode($onBehalfParams),
409 );
410 CRM_Core_BAO_UFJoin::create($ufJoinParam);
411 }
412 }
413
414 return TRUE;
415 }
416
417 /**
418 * CRM-11782 - Get rid of VALUE_SEPARATOR character in saved search form values
419 *
420 * @param \CRM_Queue_TaskContext $ctx
421 *
422 * @return bool
423 */
424 public function fixContactTypeInSmartGroups(CRM_Queue_TaskContext $ctx) {
425 $sep = CRM_Core_DAO::VALUE_SEPARATOR;
426 $dao = CRM_Core_DAO::executeQuery("SELECT id, form_values FROM civicrm_saved_search WHERE form_values LIKE '%$sep%'");
427 while ($dao->fetch()) {
428 $formValues = unserialize($dao->form_values);
429 if (isset($formValues['contact_type']) && is_array($formValues['contact_type'])) {
430 $newVals = array();
431 foreach ($formValues['contact_type'] as $key => $val) {
432 $newVals[str_replace($sep, '__', $key)] = is_string($val) ? str_replace($sep, '__', $val) : $val;
433 }
434 $formValues['contact_type'] = $newVals;
435 }
436 CRM_Core_DAO::executeQuery("UPDATE civicrm_saved_search SET form_values = %1 WHERE id = {$dao->id}", array(1 => array(serialize($formValues), 'String')));
437 }
438
439 return TRUE;
440 }
441
442 /**
443 * CRM-17637 - Ths file location has been moved; delete the old one
444 *
445 * @param \CRM_Queue_TaskContext $ctx
446 *
447 * @return bool
448 */
449 public function deleteVersionCheckCacheFile(CRM_Queue_TaskContext $ctx) {
450 $config = CRM_Core_Config::singleton();
451 $cacheFile = $config->uploadDir . 'version-info-cache.json';
452 if (file_exists($cacheFile)) {
453 unlink($cacheFile);
454 }
455 return TRUE;
456 }
457
458 /**
459 * CRM-17669 and CRM-17686, make scheduled jobs more flexible, disable the 4.6 extension if installed
460 *
461 * @param \CRM_Queue_TaskContext $ctx
462 *
463 * @return bool
464 */
465 public function disableFlexibleJobsExtension(CRM_Queue_TaskContext $ctx) {
466 try {
467 civicrm_api3('Extension', 'disable', array('key' => 'com.klangsoft.flexiblejobs'));
468 }
469 catch (CiviCRM_API3_Exception $e) {
470 // just ignore if the extension isn't installed
471 }
472
473 return TRUE;
474 }
475
476 /**
477 * CRM-17752 add index to civicrm_financial_trxn.trxn_id (deliberately non-unique).
478 *
479 * @param \CRM_Queue_TaskContext $ctx
480 *
481 * @return bool
482 */
483 public function addIndexFinancialTrxnTrxnID(CRM_Queue_TaskContext $ctx) {
484 $tables = array('civicrm_financial_trxn' => array('trxn_id'));
485 CRM_Core_BAO_SchemaHandler::createIndexes($tables);
486 return TRUE;
487 }
488
489 /**
490 * CRM-17882 Add index to civicrm_contribution.credit_note_id.
491 *
492 * @param \CRM_Queue_TaskContext $ctx
493 *
494 * @return bool
495 */
496 public function addIndexContributionCreditNoteID(CRM_Queue_TaskContext $ctx) {
497 $tables = array('civicrm_contribution' => array('creditnote_id'));
498 CRM_Core_BAO_SchemaHandler::createIndexes($tables);
499 return TRUE;
500 }
501
502 /**
503 * CRM-17775 Add correct index for table civicrm_financial_item.
504 *
505 * Note that the entity ID should always precede the entity_table as
506 * it is more unique. This is better for performance and does not cause fallback
507 * to no index if table it omitted.
508 *
509 * @return bool
510 */
511 public function addCombinedIndexFinancialItemEntityIDEntityType() {
512 CRM_Core_BAO_SchemaHandler::dropIndexIfExists('civicrm_financial_item', 'UI_id');
513 CRM_Core_BAO_SchemaHandler::dropIndexIfExists('civicrm_financial_item', 'IX_Entity');
514 CRM_Core_BAO_SchemaHandler::createIndexes(array(
515 'civicrm_financial_item' => array(array('entity_id', 'entity_table')),
516 ));
517 return TRUE;
518 }
519
520 /**
521 * CRM-17951 Add accounts option values for refund and chargeback.
522 *
523 * Add Chargeback contribution status and Chargeback and Contra account relationships,
524 * checking first if one exists.
525 */
526 public function addRefundAndChargeBackAccountsIfNotExist() {
527 // First we enable and edit the record for Credit contra - this exists but is disabled for most sites.
528 // Using the ensure function (below) will not enabled a disabled option (by design).
529 CRM_Core_DAO::executeQuery("UPDATE civicrm_option_value v
530 INNER JOIN civicrm_option_group g on v.option_group_id=g.id and g.name='account_relationship'
531 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'
532 WHERE v.name = 'Credit/Contra Account is';");
533
534 CRM_Core_BAO_OptionValue::ensureOptionValueExists(array(
535 'option_group_id' => 'account_relationship',
536 'name' => 'Chargeback Account is',
537 'label' => ts('Chargeback Account is'),
538 'is_active' => TRUE,
539 'component_id' => 'CiviContribute',
540 ));
541
542 CRM_Core_BAO_OptionValue::ensureOptionValueExists(array(
543 'option_group_id' => 'contribution_status',
544 'name' => 'Chargeback',
545 'label' => ts('Chargeback'),
546 'is_active' => TRUE,
547 'component_id' => 'CiviContribute',
548 ));
549 return TRUE;
550 }
551
552 /**
553 * CRM-17999 Add index to civicrm_contribution.source.
554 *
555 * @param \CRM_Queue_TaskContext $ctx
556 *
557 * @return bool
558 */
559 public function addIndexContributionSource(CRM_Queue_TaskContext $ctx) {
560 CRM_Core_BAO_SchemaHandler::createIndexes(array('civicrm_contribution' => array('source')));
561 return TRUE;
562 }
563
564 /**
565 * CRM-18124 Add index to civicrm_contribution.total_amount.
566 *
567 * Note that I made this a combined index with receive_date because the issue included
568 * both criteria and they seemed likely to be used in conjunction to me in other cases.
569 *
570 * @param \CRM_Queue_TaskContext $ctx
571 *
572 * @return bool
573 */
574 public function addIndexContributionAmount(CRM_Queue_TaskContext $ctx) {
575 CRM_Core_BAO_SchemaHandler::createIndexes(array(
576 'civicrm_contribution' => array(array('total_amount', 'receive_date')),
577 ));
578 return TRUE;
579 }
580
581 /**
582 * CRM-18124 Add index to civicrm_contribution.total_amount.
583 *
584 * Note that I made this a combined index with receive_date because the issue included
585 * both criteria and they seemed likely to be used in conjunction to me in other cases.
586 *
587 * @param \CRM_Queue_TaskContext $ctx
588 *
589 * @return bool
590 */
591 public function addDeletedByMergeActivityType(CRM_Queue_TaskContext $ctx) {
592 CRM_Core_BAO_OptionValue::ensureOptionValueExists(array(
593 'option_group_id' => 'activity_type',
594 'name' => 'Contact Deleted by Merge',
595 'label' => ts('Contact Deleted by Merge'),
596 'description' => ts('Contact was merged into another contact'),
597 'is_active' => TRUE,
598 'filter' => 1,
599 ));
600 return TRUE;
601 }
602
603 /**
604 * Remove a foreign key from a table if it exists
605 *
606 * @param $table_name
607 * @param $constraint_name
608 */
609 public function safeRemoveFK($table_name, $constraint_name) {
610
611 $config = CRM_Core_Config::singleton();
612 $dbUf = DB::parseDSN($config->dsn);
613 $query = "
614 SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
615 WHERE TABLE_SCHEMA = %1
616 AND TABLE_NAME = %2
617 AND CONSTRAINT_NAME = %3
618 AND CONSTRAINT_TYPE = 'FOREIGN KEY'
619 ";
620 $params = array(
621 1 => array($dbUf['database'], 'String'),
622 2 => array($table_name, 'String'),
623 3 => array($constraint_name, 'String'),
624 );
625 $dao = CRM_Core_DAO::executeQuery($query, $params);
626
627 if ($dao->fetch()) {
628 CRM_Core_DAO::executeQuery("ALTER TABLE {$table_name} DROP FOREIGN KEY {$constraint_name}", array());
629 }
630
631 }
632
633 /**
634 * CRM-18345 Don't delete mailing data on email/phone deletion
635 * Implemented here in CRM-18526
636 *
637 * @param \CRM_Queue_TaskContext $ctx
638 *
639 * @return bool
640 */
641 public function upgradeMailingFKs(CRM_Queue_TaskContext $ctx) {
642
643 // Safely drop the foreign keys
644 self::safeRemoveFK('civicrm_mailing_event_queue', 'FK_civicrm_mailing_event_queue_email_id');
645 self::safeRemoveFK('civicrm_mailing_event_queue', 'FK_civicrm_mailing_event_queue_phone_id');
646 self::safeRemoveFK('civicrm_mailing_recipients', 'FK_civicrm_mailing_recipients_email_id');
647 self::safeRemoveFK('civicrm_mailing_recipients', 'FK_civicrm_mailing_recipients_phone_id');
648
649 // Set up the new foreign keys
650 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
651
652 CRM_Core_DAO::executeQuery("
653 ALTER TABLE `civicrm_mailing_event_queue`
654 ADD CONSTRAINT `FK_civicrm_mailing_event_queue_email_id`
655 FOREIGN KEY (`email_id`)
656 REFERENCES `civicrm_email`(`id`)
657 ON DELETE SET NULL
658 ON UPDATE RESTRICT;
659 ");
660
661 CRM_Core_DAO::executeQuery("
662 ALTER TABLE `civicrm_mailing_event_queue`
663 ADD CONSTRAINT `FK_civicrm_mailing_event_queue_phone_id`
664 FOREIGN KEY (`phone_id`)
665 REFERENCES `civicrm_phone`(`id`)
666 ON DELETE SET NULL
667 ON UPDATE RESTRICT;
668 ");
669
670 CRM_Core_DAO::executeQuery("
671 ALTER TABLE `civicrm_mailing_recipients`
672 ADD CONSTRAINT `FK_civicrm_mailing_recipients_email_id`
673 FOREIGN KEY (`email_id`)
674 REFERENCES `civicrm_email`(`id`)
675 ON DELETE SET NULL
676 ON UPDATE RESTRICT;
677 ");
678
679 CRM_Core_DAO::executeQuery("
680 ALTER TABLE `civicrm_mailing_recipients`
681 ADD CONSTRAINT `FK_civicrm_mailing_recipients_phone_id`
682 FOREIGN KEY (`phone_id`)
683 REFERENCES `civicrm_phone`(`id`)
684 ON DELETE SET NULL
685 ON UPDATE RESTRICT;
686 ");
687
688 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
689
690 return TRUE;
691 }
692
693 }