Merge pull request #1754 from yashodha/CRM-13548
[civicrm-core.git] / CRM / Upgrade / Incremental / php / FourFour.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
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 */
34 class CRM_Upgrade_Incremental_php_FourFour {
35 const BATCH_SIZE = 5000;
36
37 function verifyPreDBstate(&$errors) {
38 return TRUE;
39 }
40
41 /**
42 * Compute any messages which should be displayed beforeupgrade
43 *
44 * Note: This function is called iteratively for each upcoming
45 * revision to the database.
46 *
47 * @param $postUpgradeMessage string, alterable
48 * @param $rev string, a version number, e.g. '4.4.alpha1', '4.4.beta3', '4.4.0'
49 * @return void
50 */
51 function setPreUpgradeMessage(&$preUpgradeMessage, $rev, $currentVer = NULL) {
52 }
53
54 /**
55 * Compute any messages which should be displayed after upgrade
56 *
57 * @param $postUpgradeMessage string, alterable
58 * @param $rev string, an intermediate version; note that setPostUpgradeMessage is called repeatedly with different $revs
59 * @return void
60 */
61 function setPostUpgradeMessage(&$postUpgradeMessage, $rev) {
62 if ($rev == '4.4.alpha1') {
63 $config = CRM_Core_Config::singleton();
64 if (!empty($config->useIDS)) {
65 $postUpgradeMessage .= '<br />' . ts("The setting to skip IDS check has been deprecated. Please use the permission 'skip IDS check' to bypass the IDS system.");
66 }
67 }
68 }
69
70 function upgrade_4_4_alpha1($rev) {
71 // task to process sql
72 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.4.alpha1')), 'task_4_4_x_runSql', $rev);
73
74 // Consolidate activity contacts CRM-12274.
75 $this->addTask('Consolidate activity contacts', 'activityContacts');
76
77 return TRUE;
78 }
79
80 function upgrade_4_4_beta1($rev) {
81 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.4.beta1')), 'task_4_4_x_runSql', $rev);
82
83 // add new 'data' column in civicrm_batch
84 $query = 'ALTER TABLE civicrm_batch ADD data LONGTEXT NULL COMMENT "cache entered data"';
85 CRM_Core_DAO::executeQuery($query);
86
87 // check if batch entry data exists in civicrm_cache table
88 $query = 'SELECT path, data FROM civicrm_cache WHERE group_name = "batch entry"';
89 $dao = CRM_Core_DAO::executeQuery($query);
90 while ($dao->fetch()) {
91 // get batch id $batchId[2]
92 $batchId = explode('-', $dao->path);
93 $data = unserialize($dao->data);
94
95 // move the data to civicrm_batch table
96 CRM_Core_DAO::setFieldValue('CRM_Batch_DAO_Batch', $batchId[2], 'data', json_encode(array('values' => $data)));
97 }
98
99 // delete entries from civicrm_cache table
100 $query = 'DELETE FROM civicrm_cache WHERE group_name = "batch entry"';
101 CRM_Core_DAO::executeQuery($query);
102
103 $this->addTask('Migrate custom word-replacements', 'wordReplacements');
104 }
105
106 /**
107 * Update activity contacts CRM-12274
108 *
109 * @return bool TRUE for success
110 */
111 static function activityContacts(CRM_Queue_TaskContext $ctx) {
112 $upgrade = new CRM_Upgrade_Form();
113
114 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
115 $ovValue[] = $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
116 $ovValue[] = $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
117 $ovValue[] = $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
118
119 $optionGroupID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'activity_contacts', 'id', 'name');
120 if (!empty($ovValue)) {
121 $ovValues = implode(', ', $ovValue);
122 $query = "
123 UPDATE civicrm_option_value
124 SET is_reserved = 1
125 WHERE option_group_id = {$optionGroupID} AND value IN ($ovValues)";
126
127 $dao = CRM_Core_DAO::executeQuery($query);
128 }
129
130 if (!$assigneeID) {
131 $assigneeID = 1;
132 $value[] = "({$optionGroupID}, 'Activity Assignees', 1, 'Activity Assignees', 1, 1, 1)";
133 }
134 if (!$sourceID) {
135 $sourceID = 2;
136 $value[] = "({$optionGroupID}, 'Activity Source', 2, 'Activity Source', 2, 1, 1)";
137 }
138 if (!$targetID) {
139 $targetID = 3;
140 $value[] = "({$optionGroupID}, 'Activity Targets', 3, 'Activity Targets', 3, 1, 1)";
141 }
142
143 if (!$assigneeID || !$sourceID || !$targetID ) {
144 $insert = "
145 INSERT INTO civicrm_option_value
146 (option_group_id, label, value, name, weight, is_reserved, is_active)
147 VALUES
148
149 ";
150 $values = implode(', ', $value);
151 $query = $insert . $values;
152 $dao = CRM_Core_DAO::executeQuery($query);
153 }
154
155
156 $query = "
157 CREATE TABLE IF NOT EXISTS civicrm_activity_contact (
158 id int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Activity contact id',
159 activity_id int(10) unsigned NOT NULL COMMENT 'Foreign key to the activity for this record.',
160 contact_id int(10) unsigned NOT NULL COMMENT 'Foreign key to the contact for this record.',
161 record_type_id int(10) unsigned DEFAULT NULL COMMENT 'The record type id for this row',
162 PRIMARY KEY (id),
163 UNIQUE KEY UI_activity_contact (contact_id,activity_id,record_type_id),
164 KEY FK_civicrm_activity_contact_activity_id (activity_id)
165 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
166 ";
167
168 $dao = CRM_Core_DAO::executeQuery($query);
169
170 $query = "
171 INSERT INTO civicrm_activity_contact (activity_id, contact_id, record_type_id)
172 SELECT activity_id, target_contact_id, {$targetID} as record_type_id
173 FROM civicrm_activity_target";
174
175 $dao = CRM_Core_DAO::executeQuery($query);
176
177 $query = "
178 INSERT INTO civicrm_activity_contact (activity_id, contact_id, record_type_id)
179 SELECT activity_id, assignee_contact_id, {$assigneeID} as record_type_id
180 FROM civicrm_activity_assignment";
181 $dao = CRM_Core_DAO::executeQuery($query);
182
183 $query = "
184 INSERT INTO civicrm_activity_contact (activity_id, contact_id, record_type_id)
185 SELECT id, source_contact_id, {$sourceID} as record_type_id
186 FROM civicrm_activity
187 WHERE source_contact_id IS NOT NULL";
188
189 $dao = CRM_Core_DAO::executeQuery($query);
190
191 $query = "DROP TABLE civicrm_activity_target";
192 $dao = CRM_Core_DAO::executeQuery($query);
193
194 $query = "DROP TABLE civicrm_activity_assignment";
195 $dao = CRM_Core_DAO::executeQuery($query);
196
197 $query = "ALTER TABLE civicrm_activity
198 DROP FOREIGN KEY FK_civicrm_activity_source_contact_id";
199
200 $dao = CRM_Core_DAO::executeQuery($query);
201
202 $query = "ALTER TABLE civicrm_activity DROP COLUMN source_contact_id";
203 $dao = CRM_Core_DAO::executeQuery($query);
204
205 return TRUE;
206 }
207
208 /**
209 * Migrate word-replacements from $config to civicrm_word_replacement
210 *
211 * @return bool TRUE for success
212 * @see http://issues.civicrm.org/jira/browse/CRM-13187
213 */
214 static function wordReplacements(CRM_Queue_TaskContext $ctx) {
215 $query = "
216 CREATE TABLE IF NOT EXISTS `civicrm_word_replacement` (
217 `id` int unsigned NOT NULL AUTO_INCREMENT COMMENT 'Word replacement ID',
218 `find_word` varchar(255) COMMENT 'Word which need to be replaced',
219 `replace_word` varchar(255) COMMENT 'Word which will replace the word in find',
220 `is_active` tinyint COMMENT 'Is this entry active?',
221 `match_type` enum('wildcardMatch', 'exactMatch') DEFAULT 'wildcardMatch',
222 `domain_id` int unsigned COMMENT 'FK to Domain ID. This is for Domain specific word replacement',
223 PRIMARY KEY ( `id` ),
224 UNIQUE INDEX `UI_find`(find_word),
225 CONSTRAINT FK_civicrm_word_replacement_domain_id FOREIGN KEY (`domain_id`) REFERENCES `civicrm_domain`(`id`)
226 ) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
227 ";
228 $dao = CRM_Core_DAO::executeQuery($query);
229
230 self::rebuildWordReplacementTable();
231 return TRUE;
232 }
233
234 /**
235 * (Queue Task Callback)
236 */
237 static function task_4_4_x_runSql(CRM_Queue_TaskContext $ctx, $rev) {
238 $upgrade = new CRM_Upgrade_Form();
239 $upgrade->processSQL($rev);
240
241 return TRUE;
242 }
243
244 /**
245 * Syntatic sugar for adding a task which (a) is in this class and (b) has
246 * a high priority.
247 *
248 * After passing the $funcName, you can also pass parameters that will go to
249 * the function. Note that all params must be serializable.
250 */
251 protected function addTask($title, $funcName) {
252 $queue = CRM_Queue_Service::singleton()->load(array(
253 'type' => 'Sql',
254 'name' => CRM_Upgrade_Form::QUEUE_NAME,
255 ));
256
257 $args = func_get_args();
258 $title = array_shift($args);
259 $funcName = array_shift($args);
260 $task = new CRM_Queue_Task(
261 array(get_class($this), $funcName),
262 $args,
263 $title
264 );
265 $queue->createItem($task, array('weight' => -1));
266 }
267
268 /**
269 * Get all the word-replacements stored in config-arrays
270 * and convert them to params for the WordReplacement.create API.
271 *
272 * Note: This function is duplicated in CRM_Core_BAO_WordReplacement and
273 * CRM_Upgrade_Incremental_php_FourFour to ensure that the incremental upgrade
274 * step behaves consistently even as the BAO evolves in future versions.
275 * However, if there's a bug in here prior to 4.4.0, we should apply the
276 * bugfix in both places.
277 *
278 * @param bool $rebuildEach whether to perform rebuild after each individual API call
279 * @return array Each item is $params for WordReplacement.create
280 * @see CRM_Core_BAO_WordReplacement::convertConfigArraysToAPIParams
281 */
282 static function getConfigArraysAsAPIParams($rebuildEach) {
283 $wordReplacementCreateParams = array();
284 // get all domains
285 $result = civicrm_api3('domain', 'get', array(
286 'return' => array('locale_custom_strings'),
287 ));
288 if (!empty($result["values"])) {
289 foreach ($result["values"] as $value) {
290 $params = array();
291 $params["domain_id"] = $value["id"];
292 $params["options"] = array('wp-rebuild' => $rebuildEach);
293 // unserialize word match string
294 $localeCustomArray = unserialize($value["locale_custom_strings"]);
295 if (!empty($localeCustomArray)) {
296 $wordMatchArray = array();
297 // Traverse Language array
298 foreach ($localeCustomArray as $localCustomData) {
299 // Traverse status array "enabled" "disabled"
300 foreach ($localCustomData as $status => $matchTypes) {
301 $params["is_active"] = ($status == "enabled")?TRUE:FALSE;
302 // Traverse Match Type array "wildcardMatch" "exactMatch"
303 foreach ($matchTypes as $matchType => $words) {
304 $params["match_type"] = $matchType;
305 foreach ($words as $word => $replace) {
306 $params["find_word"] = $word;
307 $params["replace_word"] = $replace;
308 $wordReplacementCreateParams[] = $params;
309 }
310 }
311 }
312 }
313 }
314 }
315 }
316 return $wordReplacementCreateParams;
317 }
318
319 /**
320 * Get all the word-replacements stored in config-arrays
321 * and write them out as records in civicrm_word_replacement.
322 *
323 * Note: This function is duplicated in CRM_Core_BAO_WordReplacement and
324 * CRM_Upgrade_Incremental_php_FourFour to ensure that the incremental upgrade
325 * step behaves consistently even as the BAO evolves in future versions.
326 * However, if there's a bug in here prior to 4.4.0, we should apply the
327 * bugfix in both places.
328 */
329 public static function rebuildWordReplacementTable() {
330 civicrm_api3('word_replacement', 'replace', array(
331 'options' => array('match' => array('domain_id', 'find_word')),
332 'values' => self::getConfigArraysAsAPIParams(FALSE),
333 ));
334 CRM_Core_BAO_WordReplacement::rebuild();
335 }
336 }