Merge pull request #7789 from rohankatkar/CRM18010_Additional_Changes
[civicrm-core.git] / CRM / Upgrade / Incremental / php / FourSeven.php
CommitLineData
6cc25669
CW
1<?php
2/*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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) {
154 $this->addTask('Add Index to civicrm_contribution creditnote_id field', 'addIndexContributionCreditNoteID');
155 }
156
2179c899 157 /**
158 * Upgrade function.
159 *
160 * @param string $rev
161 */
162 public function upgrade_4_7_2($rev) {
163 $this->addTask('Fix Index on civicrm_financial_item combined entity_id + entity_table', 'addCombinedIndexFinancialItemEntityIDEntityType');
1f395432 164 $this->addTask('enable financial account relationships for chargeback & refund', 'addRefundAndChargeBackAccountsIfNotExist');
3fe26f4c 165 $this->addTask('Add Index to civicrm_contribution.source', 'addIndexContributionSource');
2179c899 166 }
167
6cc25669
CW
168 /**
169 * CRM-16354
170 *
6dbe2c23 171 * @return int
6cc25669 172 */
6dbe2c23 173 public static function updateWysiwyg() {
aaffa79f 174 $editorID = Civi::settings()->get('editor_id');
6dbe2c23
CW
175 // Previously a numeric value indicated one of 4 wysiwyg editors shipped in core, and no value indicated 'Textarea'
176 // Now the options are "Textarea", "CKEditor", and the rest have been dropped from core.
177 $newEditor = $editorID ? "CKEditor" : "Textarea";
08ef4ddd 178 Civi::settings()->set('editor_id', $newEditor);
6cc25669 179
6dbe2c23 180 return $editorID;
6cc25669
CW
181 }
182
f806379b
TO
183 /**
184 * Migrate any last remaining options from `civicrm_domain.config_backend` to `civicrm_setting`.
185 * Cleanup setting schema.
186 *
187 * @param CRM_Queue_TaskContext $ctx
188 * @return bool
189 */
190 public function migrateSettings(CRM_Queue_TaskContext $ctx) {
4cc9e637
TO
191 // Tip: If there are problems with adding the new uniqueness index, try inspecting:
192 // SELECT name, domain_id, contact_id, count(*) AS dupes FROM civicrm_setting cs GROUP BY name, domain_id, contact_id HAVING dupes > 1;
193
194 // Nav records are expendable. https://forum.civicrm.org/index.php?topic=36933.0
195 CRM_Core_DAO::executeQuery('DELETE FROM civicrm_setting WHERE contact_id IS NOT NULL AND name = "navigation"');
196
f806379b
TO
197 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_setting DROP INDEX index_group_name');
198 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_setting DROP COLUMN group_name');
199 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_setting ADD UNIQUE INDEX index_domain_contact_name (domain_id, contact_id, name)');
200
201 $domainDao = CRM_Core_DAO::executeQuery('SELECT id, config_backend FROM civicrm_domain');
202 while ($domainDao->fetch()) {
203 $settings = CRM_Upgrade_Incremental_php_FourSeven::convertBackendToSettings($domainDao->id, $domainDao->config_backend);
204 CRM_Core_Error::debug_var('convertBackendToSettings', array(
205 'domainId' => $domainDao->id,
206 'backend' => $domainDao->config_backend,
207 'settings' => $settings,
208 ));
209
210 foreach ($settings as $name => $value) {
211 $rowParams = array(
212 1 => array($domainDao->id, 'Positive'),
213 2 => array($name, 'String'),
214 3 => array(serialize($value), 'String'),
215 );
216 $settingId = CRM_Core_DAO::singleValueQuery(
217 'SELECT id FROM civicrm_setting WHERE domain_id = %1 AND name = %2',
218 $rowParams);
219 if (!$settingId) {
220 CRM_Core_DAO::executeQuery(
221 'INSERT INTO civicrm_setting (domain_id, name, value, is_domain) VALUES (%1,%2,%3,1)',
222 $rowParams);
223 }
224 }
225 }
226
9e726168 227 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_domain DROP COLUMN config_backend');
f806379b
TO
228
229 return TRUE;
230 }
231
232 /**
233 * Take a config_backend blob and produce an equivalent list of settings.
234 *
235 * @param int $domainId
236 * Domain ID.
237 * @param string $config_backend
238 * Serialized blob.
239 * @return array
240 */
241 public static function convertBackendToSettings($domainId, $config_backend) {
242 if (!$config_backend) {
243 return array();
244 }
245
246 $backend = unserialize($config_backend);
247 if (!$backend) {
248 return array();
249 }
250
251 $mappings = \CRM_Core_Config_MagicMerge::getPropertyMap();
252 $settings = array();
253 foreach ($backend as $propertyName => $propertyValue) {
254 if (isset($mappings[$propertyName][0]) && preg_match('/^setting/', $mappings[$propertyName][0])) {
255 // $mapping format: $propertyName => Array(0 => $type, 1 => $setting|NULL).
256 $settingName = isset($mappings[$propertyName][1]) ? $mappings[$propertyName][1] : $propertyName;
257 $settings[$settingName] = $propertyValue;
258 }
259 }
260
261 return $settings;
262 }
263
0a95c936 264 /**
265 * Add Getting Started dashlet to dashboard
266 *
267 * @param \CRM_Queue_TaskContext $ctx
268 *
269 * @return bool
270 */
271 public function addGettingStartedDashlet(CRM_Queue_TaskContext $ctx) {
e1674273 272 $sql = "SELECT count(*) FROM civicrm_dashboard WHERE name='gettingStarted'";
273 $res = CRM_Core_DAO::singleValueQuery($sql);
274 $domainId = CRM_Core_Config::domainID();
275 if ($res <= 0) {
276 $sql = "INSERT INTO `civicrm_dashboard`
a8b704c5 277 ( `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 278 CRM_Core_DAO::executeQuery($sql);
279 // Add default position for Getting Started Dashlet ( left column)
280 $sql = "INSERT INTO `civicrm_dashboard_contact` (dashboard_id, contact_id, column_no, is_active)
281SELECT (SELECT MAX(id) FROM `civicrm_dashboard`), contact_id, 0, IF (SUM(is_active) > 0, 1, 0)
282FROM `civicrm_dashboard_contact` WHERE 1 GROUP BY contact_id";
283 CRM_Core_DAO::executeQuery($sql);
284 }
0a95c936 285 return TRUE;
e1674273 286 }
4175ee03 287
6b1e1a2c 288 /**
289 * Migrate on-behalf information to uf_join.module_data as on-behalf columns will be dropped
290 * on DB upgrade
291 *
292 * @param CRM_Queue_TaskContext $ctx
293 *
294 * @return bool
295 * TRUE for success
296 */
297 public static function migrateOnBehalfOfInfo(CRM_Queue_TaskContext $ctx) {
d3e92c88 298 $domain = new CRM_Core_DAO_Domain();
299 $domain->find(TRUE);
6b1e1a2c 300
d3e92c88 301 // fetch onBehalf entry in UFJoin table
6b1e1a2c 302 $ufGroupDAO = new CRM_Core_DAO_UFJoin();
303 $ufGroupDAO->module = 'OnBehalf';
304 $ufGroupDAO->find(TRUE);
305
d3e92c88 306 $forOrgColums = array();
307 if ($domain->locales) {
308 $locales = explode(CRM_Core_DAO::VALUE_SEPARATOR, $domain->locales);
309 foreach ($locales as $locale) {
310 $forOrgColums[] = "for_organization_{$locale}";
311 }
312 }
313 else {
314 $forOrgColums[] = "for_organization";
315 }
316
317 $query = "
318 SELECT " . implode(", ", $forOrgColums) . ", uj.id as join_id, uj.uf_group_id as uf_group_id
319 FROM civicrm_contribution_page cp
320 INNER JOIN civicrm_uf_join uj ON uj.entity_id = cp.id AND uj.module = 'OnBehalf'";
321 $dao = CRM_Core_DAO::executeQuery($query, array(), TRUE, NULL, FALSE, FALSE);
6b1e1a2c 322
323 if ($dao->N) {
6b1e1a2c 324 while ($dao->fetch()) {
325 $onBehalfParams['on_behalf'] = array('is_for_organization' => $dao->is_for_organization);
326 if ($domain->locales) {
6b1e1a2c 327 foreach ($locales as $locale) {
328 $for_organization = "for_organization_{$locale}";
329 $onBehalfParams['on_behalf'] += array(
330 $locale => array(
331 'for_organization' => $dao->$for_organization,
332 ),
333 );
334 }
335 }
336 else {
337 $onBehalfParams['on_behalf'] += array(
338 'default' => array(
339 'for_organization' => $dao->for_organization,
340 ),
341 );
342 }
343 $ufJoinParam = array(
344 'id' => $dao->join_id,
345 'module' => 'on_behalf',
d3e92c88 346 'uf_group_id' => $dao->uf_group_id,
6b1e1a2c 347 'module_data' => json_encode($onBehalfParams),
348 );
349 CRM_Core_BAO_UFJoin::create($ufJoinParam);
350 }
351 }
352
353 return TRUE;
354 }
cb804cd9 355
b2222b9f
CW
356 /**
357 * CRM-11782 - Get rid of VALUE_SEPARATOR character in saved search form values
358 *
359 * @param \CRM_Queue_TaskContext $ctx
360 *
361 * @return bool
362 */
363 public function fixContactTypeInSmartGroups(CRM_Queue_TaskContext $ctx) {
364 $sep = CRM_Core_DAO::VALUE_SEPARATOR;
365 $dao = CRM_Core_DAO::executeQuery("SELECT id, form_values FROM civicrm_saved_search WHERE form_values LIKE '%$sep%'");
366 while ($dao->fetch()) {
367 $formValues = unserialize($dao->form_values);
368 if (isset($formValues['contact_type']) && is_array($formValues['contact_type'])) {
369 $newVals = array();
370 foreach ($formValues['contact_type'] as $key => $val) {
371 $newVals[str_replace($sep, '__', $key)] = is_string($val) ? str_replace($sep, '__', $val) : $val;
372 }
373 $formValues['contact_type'] = $newVals;
374 }
375 CRM_Core_DAO::executeQuery("UPDATE civicrm_saved_search SET form_values = %1 WHERE id = {$dao->id}", array(1 => array(serialize($formValues), 'String')));
376 }
377
378 return TRUE;
379 }
380
0094ac08
CW
381 /**
382 * CRM-17637 - Ths file location has been moved; delete the old one
383 *
384 * @param \CRM_Queue_TaskContext $ctx
385 *
386 * @return bool
387 */
388 public function deleteVersionCheckCacheFile(CRM_Queue_TaskContext $ctx) {
389 $config = CRM_Core_Config::singleton();
390 $cacheFile = $config->uploadDir . 'version-info-cache.json';
391 if (file_exists($cacheFile)) {
392 unlink($cacheFile);
393 }
394 return TRUE;
395 }
396
fb1f3850
DRJ
397 /**
398 * CRM-17669 and CRM-17686, make scheduled jobs more flexible, disable the 4.6 extension if installed
399 *
400 * @param \CRM_Queue_TaskContext $ctx
401 *
402 * @return bool
403 */
404 public function disableFlexibleJobsExtension(CRM_Queue_TaskContext $ctx) {
d357221c
DRJ
405 try {
406 civicrm_api3('Extension', 'disable', array('key' => 'com.klangsoft.flexiblejobs'));
407 }
408 catch (CiviCRM_API3_Exception $e) {
409 // just ignore if the extension isn't installed
410 }
fb1f3850
DRJ
411
412 return TRUE;
413 }
414
20d5377e 415 /**
416 * CRM-17752 add index to civicrm_financial_trxn.trxn_id (deliberately non-unique).
417 *
418 * @param \CRM_Queue_TaskContext $ctx
419 *
420 * @return bool
421 */
422 public function addIndexFinancialTrxnTrxnID(CRM_Queue_TaskContext $ctx) {
423 $tables = array('civicrm_financial_trxn' => array('trxn_id'));
424 CRM_Core_BAO_SchemaHandler::createIndexes($tables);
425 return TRUE;
426 }
427
8ca47f5c 428 /**
429 * CRM-17882 Add index to civicrm_contribution.credit_note_id.
430 *
431 * @param \CRM_Queue_TaskContext $ctx
432 *
433 * @return bool
434 */
435 public function addIndexContributionCreditNoteID(CRM_Queue_TaskContext $ctx) {
436 $tables = array('civicrm_contribution' => array('creditnote_id'));
437 CRM_Core_BAO_SchemaHandler::createIndexes($tables);
438 return TRUE;
439 }
440
2179c899 441 /**
442 * CRM-17775 Add correct index for table civicrm_financial_item.
443 *
444 * Note that the entity ID should always precede the entity_table as
445 * it is more unique. This is better for performance and does not cause fallback
446 * to no index if table it omitted.
447 *
448 * @return bool
449 */
450 public function addCombinedIndexFinancialItemEntityIDEntityType() {
451 CRM_Core_BAO_SchemaHandler::dropIndexIfExists('civicrm_financial_item', 'UI_id');
452 CRM_Core_BAO_SchemaHandler::dropIndexIfExists('civicrm_financial_item', 'IX_Entity');
453 CRM_Core_BAO_SchemaHandler::createIndexes(array(
454 'civicrm_financial_item' => array(array('entity_id', 'entity_table')),
455 ));
456 return TRUE;
457 }
458
1f395432 459 /**
460 * CRM-17951 Add accounts option values for refund and chargeback.
461 *
462 * Add Chargeback contribution status and Chargeback and Contra account relationships,
463 * checking first if one exists.
464 */
465 public function addRefundAndChargeBackAccountsIfNotExist() {
466 // First we enable and edit the record for Credit contra - this exists but is disabled for most sites.
467 // Using the ensure function (below) will not enabled a disabled option (by design).
468 CRM_Core_DAO::executeQuery("UPDATE civicrm_option_value v
469 INNER JOIN civicrm_option_group g on v.option_group_id=g.id and g.name='account_relationship'
470 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'
471 WHERE v.name = 'Credit/Contra Account is';");
472
473 CRM_Core_BAO_OptionValue::ensureOptionValueExists(array(
474 'option_group_id' => 'account_relationship',
4a907feb
EM
475 'name' => 'Chargeback Account is',
476 'label' => ts('Chargeback Account is'),
1f395432 477 'is_active' => TRUE,
478 'component_id' => 'CiviContribute',
479 ));
480
481 CRM_Core_BAO_OptionValue::ensureOptionValueExists(array(
482 'option_group_id' => 'contribution_status',
483 'name' => 'Chargeback',
484 'label' => ts('Chargeback'),
485 'is_active' => TRUE,
486 'component_id' => 'CiviContribute',
487 ));
488 return TRUE;
489 }
490
3fe26f4c 491 /**
492 * CRM-17999 Add index to civicrm_contribution.source.
493 *
494 * @param \CRM_Queue_TaskContext $ctx
495 *
496 * @return bool
497 */
498 public function addIndexContributionSource(CRM_Queue_TaskContext $ctx) {
499 CRM_Core_BAO_SchemaHandler::createIndexes(array('civicrm_contribution' => array('source')));
500 return TRUE;
501 }
502
6cc25669 503}