Merge pull request #2897 from pradpnayak/CRM-14191
[civicrm-core.git] / CRM / Upgrade / Incremental / php / FourFour.php
CommitLineData
a47a2f90 1<?php
2/*
3 +--------------------------------------------------------------------+
232624b1 4 | CiviCRM version 4.4 |
a47a2f90 5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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 *
29 * @package CRM
30 * @copyright CiviCRM LLC (c) 2004-2013
31 * $Id$
32 *
33 */
34class CRM_Upgrade_Incremental_php_FourFour {
35 const BATCH_SIZE = 5000;
36
52592398
TO
37 const MAX_WORD_REPLACEMENT_SIZE = 255;
38
a47a2f90 39 function verifyPreDBstate(&$errors) {
40 return TRUE;
41 }
42
43 /**
44 * Compute any messages which should be displayed beforeupgrade
45 *
46 * Note: This function is called iteratively for each upcoming
47 * revision to the database.
48 *
49 * @param $postUpgradeMessage string, alterable
50 * @param $rev string, a version number, e.g. '4.4.alpha1', '4.4.beta3', '4.4.0'
51 * @return void
52 */
53 function setPreUpgradeMessage(&$preUpgradeMessage, $rev, $currentVer = NULL) {
52592398
TO
54 if ($rev == '4.4.beta1') {
55 $apiCalls = self::getConfigArraysAsAPIParams(FALSE);
56 $oversizedEntries = 0;
57 foreach ($apiCalls as $params) {
58 if (!self::isValidWordReplacement($params)) {
59 $oversizedEntries++;
60 }
61 }
62 if ($oversizedEntries > 0) {
63 $preUpgradeMessage .= '<br/>' . ts("WARNING: There are %1 word-replacement entries which will not be valid in v4.4+ (eg with over 255 characters). They will be dropped during upgrade. For details, consult the CiviCRM log.", array(
64 1 => $oversizedEntries
65 ));
66 }
67 }
a47a2f90 68 }
69
70 /**
71 * Compute any messages which should be displayed after upgrade
72 *
73 * @param $postUpgradeMessage string, alterable
74 * @param $rev string, an intermediate version; note that setPostUpgradeMessage is called repeatedly with different $revs
75 * @return void
76 */
77 function setPostUpgradeMessage(&$postUpgradeMessage, $rev) {
61320313 78 if ($rev == '4.4.1') {
634e1a1a
DL
79 $config = CRM_Core_Config::singleton();
80 if (!empty($config->useIDS)) {
61320313 81 $postUpgradeMessage .= '<br />' . ts("The setting to skip IDS check has been removed. Your site has this configured in civicrm.settings.php but it will no longer work. Instead, use the new permission 'skip IDS check' to bypass the IDS system.");
634e1a1a
DL
82 }
83 }
9e58e6ff 84 if ($rev == '4.4.3') {
09163e8a 85 $postUpgradeMessage .= '<br /><br />' . ts('Default versions of the following System Workflow Message Templates have been modified to handle new functionality: <ul><li>Events - Registration Confirmation and Receipt (on-line)</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).');
9e58e6ff 86 }
1543f800
DG
87 if ($rev == '4.4.3') {
88 $query = "SELECT cft.id financial_trxn
89FROM civicrm_financial_trxn cft
90LEFT JOIN civicrm_entity_financial_trxn ceft ON ceft.financial_trxn_id = cft.id
91LEFT JOIN civicrm_contribution cc ON ceft.entity_id = cc.id
92WHERE ceft.entity_table = 'civicrm_contribution' AND cft.payment_instrument_id IS NULL;";
93 $dao = CRM_Core_DAO::executeQuery($query);
94 if ($dao->N) {
95 $postUpgradeMessage .= '<br /><br /><strong>' . ts('Your database contains %1 financial transaction records with no payment instrument (Paid By is empty). If you use the Accounting Batches feature this may result in unbalanced transactions. If you do not use this feature, you can ignore the condition (although you will be required to select a Paid By value for new transactions). <a href="%2" target="_blank">You can review steps to correct transactions with missing payment instruments on the wiki.</a>', array(1 => $dao->N, 2 => 'http://wiki.civicrm.org/confluence/display/CRMDOC/Fixing+Transactions+Missing+a+Payment+Instrument+-+4.4.3+Upgrades')) . '</strong>';
96 }
97 }
a47a2f90 98 }
99
100 function upgrade_4_4_alpha1($rev) {
634e1a1a 101 // task to process sql
d1401e86 102 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.4.alpha1')), 'task_4_4_x_runSql', $rev);
a47a2f90 103
104 // Consolidate activity contacts CRM-12274.
d1401e86 105 $this->addTask('Consolidate activity contacts', 'activityContacts');
a47a2f90 106
107 return TRUE;
108 }
109
7ee2786a 110 function upgrade_4_4_beta1($rev) {
d1401e86 111 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.4.beta1')), 'task_4_4_x_runSql', $rev);
7ee2786a 112
56d4e0ab 113 // add new 'data' column in civicrm_batch
114 $query = 'ALTER TABLE civicrm_batch ADD data LONGTEXT NULL COMMENT "cache entered data"';
d427e40e 115 CRM_Core_DAO::executeQuery($query, array(), TRUE, NULL, FALSE, FALSE);
56d4e0ab 116
7ee2786a 117 // check if batch entry data exists in civicrm_cache table
f1811020 118 $query = 'SELECT path, data FROM civicrm_cache WHERE group_name = "batch entry"';
7ee2786a 119 $dao = CRM_Core_DAO::executeQuery($query);
120 while ($dao->fetch()) {
121 // get batch id $batchId[2]
122 $batchId = explode('-', $dao->path);
123 $data = unserialize($dao->data);
124
125 // move the data to civicrm_batch table
126 CRM_Core_DAO::setFieldValue('CRM_Batch_DAO_Batch', $batchId[2], 'data', json_encode(array('values' => $data)));
127 }
128
129 // delete entries from civicrm_cache table
f1811020 130 $query = 'DELETE FROM civicrm_cache WHERE group_name = "batch entry"';
7ee2786a 131 CRM_Core_DAO::executeQuery($query);
ba457d64 132
d1401e86 133 $this->addTask('Migrate custom word-replacements', 'wordReplacements');
7ee2786a 134 }
135
6b12405a 136 function upgrade_4_4_1($rev) {
95c0a77c 137 $config = CRM_Core_Config::singleton();
6b12405a
RN
138 // CRM-13327 upgrade handling for the newly added name badges
139 $ogID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'name_badge', 'id', 'name');
140 $nameBadges = array_flip(array_values(CRM_Core_BAO_OptionValue::getOptionValuesAssocArrayFromName('name_badge')));
141 unset($nameBadges['Avery 5395']);
142 if (!empty($nameBadges)) {
143 $dimension = '{"paper-size":"a4","orientation":"portrait","font-name":"times","font-size":6,"font-style":"","NX":2,"NY":4,"metric":"mm","lMargin":6,"tMargin":19,"SpaceX":0,"SpaceY":0,"width":100,"height":65,"lPadding":0,"tPadding":0}';
144 $query = "UPDATE civicrm_option_value
145 SET value = '{$dimension}'
146 WHERE option_group_id = %1 AND name = 'Fattorini Name Badge 100x65'";
147
148 CRM_Core_DAO::executeQuery($query, array(1 => array($ogID, 'Integer')));
149 }
150 else {
151 $dimensions = array(
152 1 => '{"paper-size":"a4","orientation":"landscape","font-name":"times","font-size":6,"font-style":"","NX":2,"NY":1,"metric":"mm","lMargin":25,"tMargin":27,"SpaceX":0,"SpaceY":35,"width":106,"height":150,"lPadding":5,"tPadding":5}',
153 2 => '{"paper-size":"a4","orientation":"portrait","font-name":"times","font-size":6,"font-style":"","NX":2,"NY":4,"metric":"mm","lMargin":6,"tMargin":19,"SpaceX":0,"SpaceY":0,"width":100,"height":65,"lPadding":0,"tPadding":0}',
154 3 => '{"paper-size":"a4","orientation":"portrait","font-name":"times","font-size":6,"font-style":"","NX":2,"NY":2,"metric":"mm","lMargin":10,"tMargin":28,"SpaceX":0,"SpaceY":0,"width":96,"height":121,"lPadding":5,"tPadding":5}',
155 );
156 $insertStatements = array(
157 1 => "($ogID, %1, '{$dimensions[1]}', %1, NULL, 0, NULL, 2, NULL, 0, 0, 1, NULL, NULL)",
158 2 => "($ogID, %2, '{$dimensions[2]}', %2, NULL, 0, NULL, 3, NULL, 0, 0, 1, NULL, NULL)",
159 3 => "($ogID, %3, '{$dimensions[3]}', %3, NULL, 0, NULL, 4, NULL, 0, 0, 1, NULL, NULL)",
160 );
161
162 $queryParams = array(
163 1 => array('A6 Badge Portrait 150x106', 'String'),
164 2 => array('Fattorini Name Badge 100x65', 'String'),
165 3 => array('Hanging Badge 3-3/4" x 4-3"/4', 'String'),
166 );
3a88e331 167
6b12405a
RN
168 foreach ($insertStatements as $values) {
169 $query = 'INSERT INTO civicrm_option_value (`option_group_id`, `label`, `value`, `name`, `grouping`, `filter`, `is_default`, `weight`, `description`, `is_optgroup`, `is_reserved`, `is_active`, `component_id`, `visibility_id`) VALUES' . $values;
170 CRM_Core_DAO::executeQuery($query, $queryParams);
171 }
172 }
173
95c0a77c
CW
174 // CRM-12578 - Prior to this version a CSS file under drupal would disable core css
175 if (!empty($config->customCSSURL) && strpos($config->userFramework, 'Drupal') === 0) {
176 // The new setting doesn't exist yet - need to create it first
177 CRM_Core_BAO_Setting::updateSettingsFromMetaData();
178 CRM_Core_BAO_Setting::setItem('1', CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'disable_core_css');
179 }
180
fcab62b4
CW
181 // CRM-13701 - Fix $config->timeInputFormat
182 $sql = "
183 SELECT time_format
184 FROM civicrm_preferences_date
185 WHERE time_format IS NOT NULL
186 AND time_format <> ''
187 LIMIT 1
188 ";
189 $timeInputFormat = CRM_Core_DAO::singleValueQuery($sql);
190 if ($timeInputFormat && $timeInputFormat != $config->timeInputFormat) {
191 $params = array('timeInputFormat' => $timeInputFormat);
192 CRM_Core_BAO_ConfigSetting::add($params);
193 }
194
187e382a
PJ
195 // CRM-13698 - add 'Available' and 'No-show' activity statuses
196 $insertStatus = array();
197 $nsinc = $avinc = $inc = 0;
198 if (!CRM_Core_OptionGroup::getValue('activity_status', 'Available', 'name')) {
199 $insertStatus[] = "(%1, 'Available', %2, 'Available', NULL, 0, NULL, %3, 0, 0, 1, NULL, NULL)";
200 $avinc = $inc = 1;
201 }
5b8e40ab
CW
202 if (!CRM_Core_OptionGroup::getValue('activity_status', 'No_show', 'name')) {
203 $insertStatus[] = "(%1, 'No-show', %4, 'No_show', NULL, 0, NULL, %5, 0, 0, 1, NULL, NULL)";
187e382a
PJ
204 $nsinc = $inc + 1;
205 }
206 if (!empty($insertStatus)) {
207 $acOptionGroupID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'activity_status', 'id', 'name');
208 $maxVal = CRM_Core_DAO::singleValueQuery("SELECT MAX(ROUND(op.value)) FROM civicrm_option_value op WHERE op.option_group_id = $acOptionGroupID");
209 $maxWeight = CRM_Core_DAO::singleValueQuery("SELECT MAX(weight) FROM civicrm_option_value WHERE option_group_id = $acOptionGroupID");
210
211 $p[1] = array($acOptionGroupID, 'Integer');
212 if ($avinc) {
213 $p[2] = array($avinc+$maxVal, 'Integer');
214 $p[3] = array($avinc+$maxWeight, 'Integer');
215 }
216 if ($nsinc) {
217 $p[4] = array($nsinc+$maxVal, 'Integer');
218 $p[5] = array($nsinc+$maxWeight, 'Integer');
219 }
220 $insertStatus = implode(',', $insertStatus);
221
222 $sql = "
223INSERT INTO
224 civicrm_option_value (`option_group_id`, label, `value`, `name`, `grouping`, `filter`, `is_default`, `weight`, `is_optgroup`, `is_reserved`, `is_active`, `component_id`, `visibility_id`)
225VALUES {$insertStatus}";
226 CRM_Core_DAO::executeQuery($sql, $p);
227 }
228
6b12405a 229 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.4.1')), 'task_4_4_x_runSql', $rev);
44379fac 230 $this->addTask('Patch word-replacement schema', 'wordReplacements_patch', $rev);
6b12405a
RN
231 }
232
fa4916a4 233 function upgrade_4_4_4($rev) {
23e300df
PJ
234 $fkConstraint = array();
235 if (!CRM_Core_DAO::checkFKConstraintInFormat('civicrm_activity_contact', 'activity_id')) {
236 $fkConstraint[] = "ADD CONSTRAINT `FK_civicrm_activity_contact_activity_id` FOREIGN KEY (`activity_id`) REFERENCES `civicrm_activity` (`id`) ON DELETE CASCADE";
237 }
238 if (!CRM_Core_DAO::checkFKConstraintInFormat('civicrm_activity_contact', 'contact_id')) {
239 $fkConstraint[] = "ADD CONSTRAINT `FK_civicrm_activity_contact_contact_id` FOREIGN KEY (`contact_id`) REFERENCES `civicrm_contact` (`id`) ON DELETE CASCADE;
240";
241 }
242
243 if (!empty($fkConstraint)) {
244 $fkConstraint = implode(',', $fkConstraint);
245 $sql = "ALTER TABLE `civicrm_activity_contact`
246{$fkConstraint}
247";
248 // CRM-14036 : delete entries of un-mapped contacts
249 CRM_Core_DAO::executeQuery("DELETE ac FROM civicrm_activity_contact ac
250LEFT JOIN civicrm_contact c
251ON c.id = ac.contact_id
252WHERE c.id IS NULL;
253");
254 // delete entries of un-mapped activities
255 CRM_Core_DAO::executeQuery("DELETE ac FROM civicrm_activity_contact ac
256LEFT JOIN civicrm_activity a
257ON a.id = ac.activity_id
258WHERE a.id IS NULL;
259");
260
261 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS=0;");
262 CRM_Core_DAO::executeQuery($sql);
263 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS=1;");
264 }
265
fa4916a4 266 // task to process sql
267 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.4.4')), 'task_4_4_x_runSql', $rev);
268
7bfaef22 269 // CRM-13892 : add `name` column to dashboard schema
fa4916a4 270 $query = "
271ALTER TABLE civicrm_dashboard
272 ADD name varchar(64) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Internal name of dashlet.' AFTER domain_id ";
9359d28c 273 CRM_Core_DAO::executeQuery($query, array(), TRUE, NULL, FALSE, FALSE);
fa4916a4 274
275 $dashboard = new CRM_Core_DAO_Dashboard();
276 $dashboard->find();
277 while ($dashboard->fetch()) {
278 $urlElements = explode('/', $dashboard->url);
279 if ($urlElements[1] == 'dashlet') {
280 $url = explode('&', $urlElements[2]);
281 $name = $url[0];
282 }
283 elseif ($urlElements[1] == 'report') {
284 $url = explode('&', $urlElements[3]);
285 $name = 'report/' .$url[0];
286 }
287 $values .= "
288 WHEN {$dashboard->id} THEN '{$name}'
289 ";
290 }
291
292 $query = "
293 UPDATE civicrm_dashboard
294 SET name = CASE id
295 {$values}
296 END;
297 ";
9359d28c 298 CRM_Core_DAO::executeQuery($query, array(), TRUE, NULL, FALSE, FALSE);
52df1bbd
DG
299
300 // CRM-13998 : missing alter statements for civicrm_report_instance
301 $this->addTask(ts('Confirm civicrm_report_instance sql table for upgrades'), 'updateReportInstanceTable');
302
fa4916a4 303
f15ec728 304 return TRUE;
fa4916a4 305 }
306
a47a2f90 307 /**
308 * Update activity contacts CRM-12274
309 *
310 * @return bool TRUE for success
311 */
312 static function activityContacts(CRM_Queue_TaskContext $ctx) {
313 $upgrade = new CRM_Upgrade_Form();
127ca309 314
e7e657f0 315 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
b95507ab 316 $ovValue[] = $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
317 $ovValue[] = $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
318 $ovValue[] = $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
634e1a1a 319
9744c42c 320 $optionGroupID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'activity_contacts', 'id', 'name');
b95507ab 321 if (!empty($ovValue)) {
322 $ovValues = implode(', ', $ovValue);
323 $query = "
634e1a1a 324UPDATE civicrm_option_value
b95507ab 325SET is_reserved = 1
326WHERE option_group_id = {$optionGroupID} AND value IN ($ovValues)";
327
328 $dao = CRM_Core_DAO::executeQuery($query);
329 }
330
9744c42c 331 if (!$assigneeID) {
b95507ab 332 $assigneeID = 1;
9744c42c 333 $value[] = "({$optionGroupID}, 'Activity Assignees', 1, 'Activity Assignees', 1, 1, 1)";
334 }
335 if (!$sourceID) {
b95507ab 336 $sourceID = 2;
9744c42c 337 $value[] = "({$optionGroupID}, 'Activity Source', 2, 'Activity Source', 2, 1, 1)";
338 }
339 if (!$targetID) {
b95507ab 340 $targetID = 3;
9744c42c 341 $value[] = "({$optionGroupID}, 'Activity Targets', 3, 'Activity Targets', 3, 1, 1)";
342 }
343
344 if (!$assigneeID || !$sourceID || !$targetID ) {
634e1a1a 345 $insert = "
9744c42c 346INSERT INTO civicrm_option_value
347(option_group_id, label, value, name, weight, is_reserved, is_active)
348VALUES
349
350";
351 $values = implode(', ', $value);
352 $query = $insert . $values;
353 $dao = CRM_Core_DAO::executeQuery($query);
354 }
355
3a88e331
DL
356 // sometimes an user does not make a clean backup and the above table
357 // already exists, so lets delete this table - CRM-13665
187e382a 358 $query = "DROP TABLE IF EXISTS civicrm_activity_contact";
3a88e331 359 $dao = CRM_Core_DAO::executeQuery($query);
9744c42c 360
a47a2f90 361 $query = "
127ca309 362CREATE TABLE IF NOT EXISTS civicrm_activity_contact (
363 id int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Activity contact id',
364 activity_id int(10) unsigned NOT NULL COMMENT 'Foreign key to the activity for this record.',
365 contact_id int(10) unsigned NOT NULL COMMENT 'Foreign key to the contact for this record.',
366 record_type_id int(10) unsigned DEFAULT NULL COMMENT 'The record type id for this row',
367 PRIMARY KEY (id),
368 UNIQUE KEY UI_activity_contact (contact_id,activity_id,record_type_id),
369 KEY FK_civicrm_activity_contact_activity_id (activity_id)
a47a2f90 370) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
371";
372
373 $dao = CRM_Core_DAO::executeQuery($query);
634e1a1a 374
3a88e331 375
634e1a1a 376 $query = "
127ca309 377INSERT INTO civicrm_activity_contact (activity_id, contact_id, record_type_id)
378SELECT activity_id, target_contact_id, {$targetID} as record_type_id
a47a2f90 379FROM civicrm_activity_target";
380
381 $dao = CRM_Core_DAO::executeQuery($query);
382
634e1a1a 383 $query = "
127ca309 384INSERT INTO civicrm_activity_contact (activity_id, contact_id, record_type_id)
385SELECT activity_id, assignee_contact_id, {$assigneeID} as record_type_id
a47a2f90 386FROM civicrm_activity_assignment";
387 $dao = CRM_Core_DAO::executeQuery($query);
634e1a1a 388
a47a2f90 389 $query = "
127ca309 390 INSERT INTO civicrm_activity_contact (activity_id, contact_id, record_type_id)
391SELECT id, source_contact_id, {$sourceID} as record_type_id
634e1a1a 392FROM civicrm_activity
a47a2f90 393WHERE source_contact_id IS NOT NULL";
394
395 $dao = CRM_Core_DAO::executeQuery($query);
396
397 $query = "DROP TABLE civicrm_activity_target";
398 $dao = CRM_Core_DAO::executeQuery($query);
399
400 $query = "DROP TABLE civicrm_activity_assignment";
401 $dao = CRM_Core_DAO::executeQuery($query);
402
634e1a1a 403 $query = "ALTER TABLE civicrm_activity
a47a2f90 404 DROP FOREIGN KEY FK_civicrm_activity_source_contact_id";
634e1a1a 405
a47a2f90 406 $dao = CRM_Core_DAO::executeQuery($query);
407
408 $query = "ALTER TABLE civicrm_activity DROP COLUMN source_contact_id";
409 $dao = CRM_Core_DAO::executeQuery($query);
410
ba457d64
TO
411 return TRUE;
412 }
413
414 /**
415 * Migrate word-replacements from $config to civicrm_word_replacement
416 *
417 * @return bool TRUE for success
418 * @see http://issues.civicrm.org/jira/browse/CRM-13187
419 */
420 static function wordReplacements(CRM_Queue_TaskContext $ctx) {
421 $query = "
7c312eca
TO
422CREATE TABLE IF NOT EXISTS `civicrm_word_replacement` (
423 `id` int unsigned NOT NULL AUTO_INCREMENT COMMENT 'Word replacement ID',
02ffc0f2
TO
424 `find_word` varchar(255) COLLATE utf8_bin COMMENT 'Word which need to be replaced',
425 `replace_word` varchar(255) COLLATE utf8_bin COMMENT 'Word which will replace the word in find',
7c312eca
TO
426 `is_active` tinyint COMMENT 'Is this entry active?',
427 `match_type` enum('wildcardMatch', 'exactMatch') DEFAULT 'wildcardMatch',
428 `domain_id` int unsigned COMMENT 'FK to Domain ID. This is for Domain specific word replacement',
429 PRIMARY KEY ( `id` ),
44379fac 430 UNIQUE INDEX `UI_domain_find` (domain_id, find_word),
7c312eca
TO
431 CONSTRAINT FK_civicrm_word_replacement_domain_id FOREIGN KEY (`domain_id`) REFERENCES `civicrm_domain`(`id`)
432) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
433 ";
ba457d64
TO
434 $dao = CRM_Core_DAO::executeQuery($query);
435
daa14c0c 436 self::rebuildWordReplacementTable();
ba457d64 437 return TRUE;
a47a2f90 438 }
439
44379fac
TO
440 /**
441 * Fix misconfigured constraints created in 4.4.0. To distinguish the good
442 * and bad configurations, we change the constraint name from "UI_find"
443 * (the original name in 4.4.0) to "UI_domain_find" (the new name in
444 * 4.4.1).
445 *
446 * @return bool TRUE for success
447 * @see http://issues.civicrm.org/jira/browse/CRM-13655
448 */
449 static function wordReplacements_patch(CRM_Queue_TaskContext $ctx, $rev) {
450 if (CRM_Core_DAO::checkConstraintExists('civicrm_word_replacement', 'UI_find')) {
451 CRM_Core_DAO::executeQuery("ALTER TABLE civicrm_word_replacement DROP FOREIGN KEY FK_civicrm_word_replacement_domain_id;");
452 CRM_Core_DAO::executeQuery("ALTER TABLE civicrm_word_replacement DROP KEY FK_civicrm_word_replacement_domain_id;");
453 CRM_Core_DAO::executeQuery("ALTER TABLE civicrm_word_replacement DROP KEY UI_find;");
454 CRM_Core_DAO::executeQuery("ALTER TABLE civicrm_word_replacement MODIFY COLUMN `find_word` varchar(255) COLLATE utf8_bin DEFAULT NULL COMMENT 'Word which need to be replaced';");
455 CRM_Core_DAO::executeQuery("ALTER TABLE civicrm_word_replacement MODIFY COLUMN `replace_word` varchar(255) COLLATE utf8_bin DEFAULT NULL COMMENT 'Word which will replace the word in find';");
456 CRM_Core_DAO::executeQuery("ALTER TABLE civicrm_word_replacement ADD CONSTRAINT UI_domain_find UNIQUE KEY `UI_domain_find` (`domain_id`,`find_word`);");
457 CRM_Core_DAO::executeQuery("ALTER TABLE civicrm_word_replacement ADD CONSTRAINT FK_civicrm_word_replacement_domain_id FOREIGN KEY (`domain_id`) REFERENCES `civicrm_domain` (`id`);");
458 }
459 return TRUE;
460 }
461
a47a2f90 462 /**
463 * (Queue Task Callback)
464 */
465 static function task_4_4_x_runSql(CRM_Queue_TaskContext $ctx, $rev) {
466 $upgrade = new CRM_Upgrade_Form();
467 $upgrade->processSQL($rev);
468
469 return TRUE;
470 }
471
472 /**
473 * Syntatic sugar for adding a task which (a) is in this class and (b) has
474 * a high priority.
475 *
476 * After passing the $funcName, you can also pass parameters that will go to
477 * the function. Note that all params must be serializable.
478 */
479 protected function addTask($title, $funcName) {
480 $queue = CRM_Queue_Service::singleton()->load(array(
481 'type' => 'Sql',
482 'name' => CRM_Upgrade_Form::QUEUE_NAME,
483 ));
484
485 $args = func_get_args();
486 $title = array_shift($args);
487 $funcName = array_shift($args);
488 $task = new CRM_Queue_Task(
489 array(get_class($this), $funcName),
490 $args,
491 $title
492 );
493 $queue->createItem($task, array('weight' => -1));
494 }
cbe56ea6
TO
495
496 /**
daa14c0c
TO
497 * Get all the word-replacements stored in config-arrays
498 * and convert them to params for the WordReplacement.create API.
499 *
0f65e834
TO
500 * Note: This function is duplicated in CRM_Core_BAO_WordReplacement and
501 * CRM_Upgrade_Incremental_php_FourFour to ensure that the incremental upgrade
502 * step behaves consistently even as the BAO evolves in future versions.
503 * However, if there's a bug in here prior to 4.4.0, we should apply the
504 * bugfix in both places.
505 *
63b71ea8 506 * @param bool $rebuildEach whether to perform rebuild after each individual API call
daa14c0c
TO
507 * @return array Each item is $params for WordReplacement.create
508 * @see CRM_Core_BAO_WordReplacement::convertConfigArraysToAPIParams
cbe56ea6 509 */
63b71ea8 510 static function getConfigArraysAsAPIParams($rebuildEach) {
cbe56ea6 511 $wordReplacementCreateParams = array();
cbe56ea6 512 // get all domains
daa14c0c
TO
513 $result = civicrm_api3('domain', 'get', array(
514 'return' => array('locale_custom_strings'),
515 ));
cbe56ea6
TO
516 if (!empty($result["values"])) {
517 foreach ($result["values"] as $value) {
518 $params = array();
cbe56ea6 519 $params["domain_id"] = $value["id"];
63b71ea8 520 $params["options"] = array('wp-rebuild' => $rebuildEach);
cbe56ea6
TO
521 // unserialize word match string
522 $localeCustomArray = unserialize($value["locale_custom_strings"]);
523 if (!empty($localeCustomArray)) {
524 $wordMatchArray = array();
7c312eca 525 // Traverse Language array
cbe56ea6 526 foreach ($localeCustomArray as $localCustomData) {
7c312eca
TO
527 // Traverse status array "enabled" "disabled"
528 foreach ($localCustomData as $status => $matchTypes) {
529 $params["is_active"] = ($status == "enabled")?TRUE:FALSE;
530 // Traverse Match Type array "wildcardMatch" "exactMatch"
531 foreach ($matchTypes as $matchType => $words) {
532 $params["match_type"] = $matchType;
533 foreach ($words as $word => $replace) {
534 $params["find_word"] = $word;
535 $params["replace_word"] = $replace;
536 $wordReplacementCreateParams[] = $params;
537 }
538 }
cbe56ea6
TO
539 }
540 }
541 }
542 }
543 }
544 return $wordReplacementCreateParams;
8d57c529 545 }
ba457d64 546
daa14c0c
TO
547 /**
548 * Get all the word-replacements stored in config-arrays
549 * and write them out as records in civicrm_word_replacement.
0f65e834
TO
550 *
551 * Note: This function is duplicated in CRM_Core_BAO_WordReplacement and
552 * CRM_Upgrade_Incremental_php_FourFour to ensure that the incremental upgrade
553 * step behaves consistently even as the BAO evolves in future versions.
554 * However, if there's a bug in here prior to 4.4.0, we should apply the
555 * bugfix in both places.
daa14c0c
TO
556 */
557 public static function rebuildWordReplacementTable() {
558 civicrm_api3('word_replacement', 'replace', array(
559 'options' => array('match' => array('domain_id', 'find_word')),
52592398 560 'values' => array_filter(self::getConfigArraysAsAPIParams(FALSE), array(__CLASS__, 'isValidWordReplacement')),
daa14c0c
TO
561 ));
562 CRM_Core_BAO_WordReplacement::rebuild();
ba457d64 563 }
52df1bbd
DG
564
565
566 /***
567 * CRM-13998 missing alter statements for civicrm_report_instance
568 ***/
569 public function updateReportInstanceTable() {
570
571 // add civicrm_report_instance.name
572
573 $sql = "SELECT count(*) FROM information_schema.columns "
574 . "WHERE table_schema = database() AND table_name = 'civicrm_report_instance' AND COLUMN_NAME = 'name' ";
575
576 $res = CRM_Core_DAO::singleValueQuery($sql);
577
578 if ($res <= 0 ) {
579 $sql = "ALTER TABLE civicrm_report_instance ADD `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'when combined with report_id/template uniquely identifies the instance'";
580 $res = CRM_Core_DAO::executeQuery($sql);
581 }
582
583 // add civicrm_report_instance args
584
585 $sql = "SELECT count(*) FROM information_schema.columns WHERE table_schema = database() AND table_name = 'civicrm_report_instance' AND COLUMN_NAME = 'args' ";
586
587 $res = CRM_Core_DAO::singleValueQuery($sql);
588
589 if ($res <= 0 ) {
590 $sql = "ALTER TABLE civicrm_report_instance ADD `args` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'arguments that are passed in the url when invoking the instance'";
591
592 $res = CRM_Core_DAO::executeQuery($sql);
593 }
594
595 return TRUE;
596 }
52592398
TO
597
598 /**
599 * @param array $params
600 * @return bool TRUE if $params is valid
601 */
602 static function isValidWordReplacement($params) {
603 $result = strlen($params['find_word']) <= self::MAX_WORD_REPLACEMENT_SIZE && strlen($params['replace_word']) > self::MAX_WORD_REPLACEMENT_SIZE;
604 if (!$result) {
605 CRM_Core_Error::debug_var('invalidWordReplacement', $params);
606 }
607 return $result;
608 }
a47a2f90 609}