Attempt to fix upgrade and keep activity tab filter settings
[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 }
6cc25669
CW
102 }
103
6cc25669
CW
104 /**
105 * Upgrade function.
106 *
107 * @param string $rev
108 */
109 public function upgrade_4_7_alpha1($rev) {
b604d7ec 110 $this->addTask('Migrate \'on behalf of\' information to module_data', 'migrateOnBehalfOfInfo');
bf6a5362 111 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
f806379b 112 $this->addTask(ts('Migrate Settings to %1', array(1 => $rev)), 'migrateSettings', $rev);
b604d7ec 113 $this->addTask('Add Getting Started dashlet', 'addGettingStartedDashlet', $rev);
a40fd1ac
CW
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);
058b8a5e 123 $this->addTask(ts('Remove %1', array(1 => 'Moneris')), 'removePaymentProcessorType', 'Moneris');
b2222b9f 124 $this->addTask('Update Smart Groups', 'fixContactTypeInSmartGroups');
6cc25669
CW
125 }
126
0094ac08
CW
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
fb1f3850
DRJ
137 /**
138 * Upgrade function.
139 *
140 * @param string $rev
141 */
902e557f 142 public function upgrade_4_7_beta6($rev) {
13599400 143 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
fb1f3850 144 $this->addTask('Disable flexible jobs extension', 'disableFlexibleJobsExtension');
20d5377e 145 $this->addTask('Add Index to financial_trxn trxn_id field', 'addIndexFinancialTrxnTrxnID');
fb1f3850
DRJ
146 }
147
8ca47f5c 148 /**
149 * Upgrade function.
150 *
151 * @param string $rev
152 */
153 public function upgrade_4_7_1($rev) {
2af0b023 154 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
8ca47f5c 155 $this->addTask('Add Index to civicrm_contribution creditnote_id field', 'addIndexContributionCreditNoteID');
156 }
157
2179c899 158 /**
159 * Upgrade function.
160 *
161 * @param string $rev
162 */
163 public function upgrade_4_7_2($rev) {
2af0b023 164 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
2179c899 165 $this->addTask('Fix Index on civicrm_financial_item combined entity_id + entity_table', 'addCombinedIndexFinancialItemEntityIDEntityType');
1f395432 166 $this->addTask('enable financial account relationships for chargeback & refund', 'addRefundAndChargeBackAccountsIfNotExist');
3fe26f4c 167 $this->addTask('Add Index to civicrm_contribution.source', 'addIndexContributionSource');
2179c899 168 }
169
fd28b6a0 170 /**
171 * Upgrade function.
172 *
173 * @param string $rev
174 */
175 public function upgrade_4_7_3($rev) {
2af0b023 176 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
fd28b6a0 177 $this->addTask('Add Index to civicrm_contribution.total_amount', 'addIndexContributionAmount');
178 }
179
6eb752fa 180 /**
181 * Upgrade function.
182 *
183 * @param string $rev
184 */
185 public function upgrade_4_7_4($rev) {
2af0b023 186 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
6eb752fa 187 $this->addTask('Add Contact Deleted by Merge Activity Type', 'addDeletedByMergeActivityType');
188 }
189
2cbdd085
J
190 /**
191 * Upgrade function.
192 *
193 * @param string $rev
194 */
6a2d3987 195 public function upgrade_4_7_7($rev) {
2cbdd085 196 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
6a2d3987
J
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 }
2cbdd085
J
201 }
202
2af0b023
CW
203 /**
204 * Upgrade function.
205 *
206 * @param string $rev
207 */
6a2d3987 208 public function upgrade_4_7_8($rev) {
2af0b023 209 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => $rev)), 'runSql', $rev);
6a2d3987 210 $this->addTask('Upgrade mailing foreign key constraints', 'upgradeMailingFKs');
065ffec9
TO
211 }
212
2af0b023
CW
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
6cc25669
CW
229 /**
230 * CRM-16354
231 *
6dbe2c23 232 * @return int
6cc25669 233 */
6dbe2c23 234 public static function updateWysiwyg() {
aaffa79f 235 $editorID = Civi::settings()->get('editor_id');
6dbe2c23
CW
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";
08ef4ddd 239 Civi::settings()->set('editor_id', $newEditor);
6cc25669 240
6dbe2c23 241 return $editorID;
6cc25669
CW
242 }
243
f806379b
TO
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) {
4cc9e637
TO
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"');
3ddd2901
SL
257
258 // Handle Strange activity_tab_filter settings.
259 CRM_Core_DAO::executeQuery('CREATE TABLE civicrm_activity_setting LIKE civicrm_setting');
260 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_activity_setting DROP INDEX index_group_name');
261 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_activity_setting DROP COLUMN group_name');
262 CRM_Core_DAO::executeQuery('INSERT INTO civicrm_activity_setting (name, contact_id, domain_id, value)
263 SELECT DISTNCT name, contact_id, domain_id, value
264 FROM civicrm_setting
265 WHERE name = "activity_tab_filter"
266 AND value is not NULL');
ee4d8422 267 CRM_Core_DAO::executeQuery('DELETE FROM civicrm_setting WHERE name = "activity_tab_filter"');
4cc9e637 268
f806379b
TO
269 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_setting DROP INDEX index_group_name');
270 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_setting DROP COLUMN group_name');
271 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_setting ADD UNIQUE INDEX index_domain_contact_name (domain_id, contact_id, name)');
3ddd2901
SL
272 CRM_Core_DAO::executeQuery('INSERT INTO civicrm_setting (name, contact_id, domain_id, value)
273 SELECT DISTNCT name, contact_id, domain_id, value
274 FROM civicrm_activity_setting
275 WHERE name = "activity_tab_filter"
276 AND value is not NULL');
277 CRM_Core_DAO::executeQuery('DROP TABLE civicrm_activity_setting');
f806379b
TO
278
279 $domainDao = CRM_Core_DAO::executeQuery('SELECT id, config_backend FROM civicrm_domain');
280 while ($domainDao->fetch()) {
281 $settings = CRM_Upgrade_Incremental_php_FourSeven::convertBackendToSettings($domainDao->id, $domainDao->config_backend);
282 CRM_Core_Error::debug_var('convertBackendToSettings', array(
283 'domainId' => $domainDao->id,
284 'backend' => $domainDao->config_backend,
285 'settings' => $settings,
286 ));
287
288 foreach ($settings as $name => $value) {
289 $rowParams = array(
290 1 => array($domainDao->id, 'Positive'),
291 2 => array($name, 'String'),
292 3 => array(serialize($value), 'String'),
293 );
294 $settingId = CRM_Core_DAO::singleValueQuery(
295 'SELECT id FROM civicrm_setting WHERE domain_id = %1 AND name = %2',
296 $rowParams);
297 if (!$settingId) {
298 CRM_Core_DAO::executeQuery(
299 'INSERT INTO civicrm_setting (domain_id, name, value, is_domain) VALUES (%1,%2,%3,1)',
300 $rowParams);
301 }
302 }
303 }
304
9e726168 305 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_domain DROP COLUMN config_backend');
f806379b
TO
306
307 return TRUE;
308 }
309
310 /**
311 * Take a config_backend blob and produce an equivalent list of settings.
312 *
313 * @param int $domainId
314 * Domain ID.
315 * @param string $config_backend
316 * Serialized blob.
317 * @return array
318 */
319 public static function convertBackendToSettings($domainId, $config_backend) {
320 if (!$config_backend) {
321 return array();
322 }
323
324 $backend = unserialize($config_backend);
325 if (!$backend) {
326 return array();
327 }
328
329 $mappings = \CRM_Core_Config_MagicMerge::getPropertyMap();
330 $settings = array();
331 foreach ($backend as $propertyName => $propertyValue) {
332 if (isset($mappings[$propertyName][0]) && preg_match('/^setting/', $mappings[$propertyName][0])) {
333 // $mapping format: $propertyName => Array(0 => $type, 1 => $setting|NULL).
334 $settingName = isset($mappings[$propertyName][1]) ? $mappings[$propertyName][1] : $propertyName;
335 $settings[$settingName] = $propertyValue;
336 }
337 }
338
339 return $settings;
340 }
341
0a95c936 342 /**
343 * Add Getting Started dashlet to dashboard
344 *
345 * @param \CRM_Queue_TaskContext $ctx
346 *
347 * @return bool
348 */
349 public function addGettingStartedDashlet(CRM_Queue_TaskContext $ctx) {
9c4a04f2 350 $sql = "SELECT count(*) FROM civicrm_dashboard WHERE name='getting-started'";
e1674273 351 $res = CRM_Core_DAO::singleValueQuery($sql);
352 $domainId = CRM_Core_Config::domainID();
353 if ($res <= 0) {
354 $sql = "INSERT INTO `civicrm_dashboard`
a8b704c5 355 ( `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 356 CRM_Core_DAO::executeQuery($sql);
357 // Add default position for Getting Started Dashlet ( left column)
358 $sql = "INSERT INTO `civicrm_dashboard_contact` (dashboard_id, contact_id, column_no, is_active)
359SELECT (SELECT MAX(id) FROM `civicrm_dashboard`), contact_id, 0, IF (SUM(is_active) > 0, 1, 0)
429da6a1 360FROM `civicrm_dashboard_contact` JOIN `civicrm_contact` WHERE civicrm_dashboard_contact.contact_id = civicrm_contact.id GROUP BY contact_id";
e1674273 361 CRM_Core_DAO::executeQuery($sql);
362 }
0a95c936 363 return TRUE;
e1674273 364 }
4175ee03 365
6b1e1a2c 366 /**
367 * Migrate on-behalf information to uf_join.module_data as on-behalf columns will be dropped
368 * on DB upgrade
369 *
370 * @param CRM_Queue_TaskContext $ctx
371 *
372 * @return bool
373 * TRUE for success
374 */
375 public static function migrateOnBehalfOfInfo(CRM_Queue_TaskContext $ctx) {
d3e92c88 376 $domain = new CRM_Core_DAO_Domain();
377 $domain->find(TRUE);
6b1e1a2c 378
d3e92c88 379 // fetch onBehalf entry in UFJoin table
6b1e1a2c 380 $ufGroupDAO = new CRM_Core_DAO_UFJoin();
381 $ufGroupDAO->module = 'OnBehalf';
382 $ufGroupDAO->find(TRUE);
383
d3e92c88 384 $forOrgColums = array();
385 if ($domain->locales) {
386 $locales = explode(CRM_Core_DAO::VALUE_SEPARATOR, $domain->locales);
387 foreach ($locales as $locale) {
388 $forOrgColums[] = "for_organization_{$locale}";
389 }
390 }
391 else {
392 $forOrgColums[] = "for_organization";
393 }
394
395 $query = "
396 SELECT " . implode(", ", $forOrgColums) . ", uj.id as join_id, uj.uf_group_id as uf_group_id
397 FROM civicrm_contribution_page cp
398 INNER JOIN civicrm_uf_join uj ON uj.entity_id = cp.id AND uj.module = 'OnBehalf'";
399 $dao = CRM_Core_DAO::executeQuery($query, array(), TRUE, NULL, FALSE, FALSE);
6b1e1a2c 400
401 if ($dao->N) {
6b1e1a2c 402 while ($dao->fetch()) {
403 $onBehalfParams['on_behalf'] = array('is_for_organization' => $dao->is_for_organization);
404 if ($domain->locales) {
6b1e1a2c 405 foreach ($locales as $locale) {
406 $for_organization = "for_organization_{$locale}";
407 $onBehalfParams['on_behalf'] += array(
408 $locale => array(
409 'for_organization' => $dao->$for_organization,
410 ),
411 );
412 }
413 }
414 else {
415 $onBehalfParams['on_behalf'] += array(
416 'default' => array(
417 'for_organization' => $dao->for_organization,
418 ),
419 );
420 }
421 $ufJoinParam = array(
422 'id' => $dao->join_id,
423 'module' => 'on_behalf',
d3e92c88 424 'uf_group_id' => $dao->uf_group_id,
6b1e1a2c 425 'module_data' => json_encode($onBehalfParams),
426 );
427 CRM_Core_BAO_UFJoin::create($ufJoinParam);
428 }
429 }
430
431 return TRUE;
432 }
cb804cd9 433
b2222b9f
CW
434 /**
435 * CRM-11782 - Get rid of VALUE_SEPARATOR character in saved search form values
436 *
437 * @param \CRM_Queue_TaskContext $ctx
438 *
439 * @return bool
440 */
441 public function fixContactTypeInSmartGroups(CRM_Queue_TaskContext $ctx) {
442 $sep = CRM_Core_DAO::VALUE_SEPARATOR;
443 $dao = CRM_Core_DAO::executeQuery("SELECT id, form_values FROM civicrm_saved_search WHERE form_values LIKE '%$sep%'");
444 while ($dao->fetch()) {
445 $formValues = unserialize($dao->form_values);
446 if (isset($formValues['contact_type']) && is_array($formValues['contact_type'])) {
447 $newVals = array();
448 foreach ($formValues['contact_type'] as $key => $val) {
449 $newVals[str_replace($sep, '__', $key)] = is_string($val) ? str_replace($sep, '__', $val) : $val;
450 }
451 $formValues['contact_type'] = $newVals;
452 }
453 CRM_Core_DAO::executeQuery("UPDATE civicrm_saved_search SET form_values = %1 WHERE id = {$dao->id}", array(1 => array(serialize($formValues), 'String')));
454 }
455
456 return TRUE;
457 }
458
0094ac08
CW
459 /**
460 * CRM-17637 - Ths file location has been moved; delete the old one
461 *
462 * @param \CRM_Queue_TaskContext $ctx
463 *
464 * @return bool
465 */
466 public function deleteVersionCheckCacheFile(CRM_Queue_TaskContext $ctx) {
467 $config = CRM_Core_Config::singleton();
468 $cacheFile = $config->uploadDir . 'version-info-cache.json';
469 if (file_exists($cacheFile)) {
470 unlink($cacheFile);
471 }
472 return TRUE;
473 }
474
fb1f3850
DRJ
475 /**
476 * CRM-17669 and CRM-17686, make scheduled jobs more flexible, disable the 4.6 extension if installed
477 *
478 * @param \CRM_Queue_TaskContext $ctx
479 *
480 * @return bool
481 */
482 public function disableFlexibleJobsExtension(CRM_Queue_TaskContext $ctx) {
d357221c
DRJ
483 try {
484 civicrm_api3('Extension', 'disable', array('key' => 'com.klangsoft.flexiblejobs'));
485 }
486 catch (CiviCRM_API3_Exception $e) {
487 // just ignore if the extension isn't installed
488 }
fb1f3850
DRJ
489
490 return TRUE;
491 }
492
20d5377e 493 /**
494 * CRM-17752 add index to civicrm_financial_trxn.trxn_id (deliberately non-unique).
495 *
496 * @param \CRM_Queue_TaskContext $ctx
497 *
498 * @return bool
499 */
500 public function addIndexFinancialTrxnTrxnID(CRM_Queue_TaskContext $ctx) {
501 $tables = array('civicrm_financial_trxn' => array('trxn_id'));
502 CRM_Core_BAO_SchemaHandler::createIndexes($tables);
503 return TRUE;
504 }
505
8ca47f5c 506 /**
507 * CRM-17882 Add index to civicrm_contribution.credit_note_id.
508 *
509 * @param \CRM_Queue_TaskContext $ctx
510 *
511 * @return bool
512 */
513 public function addIndexContributionCreditNoteID(CRM_Queue_TaskContext $ctx) {
514 $tables = array('civicrm_contribution' => array('creditnote_id'));
515 CRM_Core_BAO_SchemaHandler::createIndexes($tables);
516 return TRUE;
517 }
518
2179c899 519 /**
520 * CRM-17775 Add correct index for table civicrm_financial_item.
521 *
522 * Note that the entity ID should always precede the entity_table as
523 * it is more unique. This is better for performance and does not cause fallback
524 * to no index if table it omitted.
525 *
526 * @return bool
527 */
528 public function addCombinedIndexFinancialItemEntityIDEntityType() {
529 CRM_Core_BAO_SchemaHandler::dropIndexIfExists('civicrm_financial_item', 'UI_id');
530 CRM_Core_BAO_SchemaHandler::dropIndexIfExists('civicrm_financial_item', 'IX_Entity');
531 CRM_Core_BAO_SchemaHandler::createIndexes(array(
532 'civicrm_financial_item' => array(array('entity_id', 'entity_table')),
533 ));
534 return TRUE;
535 }
536
1f395432 537 /**
538 * CRM-17951 Add accounts option values for refund and chargeback.
539 *
540 * Add Chargeback contribution status and Chargeback and Contra account relationships,
541 * checking first if one exists.
542 */
543 public function addRefundAndChargeBackAccountsIfNotExist() {
544 // First we enable and edit the record for Credit contra - this exists but is disabled for most sites.
545 // Using the ensure function (below) will not enabled a disabled option (by design).
546 CRM_Core_DAO::executeQuery("UPDATE civicrm_option_value v
547 INNER JOIN civicrm_option_group g on v.option_group_id=g.id and g.name='account_relationship'
548 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'
549 WHERE v.name = 'Credit/Contra Account is';");
550
551 CRM_Core_BAO_OptionValue::ensureOptionValueExists(array(
552 'option_group_id' => 'account_relationship',
4a907feb
EM
553 'name' => 'Chargeback Account is',
554 'label' => ts('Chargeback Account is'),
1f395432 555 'is_active' => TRUE,
556 'component_id' => 'CiviContribute',
557 ));
558
559 CRM_Core_BAO_OptionValue::ensureOptionValueExists(array(
560 'option_group_id' => 'contribution_status',
561 'name' => 'Chargeback',
562 'label' => ts('Chargeback'),
563 'is_active' => TRUE,
564 'component_id' => 'CiviContribute',
565 ));
566 return TRUE;
567 }
568
3fe26f4c 569 /**
570 * CRM-17999 Add index to civicrm_contribution.source.
571 *
572 * @param \CRM_Queue_TaskContext $ctx
573 *
574 * @return bool
575 */
576 public function addIndexContributionSource(CRM_Queue_TaskContext $ctx) {
577 CRM_Core_BAO_SchemaHandler::createIndexes(array('civicrm_contribution' => array('source')));
578 return TRUE;
579 }
580
fd28b6a0 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 addIndexContributionAmount(CRM_Queue_TaskContext $ctx) {
592 CRM_Core_BAO_SchemaHandler::createIndexes(array(
593 'civicrm_contribution' => array(array('total_amount', 'receive_date')),
594 ));
595 return TRUE;
596 }
597
6eb752fa 598 /**
599 * CRM-18124 Add index to civicrm_contribution.total_amount.
600 *
601 * Note that I made this a combined index with receive_date because the issue included
602 * both criteria and they seemed likely to be used in conjunction to me in other cases.
603 *
604 * @param \CRM_Queue_TaskContext $ctx
605 *
606 * @return bool
607 */
608 public function addDeletedByMergeActivityType(CRM_Queue_TaskContext $ctx) {
609 CRM_Core_BAO_OptionValue::ensureOptionValueExists(array(
610 'option_group_id' => 'activity_type',
611 'name' => 'Contact Deleted by Merge',
612 'label' => ts('Contact Deleted by Merge'),
613 'description' => ts('Contact was merged into another contact'),
614 'is_active' => TRUE,
e14e412b 615 'filter' => 1,
6eb752fa 616 ));
617 return TRUE;
618 }
619
2cbdd085
J
620 /**
621 * Remove a foreign key from a table if it exists
622 *
623 * @param $table_name
624 * @param $constraint_name
625 */
626 public function safeRemoveFK($table_name, $constraint_name) {
627
628 $config = CRM_Core_Config::singleton();
629 $dbUf = DB::parseDSN($config->dsn);
630 $query = "
631 SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
632 WHERE TABLE_SCHEMA = %1
633 AND TABLE_NAME = %2
634 AND CONSTRAINT_NAME = %3
635 AND CONSTRAINT_TYPE = 'FOREIGN KEY'
636 ";
637 $params = array(
638 1 => array($dbUf['database'], 'String'),
639 2 => array($table_name, 'String'),
640 3 => array($constraint_name, 'String'),
641 );
642 $dao = CRM_Core_DAO::executeQuery($query, $params);
643
644 if ($dao->fetch()) {
645 CRM_Core_DAO::executeQuery("ALTER TABLE {$table_name} DROP FOREIGN KEY {$constraint_name}", array());
646 }
647
648 }
649
650 /**
651 * CRM-18345 Don't delete mailing data on email/phone deletion
652 * Implemented here in CRM-18526
653 *
654 * @param \CRM_Queue_TaskContext $ctx
655 *
656 * @return bool
657 */
658 public function upgradeMailingFKs(CRM_Queue_TaskContext $ctx) {
659
660 // Safely drop the foreign keys
a430a278
J
661 self::safeRemoveFK('civicrm_mailing_event_queue', 'FK_civicrm_mailing_event_queue_email_id');
662 self::safeRemoveFK('civicrm_mailing_event_queue', 'FK_civicrm_mailing_event_queue_phone_id');
663 self::safeRemoveFK('civicrm_mailing_recipients', 'FK_civicrm_mailing_recipients_email_id');
664 self::safeRemoveFK('civicrm_mailing_recipients', 'FK_civicrm_mailing_recipients_phone_id');
2cbdd085
J
665
666 // Set up the new foreign keys
667 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
668
669 CRM_Core_DAO::executeQuery("
670 ALTER TABLE `civicrm_mailing_event_queue`
671 ADD CONSTRAINT `FK_civicrm_mailing_event_queue_email_id`
672 FOREIGN KEY (`email_id`)
673 REFERENCES `civicrm_email`(`id`)
674 ON DELETE SET NULL
675 ON UPDATE RESTRICT;
676 ");
677
678 CRM_Core_DAO::executeQuery("
679 ALTER TABLE `civicrm_mailing_event_queue`
680 ADD CONSTRAINT `FK_civicrm_mailing_event_queue_phone_id`
681 FOREIGN KEY (`phone_id`)
682 REFERENCES `civicrm_phone`(`id`)
683 ON DELETE SET NULL
684 ON UPDATE RESTRICT;
685 ");
686
687 CRM_Core_DAO::executeQuery("
688 ALTER TABLE `civicrm_mailing_recipients`
689 ADD CONSTRAINT `FK_civicrm_mailing_recipients_email_id`
690 FOREIGN KEY (`email_id`)
691 REFERENCES `civicrm_email`(`id`)
692 ON DELETE SET NULL
693 ON UPDATE RESTRICT;
694 ");
695
696 CRM_Core_DAO::executeQuery("
697 ALTER TABLE `civicrm_mailing_recipients`
698 ADD CONSTRAINT `FK_civicrm_mailing_recipients_phone_id`
699 FOREIGN KEY (`phone_id`)
700 REFERENCES `civicrm_phone`(`id`)
701 ON DELETE SET NULL
702 ON UPDATE RESTRICT;
703 ");
704
705 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
706
707 return TRUE;
708 }
709
6cc25669 710}