INFRA-132 - Add space before "{"
[civicrm-core.git] / CRM / Upgrade / Incremental / php / FourThree.php
CommitLineData
6a488035
TO
1<?php
2
3/*
4 +--------------------------------------------------------------------+
39de6fd5 5 | CiviCRM version 4.6 |
6a488035 6 +--------------------------------------------------------------------+
06b69b18 7 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
8 +--------------------------------------------------------------------+
9 | This file is a part of CiviCRM. |
10 | |
11 | CiviCRM is free software; you can copy, modify, and distribute it |
12 | under the terms of the GNU Affero General Public License |
13 | Version 3, 19 November 2007. |
14 | |
15 | CiviCRM is distributed in the hope that it will be useful, but |
16 | WITHOUT ANY WARRANTY; without even the implied warranty of |
17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
18 | See the GNU Affero General Public License for more details. |
19 | |
20 | You should have received a copy of the GNU Affero General Public |
21 | License along with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26*/
27
28/**
29 *
30 * @package CRM
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35class CRM_Upgrade_Incremental_php_FourThree {
36 const BATCH_SIZE = 5000;
37
624e56fa
EM
38 /**
39 * @param $errors
40 *
41 * @return bool
42 */
00be9182 43 public function verifyPreDBstate(&$errors) {
6a488035
TO
44 return TRUE;
45 }
46
505cf9f9
PJ
47 /**
48 * Compute any messages which should be displayed beforeupgrade
49 *
50 * Note: This function is called iteratively for each upcoming
51 * revision to the database.
52 *
77b97be7 53 * @param $preUpgradeMessage
c68f8bfa
TO
54 * @param $rev
55 * String, a version number, e.g. '4.3.alpha1', '4.3.beta3', '4.3.0'.
77b97be7
EM
56 * @param null $currentVer
57 *
ce4b9629 58 * @return void|bool
505cf9f9 59 */
00be9182 60 public function setPreUpgradeMessage(&$preUpgradeMessage, $rev, $currentVer = NULL) {
7402727c 61 if ($rev == '4.3.beta3') {
505cf9f9
PJ
62 //CRM-12084
63 //sql for checking orphaned contribution records
64 $sql = "SELECT COUNT(ct.id) FROM civicrm_contribution ct LEFT JOIN civicrm_contact c ON ct.contact_id = c.id WHERE c.id IS NULL";
65 $count = CRM_Core_DAO::singleValueQuery($sql, array(), TRUE, FALSE);
66
67 if ($count > 0) {
68 $error = ts("There is a data integrity issue with this CiviCRM database. It contains %1 contribution records which are linked to contact records that have been deleted. You will need to correct this manually before you can run the upgrade. Use the following MySQL query to identify the problem records: %2 These records will need to be deleted or linked to an existing contact record.", array(1 => $count, 2 => '<em>SELECT ct.* FROM civicrm_contribution ct LEFT JOIN civicrm_contact c ON ct.contact_id = c.id WHERE c.id IS NULL;</em>'));
69 CRM_Core_Error::fatal($error);
70 return FALSE;
71 }
72 }
de65d43e 73 if ($rev == '4.3.beta4' && CRM_Utils_Constant::value('CIVICRM_UF', FALSE) == 'Drupal6') {
70ec93e4
CB
74 // CRM-11823 - Make sure the D6 HTML HEAD technique will work on
75 // upgrade pages ... except when we're in Drush.
76 if (!function_exists('drush_main')) {
77 theme('item_list', array()); // force-load theme registry
78 $theme_registry = theme_get_registry();
79 if (!isset($theme_registry['page']['preprocess functions']) || FALSE === array_search('civicrm_preprocess_page_inject', $theme_registry['page']['preprocess functions'])) {
80 CRM_Core_Error::fatal('Please reset the Drupal cache (Administer => Site Configuration => Performance => Clear cached data))');
81 }
de65d43e
TO
82 }
83 }
77b97be7 84
ce4b9629
CW
85 if ($rev == '4.3.6') {
86 $constraintArray = array(
87 'civicrm_contact' => 'contact_id',
77b97be7 88 'civicrm_payment_processor' => 'payment_processor_id',
ce4b9629 89 );
77b97be7
EM
90
91 if (version_compare('4.1alpha1', $currentVer) <= 0) {
9e1a3f4f
PN
92 $constraintArray['civicrm_campaign'] = 'campaign_id';
93 }
77b97be7
EM
94
95 if (version_compare('4.3alpha1', $currentVer) <= 0) {
9e1a3f4f
PN
96 $constraintArray['civicrm_financial_type'] = 'financial_type_id';
97 }
77b97be7 98
ce4b9629
CW
99 foreach ($constraintArray as $key => $value) {
100 $query = "SELECT contri_recur.id FROM civicrm_contribution_recur contri_recur LEFT JOIN {$key} ON contri_recur.{$value} = {$key}.id
101WHERE {$key}.id IS NULL";
133b8445
PN
102 if ($value != 'contact_id') {
103 $query .= " AND contri_recur.{$value} IS NOT NULL ";
ce4b9629
CW
104 }
105 $dao = CRM_Core_DAO::executeQuery($query);
106 if ($dao->N) {
050743aa 107 $invalidDataMessage = '<strong>Oops, it looks like you have orphaned recurring contribution records in your database. Before this upgrade can complete they will need to be fixed or deleted. <a href="http://wiki.civicrm.org/confluence/display/CRMDOC/Fixing+Orphaned+Contribution+Recur+Records" target="_blank">You can review steps to correct this situation on the documentation wiki.</a></strong>';
ce4b9629
CW
108 CRM_Core_Error::fatal($invalidDataMessage);
109 return FALSE;
110 }
111 }
112 }
505cf9f9
PJ
113 }
114
6a488035
TO
115 /**
116 * Compute any messages which should be displayed after upgrade
117 *
c68f8bfa
TO
118 * @param $postUpgradeMessage
119 * String, alterable.
120 * @param $rev
121 * String, an intermediate version; note that setPostUpgradeMessage is called repeatedly with different $revs.
6a488035
TO
122 * @return void
123 */
00be9182 124 public function setPostUpgradeMessage(&$postUpgradeMessage, $rev) {
6a488035
TO
125 if ($rev == '4.3.alpha1') {
126 // check if CiviMember component is enabled
127 $config = CRM_Core_Config::singleton();
128 if (in_array('CiviMember', $config->enableComponents)) {
129 $postUpgradeMessage .= '<br />' . ts('Membership renewal reminders must now be configured using the Schedule Reminders feature, which supports multiple renewal reminders (Administer > Communications > Schedule Reminders). The Update Membership Statuses scheduled job will no longer send membershp renewal reminders. You can use your existing renewal reminder message template(s) with the Schedule Reminders feature.');
130 $postUpgradeMessage .= '<br />' . ts('The Set Membership Reminder Dates scheduled job has been deleted since membership reminder dates stored in the membership table are no longer in use.');
131 }
c28241be 132
6a488035 133 //CRM-11636
c28241be 134 //here we do the financial type check and migration
6a488035 135 $isDefaultsModified = self::_checkAndMigrateDefaultFinancialTypes();
22e263ad 136 if ($isDefaultsModified) {
6a488035 137 $postUpgradeMessage .= '<br />' . ts('Please review all price set financial type assignments.');
c28241be 138 }
6a488035
TO
139 list($context, $orgName) = self::createDomainContacts();
140 if ($context == 'added') {
10a5be27 141 $postUpgradeMessage .= '<br />' . ts("A new organization contact has been added as the default domain contact using the information from your Organization Address and Contact Info settings: '%1'.", array(1 => $orgName));
6a488035
TO
142 }
143 elseif ($context == 'merged') {
10a5be27 144 $postUpgradeMessage .= '<br />' . ts("The existing organization contact record for '%1' has been marked as the default domain contact, and has been updated with information from your Organization Address and Contact Info settings.", array(1 => $orgName));
6a488035 145 }
24571eea
DS
146
147 $providerExists = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_sms_provider LIMIT 1");
148 if ($providerExists) {
149 $postUpgradeMessage .= '<br />' . ts('SMS providers were found to setup. Please note Clickatell / Twilio are now shipped as extensions and will require installing them to continue working. Extension could be downloaded and installed from <a href="%1">github</a>.', array(1 => 'https://github.com/civicrm/civicrm-core/tree/master/tools/extensions'));
150 }
6a488035
TO
151 }
152
153 if ($rev == '4.3.alpha2') {
154 $sql = "
155SELECT title, id
156FROM civicrm_action_schedule
157WHERE entity_value = '' OR entity_value IS NULL
158";
c28241be 159
6a488035
TO
160 $dao = CRM_Core_DAO::executeQuery($sql);
161 $reminder = array();
162 $list = '';
163 while ($dao->fetch()) {
164 $reminder[$dao->id] = $dao->title;
165 $list .= "<li>{$dao->title}</li>";
166 }
c28241be 167 if (!empty($reminder)) {
6a488035
TO
168 $list = "<br /><ul>" . $list . "</ul>";
169 $postUpgradeMessage .= '<br />' .ts("Scheduled Reminders must be linked to one or more 'entities' (Events, Event Templates, Activity Types, Membership Types). The following reminders are not configured properly and will not be run. Please review them and update or delete them: %1", array(1 => $list));
170 }
171 }
2cf0e58d 172 if ($rev == '4.3.beta2') {
6a488035
TO
173 $postUpgradeMessage .= '<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><li>Events - Registration Confirmation and Receipt (off-line)</li><li>Pledges - Acknowledgement</li><li>Pledges - Payment Reminder</li><li>Contributions - Receipt (off-line)</li><li>Contributions - Receipt (on-line)</li><li>Memberships - Signup and Renewal Receipts (off-line)</li><li>Memberships - Receipt (on-line)</li><li>Personal Campaign Pages - Admin 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).');
174 }
e3a96c9b
DG
175
176 if ($rev == '4.3.beta5') {
177 $postUpgradeMessage .= '<br />' . ts("If you are interested in trying out the new Accounting Integration features, please review user permissions and assign the new 'manual batch' permissions as appropriate.");
178
179 // CRM-12155
22bf3365
DL
180 $query = "
181SELECT ceft.id FROM `civicrm_financial_trxn` cft
182LEFT JOIN civicrm_entity_financial_trxn ceft
183 ON ceft.financial_trxn_id = cft.id AND ceft.entity_table = 'civicrm_contribution'
184LEFT JOIN civicrm_contribution cc
185 ON cc.id = ceft.entity_id AND ceft.entity_table = 'civicrm_contribution'
186WHERE cc.id IS NULL
187";
e3a96c9b
DG
188
189 $dao = CRM_Core_DAO::executeQuery($query);
190 $isOrphanData = TRUE;
191 if (!$dao->N) {
22bf3365
DL
192 $query = "
193SELECT cli.id FROM civicrm_line_item cli
e3a96c9b
DG
194LEFT JOIN civicrm_contribution cc ON cli.entity_id = cc.id AND cli.entity_table = 'civicrm_contribution'
195LEFT JOIN civicrm_participant cp ON cli.entity_id = cp.id AND cli.entity_table = 'civicrm_participant'
196WHERE CASE WHEN cli.entity_table = 'civicrm_contribution'
22bf3365
DL
197 THEN cc.id IS NULL
198 ELSE cp.id IS NULL
199END
200";
e3a96c9b 201 $dao = CRM_Core_DAO::executeQuery($query);
22bf3365 202 if (!$dao->N) {
e3a96c9b
DG
203 $revPattern = '/^((\d{1,2})\.\d{1,2})\.(\d{1,2}|\w{4,7})?$/i';
204 preg_match($revPattern, $currentVer, $version);
205 if ($version[1] >= 4.3) {
22bf3365
DL
206 $query = "
207SELECT cfi.id
208FROM civicrm_financial_item cfi
e3a96c9b 209LEFT JOIN civicrm_entity_financial_trxn ceft ON ceft.entity_table = 'civicrm_financial_item' and cfi.id = ceft.entity_id
22bf3365
DL
210WHERE ceft.entity_id IS NULL;
211";
e3a96c9b 212 $dao = CRM_Core_DAO::executeQuery($query);
22bf3365 213 if (!$dao->N) {
e3a96c9b
DG
214 $isOrphanData = FALSE;
215 }
216 }
217 else {
22bf3365 218 $isOrphanData = FALSE;
e3a96c9b
DG
219 }
220 }
221 }
222
223 if ($isOrphanData) {
56181f67 224 $postUpgradeMessage .= "</br> <strong>" . ts('Your database contains extraneous financial records related to deleted contacts and contributions. These records should not affect the site and will not appear in reports, search results or exports. However you may wish to clean them up. Refer to <a href="%1" target="_blank">this wiki page for details</a>.
e3a96c9b
DG
225 ', array( 1 => 'http://wiki.civicrm.org/confluence/display/CRMDOC/Clean+up+extraneous+financial+data+-+4.3+upgrades')) . "</strong>";
226 }
227 }
56181f67
DG
228 if ($rev == '4.3.4') {
229 $postUpgradeMessage .= '<br />' . ts('System Administrator Alert: If you are running scheduled jobs using CLI.php, you will need to reconfigure cron tasks to include a password. Scheduled jobs will no longer run if the password is not provided (<a href="%1" target="_blank">learn more</a>).',
230 array( 1 => 'http://wiki.civicrm.org/confluence/display/CRMDOC/Managing+Scheduled+Jobs'));
231 }
5d9ebb64
PJ
232 if ($rev == '4.3.5') {
233 $postUpgradeMessage .= '<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><li>Events - Registration Confirmation and Receipt (off-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).');
234 }
b9810330
DG
235 if ($rev == '4.3.6') {
236 $flag = CRM_Core_DAO::singleValueQuery('SELECT count(ccp.id) FROM civicrm_contribution_product ccp
237INNER JOIN civicrm_product cp ON ccp.product_id = cp.id
238WHERE ccp.financial_type_id IS NULL and cp.cost > 0');
239 if ($flag) {
240 $postUpgradeMessage .= '<br />' . ts('Your database contains one or more premiums which have a cost but are not linked to a financial type. If you are exporting transations to an accounting package, this will result in unbalanced transactions. <a href="%1" target="_blank">You can review steps to correct this situation on the wiki.</a>',
241 array( 1 => 'http://wiki.civicrm.org/confluence/display/CRMDOC/Fixing+Issues+Caused+by+Missing+Cost+of+Goods+Account+-+4.3+Upgrades'));
242 }
243 }
6a488035
TO
244 }
245
624e56fa
EM
246 /**
247 * @param $rev
248 *
249 * @return bool
250 */
00be9182 251 public function upgrade_4_3_alpha1($rev) {
6a488035 252 self::task_4_3_alpha1_checkDBConstraints();
c28241be 253
b676923b
PN
254 // add indexes for civicrm_entity_financial_trxn
255 // CRM-12141
d1401e86 256 $this->addTask('Check/Add indexes for civicrm_entity_financial_trxn', 'task_4_3_x_checkIndexes', $rev);
6a488035 257 // task to process sql
d1401e86 258 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.3.alpha1')), 'task_4_3_x_runSql', $rev);
c28241be 259
6a488035 260 //CRM-11636
d1401e86 261 $this->addTask('Populate financial type values for price records', 'assignFinancialTypeToPriceRecords');
6a488035 262 //CRM-11514 create financial records for contributions
d1401e86 263 $this->addTask('Create financial records for contributions', 'createFinancialRecords');
c28241be 264
6a488035
TO
265 $minId = CRM_Core_DAO::singleValueQuery('SELECT coalesce(min(id),0) FROM civicrm_contact');
266 $maxId = CRM_Core_DAO::singleValueQuery('SELECT coalesce(max(id),0) FROM civicrm_contact');
267 for ($startId = $minId; $startId <= $maxId; $startId += self::BATCH_SIZE) {
268 $endId = $startId + self::BATCH_SIZE - 1;
10a5be27 269 $title = ts('Upgrade timestamps (%1 => %2)', array(1 => $startId, 2 => $endId));
6a488035
TO
270 $this->addTask($title, 'convertTimestamps', $startId, $endId);
271 }
272
273 // CRM-10893
274 // fix WP access control
275 $config = CRM_Core_Config::singleton( );
276 if ($config->userFramework == 'WordPress') {
277 civicrm_wp_set_capabilities( );
278 }
279
280 // Update phones CRM-11292.
d1401e86 281 $this->addTask('Upgrade Phone Numbers', 'phoneNumeric');
c28241be 282
6a488035
TO
283 return TRUE;
284 }
285
624e56fa
EM
286 /**
287 * @param $rev
288 */
00be9182 289 public function upgrade_4_3_alpha2($rev) {
6a488035
TO
290 //CRM-11847
291 $isColumnPresent = CRM_Core_DAO::checkFieldExists('civicrm_dedupe_rule_group', 'is_default');
292 if ($isColumnPresent) {
293 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_dedupe_rule_group DROP COLUMN is_default');
294 }
d1401e86 295 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.3.alpha2')), 'task_4_3_x_runSql', $rev);
6a488035
TO
296 }
297
624e56fa
EM
298 /**
299 * @param $rev
300 */
00be9182 301 public function upgrade_4_3_alpha3($rev) {
d1401e86 302 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.3.alpha3')), 'task_4_3_x_runSql', $rev);
6a488035
TO
303 }
304
624e56fa
EM
305 /**
306 * @param $rev
307 */
00be9182 308 public function upgrade_4_3_beta2($rev) {
d1401e86 309 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.3.beta2')), 'task_4_3_x_runSql', $rev);
ab00f69d 310
c28241be
DL
311 // CRM-12002
312 if (
313 CRM_Core_DAO::checkTableExists('log_civicrm_line_item') &&
314 CRM_Core_DAO::checkFieldExists('log_civicrm_line_item', 'label')
315 ) {
316 CRM_Core_DAO::executeQuery('ALTER TABLE `log_civicrm_line_item` CHANGE `label` `label` VARCHAR(255) NULL DEFAULT NULL');
317 }
318 }
319
624e56fa
EM
320 /**
321 * @param $rev
322 */
00be9182 323 public function upgrade_4_3_beta3($rev) {
d1401e86 324 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.3.beta3')), 'task_4_3_x_runSql', $rev);
d20145bc
PN
325 // CRM-12065
326 $query = "SELECT id, form_values FROM civicrm_report_instance WHERE form_values LIKE '%contribution_type%'";
327 $this->addTask('Replace contribution_type to financial_type in table civicrm_report_instance', 'replaceContributionTypeId', $query, 'reportInstance');
328 $query = "SELECT * FROM civicrm_saved_search WHERE form_values LIKE '%contribution_type%'";
329 $this->addTask('Replace contribution_type to financial_type in table civicrm_saved_search', 'replaceContributionTypeId', $query, 'savedSearch');
330 }
558ccc27 331
624e56fa
EM
332 /**
333 * @param $rev
334 */
00be9182 335 public function upgrade_4_3_beta4($rev) {
d1401e86 336 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.3.beta4')), 'task_4_3_x_runSql', $rev);
b676923b
PN
337 // add indexes for civicrm_entity_financial_trxn
338 // CRM-12141
d1401e86 339 $this->addTask('Check/Add indexes for civicrm_entity_financial_trxn', 'task_4_3_x_checkIndexes', $rev);
558ccc27
DL
340 }
341
624e56fa
EM
342 /**
343 * @param $rev
344 */
00be9182 345 public function upgrade_4_3_beta5($rev) {
ab00f69d
DL
346 // CRM-12205
347 if (
348 CRM_Core_DAO::checkTableExists('log_civicrm_financial_trxn') &&
349 CRM_Core_DAO::checkFieldExists('log_civicrm_financial_trxn', 'trxn_id')
350 ) {
351 CRM_Core_DAO::executeQuery('ALTER TABLE `log_civicrm_financial_trxn` CHANGE `trxn_id` `trxn_id` VARCHAR(255) NULL DEFAULT NULL');
352 }
35fe5ae1 353 // CRM-12142 - some sites didn't get this column added yet, and sites which installed 4.3 from scratch will already have it
be996105
PJ
354 // CRM-12367 - add this column to single lingual sites only
355 $upgrade = new CRM_Upgrade_Form();
356 if (!$upgrade->multilingual &&
35fe5ae1
DG
357 !CRM_Core_DAO::checkFieldExists('civicrm_premiums', 'premiums_nothankyou_label')
358 ) {
22bf3365
DL
359 $query = "
360ALTER TABLE civicrm_premiums
361ADD COLUMN premiums_nothankyou_label varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL
362 COMMENT 'Label displayed for No Thank-you option in premiums block (e.g. No thank you)'
363";
be996105 364 CRM_Core_DAO::executeQuery($query, array(), TRUE, NULL, FALSE, FALSE);
22bf3365 365 }
d1401e86 366 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.3.beta5')), 'task_4_3_x_runSql', $rev);
ab00f69d
DL
367 }
368
624e56fa
EM
369 /**
370 * @param $rev
371 */
00be9182 372 public function upgrade_4_3_4($rev) {
d1401e86 373 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.3.4')), 'task_4_3_x_runSql', $rev);
56181f67 374 }
2efcf0c2 375
624e56fa
EM
376 /**
377 * @param $rev
378 */
00be9182 379 public function upgrade_4_3_5($rev) {
d2e8983d
PN
380 // CRM-12156
381 $config = CRM_Core_Config::singleton();
382 $dbname = DB::parseDSN($config->dsn);
383 $sql = "SELECT DELETE_RULE
384FROM information_schema.REFERENTIAL_CONSTRAINTS
385WHERE CONSTRAINT_NAME = 'FK_civicrm_financial_item_contact_id'
386AND CONSTRAINT_SCHEMA = %1";
387 $params = array(1 => array($dbname['database'], 'String'));
388 $onDelete = CRM_Core_DAO::singleValueQuery($sql, $params, TRUE, FALSE);
2efcf0c2 389
d2e8983d
PN
390 if ($onDelete != 'CASCADE') {
391 $query = "ALTER TABLE `civicrm_financial_item`
392DROP FOREIGN KEY FK_civicrm_financial_item_contact_id,
393DROP INDEX FK_civicrm_financial_item_contact_id;";
394 CRM_Core_DAO::executeQuery($query, array(), TRUE, NULL, FALSE, FALSE);
395 $query = "
396ALTER TABLE `civicrm_financial_item`
397ADD CONSTRAINT `FK_civicrm_financial_item_contact_id` FOREIGN KEY (`contact_id`) REFERENCES `civicrm_contact` (`id`) ON DELETE CASCADE;
398";
399 CRM_Core_DAO::executeQuery($query, array(), TRUE, NULL, FALSE, FALSE);
400 }
d1401e86 401 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.3.5')), 'task_4_3_x_runSql', $rev);
d2e8983d 402 }
56181f67 403
624e56fa
EM
404 /**
405 * @param $rev
406 */
00be9182 407 public function upgrade_4_3_6($rev) {
5beb1de0 408 //CRM-13094
0947d54d 409 $this->addTask(ts('Add missing constraints'), 'addMissingConstraints', $rev);
bdbf899f 410 //CRM-13088
d1401e86
ML
411 $this->addTask('Add ON DELETE Options for constraints', 'task_4_3_x_checkConstraints', $rev);
412 $this->addTask(ts('Upgrade DB to %1: SQL', array(1 => '4.3.6')), 'task_4_3_x_runSql', $rev);
bf45dbe8
PN
413 // CRM-12844
414 // update line_item, financial_trxn and financial_item table for recurring contributions
d1401e86
ML
415 $this->addTask('Update financial_account_id in financial_trxn table', 'updateFinancialTrxnData', $rev);
416 $this->addTask('Update Line Item Data', 'updateLineItemData', $rev);
bf45dbe8 417 }
77b97be7 418
6a488035 419 //CRM-11636
624e56fa
EM
420 /**
421 * @return bool
422 */
00be9182 423 public function assignFinancialTypeToPriceRecords() {
6a488035
TO
424 $upgrade = new CRM_Upgrade_Form();
425 //here we update price set entries
22bf3365 426 $sqlFinancialIds = "
abe9581c 427SELECT id, LCASE(name) name
22bf3365
DL
428FROM civicrm_financial_type
429WHERE name IN ('Donation', 'Event Fee', 'Member Dues');
430";
6a488035 431 $daoFinancialIds = CRM_Core_DAO::executeQuery($sqlFinancialIds);
22e263ad 432 while ($daoFinancialIds->fetch()) {
6a488035
TO
433 $financialIds[$daoFinancialIds->name] = $daoFinancialIds->id;
434 }
22bf3365
DL
435 $sqlPriceSetUpdate = "
436UPDATE civicrm_price_set ps
437SET ps.financial_type_id =
438 CASE
abe9581c
PN
439 WHEN ps.extends LIKE '%1%' THEN {$financialIds['event fee']}
440 WHEN ps.extends LIKE '2' THEN {$financialIds['donation']}
441 WHEN ps.extends LIKE '3' THEN {$financialIds['member dues']}
6a488035 442 END
22bf3365
DL
443WHERE financial_type_id IS NULL
444";
6a488035
TO
445 CRM_Core_DAO::executeQuery($sqlPriceSetUpdate);
446
447 //here we update price field value rows
22bf3365
DL
448 $sqlPriceFieldValueUpdate = "
449UPDATE civicrm_price_field_value pfv
450LEFT JOIN civicrm_membership_type mt ON (pfv.membership_type_id = mt.id)
451INNER JOIN civicrm_price_field pf ON (pfv.price_field_id = pf.id)
452INNER JOIN civicrm_price_set ps ON (pf.price_set_id = ps.id)
453 SET pfv.financial_type_id =
454 CASE
455 WHEN pfv.membership_type_id IS NOT NULL THEN mt.financial_type_id
456 WHEN pfv.membership_type_id IS NULL THEN ps.financial_type_id
457 END
458";
6a488035 459 CRM_Core_DAO::executeQuery($sqlPriceFieldValueUpdate);
c28241be 460
6a488035
TO
461 return TRUE;
462 }
c28241be 463
624e56fa
EM
464 /**
465 * @return bool
466 */
00be9182 467 public static function _checkAndMigrateDefaultFinancialTypes() {
6a488035
TO
468 $modifiedDefaults = FALSE;
469 //insert types if not exists
22bf3365
DL
470 $sqlFetchTypes = "
471SELECT id, name
472FROM civicrm_contribution_type
473WHERE name IN ('Donation', 'Event Fee', 'Member Dues') AND is_active =1
474";
6a488035
TO
475 $daoFetchTypes = CRM_Core_DAO::executeQuery($sqlFetchTypes);
476
477 if ($daoFetchTypes->N < 3) {
478 $modifiedDefaults = TRUE;
c28241be 479 $insertStatments = array (
6a488035
TO
480 'Donation' => "('Donation', 0, 1, 1)",
481 'Member' => "('Member Dues', 0, 1, 1)",
482 'Event Fee' => "('Event Fee', 0, 1, 0)",
483 );
484 foreach ($insertStatments as $values) {
22bf3365
DL
485 $query = "
486INSERT INTO civicrm_contribution_type (name, is_reserved, is_active, is_deductible)
487VALUES $values
488ON DUPLICATE KEY UPDATE is_active = 1
489";
6a488035 490 CRM_Core_DAO::executeQuery($query);
c28241be 491 }
6a488035
TO
492 }
493 return $modifiedDefaults;
494 }
c28241be 495
624e56fa
EM
496 /**
497 * @return bool
498 */
00be9182 499 public function createFinancialRecords() {
6a488035
TO
500 $upgrade = new CRM_Upgrade_Form();
501
502 // update civicrm_entity_financial_trxn.amount = civicrm_financial_trxn.total_amount
22bf3365
DL
503 $query = "
504UPDATE civicrm_entity_financial_trxn ceft
505LEFT JOIN civicrm_financial_trxn cft ON cft.id = ceft.financial_trxn_id
506SET ceft.amount = total_amount
507WHERE cft.net_amount IS NOT NULL
508AND ceft.entity_table = 'civicrm_contribution'
509";
6a488035 510 CRM_Core_DAO::executeQuery($query);
c28241be 511
6a488035
TO
512 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
513 $completedStatus = array_search('Completed', $contributionStatus);
514 $pendingStatus = array_search('Pending', $contributionStatus);
515 $cancelledStatus = array_search('Cancelled', $contributionStatus);
516 $queryParams = array(
517 1 => array($completedStatus, 'Integer'),
518 2 => array($pendingStatus, 'Integer'),
519 3 => array($cancelledStatus, 'Integer')
520 );
c28241be 521
f743a6eb 522 $accountType = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name = 'Asset' "));
909a777b 523 $query = "
22bf3365
DL
524SELECT id
525FROM civicrm_financial_account
526WHERE is_default = 1
527AND financial_account_type_id = {$accountType}
528";
909a777b 529 $financialAccountId = CRM_Core_DAO::singleValueQuery($query);
c28241be 530
cc405f4e 531 $accountRelationsips = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_EntityFinancialAccount',
532 'account_relationship', CRM_Core_DAO::$_nullArray, 'validate');
c28241be 533
6a488035
TO
534 $accountsReceivableAccount = array_search('Accounts Receivable Account is', $accountRelationsips);
535 $incomeAccountIs = array_search('Income Account is', $accountRelationsips);
536 $assetAccountIs = array_search('Asset Account is', $accountRelationsips);
537 $expenseAccountIs = array_search('Expense Account is', $accountRelationsips);
c28241be 538
cc405f4e 539 $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id',
540 CRM_Core_DAO::$_nullArray, 'validate');
6a488035
TO
541 $unpaidStatus = array_search('Unpaid', $financialItemStatus);
542 $paidStatus = array_search('Paid', $financialItemStatus);
c28241be 543
6a488035
TO
544 $validCurrencyCodes = CRM_Core_PseudoConstant::currencyCode();
545 $validCurrencyCodes = implode("','", $validCurrencyCodes);
546 $config = CRM_Core_Config::singleton();
547 $defaultCurrency = $config->defaultCurrency;
548 $now = date( 'YmdHis' );
549
550 //adding financial_trxn records and entity_financial_trxn records related to contribution
551 //Add temp column for easy entry in entity_financial_trxn
552 $sql = "ALTER TABLE civicrm_financial_trxn ADD COLUMN contribution_id INT DEFAULT NULL";
553 CRM_Core_DAO::executeQuery($sql);
c28241be
DL
554
555 //pending pay later status handling
6a488035
TO
556 $sql = "
557INSERT INTO civicrm_financial_trxn
558 (contribution_id, payment_instrument_id, currency, total_amount, net_amount, fee_amount, trxn_id, status_id,
559 check_number, to_financial_account_id, from_financial_account_id, trxn_date)
22bf3365
DL
560SELECT con.id as contribution_id, con.payment_instrument_id,
561 IF(con.currency IN ('{$validCurrencyCodes}'), con.currency, '{$defaultCurrency}') as currency,
562 con.total_amount, con.net_amount, con.fee_amount, con.trxn_id, con.contribution_status_id,
563 con.check_number, efa.financial_account_id as to_financial_account_id, NULL as from_financial_account_id,
6a488035 564 REPLACE(REPLACE(REPLACE(
c28241be
DL
565 CASE
566 WHEN con.receive_date IS NOT NULL THEN
6a488035 567 con.receive_date
c28241be 568 WHEN con.receipt_date IS NOT NULL THEN
6a488035
TO
569 con.receipt_date
570 ELSE
c28241be 571 {$now}
6a488035
TO
572 END
573 , '-', ''), ':', ''), ' ', '') as trxn_date
574FROM civicrm_contribution con
c28241be 575 LEFT JOIN civicrm_entity_financial_account efa
6a488035
TO
576 ON (con.financial_type_id = efa.entity_id AND efa.entity_table = 'civicrm_financial_type'
577 AND efa.account_relationship = {$accountsReceivableAccount})
22bf3365
DL
578WHERE con.is_pay_later = 1
579AND con.contribution_status_id = {$pendingStatus}
580";
6a488035 581 CRM_Core_DAO::executeQuery($sql);
c28241be 582
6a488035
TO
583 //create a temp table to hold financial account id related to payment instruments
584 $tempTableName1 = CRM_Core_DAO::createTempTableName();
c28241be 585
c75e8bb2
DL
586 $sql = "
587CREATE TEMPORARY TABLE {$tempTableName1}
22bf3365
DL
588SELECT ceft.financial_account_id financial_account_id, cov.value as instrument_id
589FROM civicrm_entity_financial_account ceft
590INNER JOIN civicrm_option_value cov ON cov.id = ceft.entity_id AND ceft.entity_table = 'civicrm_option_value'
591INNER JOIN civicrm_option_group cog ON cog.id = cov.option_group_id
c75e8bb2
DL
592WHERE cog.name = 'payment_instrument'
593";
6a488035 594 CRM_Core_DAO::executeQuery($sql);
22bf3365 595
b676923b 596 //CRM-12141
1b1d8be3 597 $sql = "ALTER TABLE {$tempTableName1} ADD INDEX index_instrument_id (instrument_id(200));";
b676923b 598 CRM_Core_DAO::executeQuery($sql);
6a488035 599
c28241be 600 //create temp table to process completed / cancelled contribution
6a488035 601 $tempTableName2 = CRM_Core_DAO::createTempTableName();
22bf3365 602 $sql = "
c75e8bb2 603CREATE TEMPORARY TABLE {$tempTableName2}
22bf3365
DL
604SELECT con.id as contribution_id, con.payment_instrument_id,
605 IF(con.currency IN ('{$validCurrencyCodes}'), con.currency, '{$defaultCurrency}') as currency,
606 con.total_amount, con.net_amount, con.fee_amount, con.trxn_id, con.contribution_status_id,
607 con.check_number, NULL as from_financial_account_id,
c28241be
DL
608 REPLACE(REPLACE(REPLACE(
609 CASE
610 WHEN con.receive_date IS NOT NULL THEN
6a488035 611 con.receive_date
c28241be 612 WHEN con.receipt_date IS NOT NULL THEN
6a488035
TO
613 con.receipt_date
614 ELSE
c28241be 615 {$now}
6a488035
TO
616 END
617 , '-', ''), ':', ''), ' ', '') as trxn_date,
c28241be 618 CASE
6a488035
TO
619 WHEN con.payment_instrument_id IS NULL THEN
620 {$financialAccountId}
621 WHEN con.payment_instrument_id IS NOT NULL THEN
622 tpi.financial_account_id
623 END as to_financial_account_id,
624 IF(eft.financial_trxn_id IS NULL, 'insert', eft.financial_trxn_id) as action
22bf3365
DL
625FROM civicrm_contribution con
626LEFT JOIN civicrm_entity_financial_trxn eft
627 ON (eft.entity_table = 'civicrm_contribution' AND eft.entity_id = con.id)
628LEFT JOIN {$tempTableName1} tpi
629 ON con.payment_instrument_id = tpi.instrument_id
630WHERE con.contribution_status_id IN ({$completedStatus}, {$cancelledStatus})
631";
6a488035 632 CRM_Core_DAO::executeQuery($sql);
22bf3365 633
b676923b
PN
634 // CRM-12141
635 $sql = "ALTER TABLE {$tempTableName2} ADD INDEX index_action (action);";
636 CRM_Core_DAO::executeQuery($sql);
c28241be 637
6a488035
TO
638 //handling for completed contribution and cancelled contribution
639 //insertion of new records
640 $sql = "
c28241be 641INSERT INTO civicrm_financial_trxn
6a488035 642 (contribution_id, payment_instrument_id, currency, total_amount, net_amount, fee_amount, trxn_id, status_id, check_number,
c28241be 643 to_financial_account_id, from_financial_account_id, trxn_date)
6a488035
TO
644SELECT tempI.contribution_id, tempI.payment_instrument_id, tempI.currency, tempI.total_amount, tempI.net_amount,
645 tempI.fee_amount, tempI.trxn_id, tempI.contribution_status_id, tempI.check_number,
c28241be 646 tempI.to_financial_account_id, tempI.from_financial_account_id, tempI.trxn_date
6a488035 647FROM {$tempTableName2} tempI
c75e8bb2
DL
648WHERE tempI.action = 'insert'
649";
6a488035
TO
650 CRM_Core_DAO::executeQuery($sql);
651
652 //update of existing records
653 $sql = "
654UPDATE civicrm_financial_trxn ft
c28241be 655 INNER JOIN {$tempTableName2} tempU
6a488035
TO
656 ON (tempU.action != 'insert' AND ft.id = tempU.action)
657SET ft.from_financial_account_id = NULL,
658 ft.to_financial_account_id = tempU.to_financial_account_id,
c28241be 659 ft.status_id = tempU.contribution_status_id,
6a488035
TO
660 ft.payment_instrument_id = tempU.payment_instrument_id,
661 ft.check_number = tempU.check_number,
662 ft.contribution_id = tempU.contribution_id;";
663 CRM_Core_DAO::executeQuery($sql);
664
665 //insert the -ve transaction rows for cancelled contributions
666 $sql = "
667INSERT INTO civicrm_financial_trxn
c28241be
DL
668 (contribution_id, payment_instrument_id, currency, total_amount, net_amount, fee_amount, trxn_id, status_id,
669 check_number, to_financial_account_id, from_financial_account_id, trxn_date)
670SELECT ft.contribution_id, ft.payment_instrument_id, ft.currency, -ft.total_amount, ft.net_amount, ft.fee_amount, ft.trxn_id,
6a488035 671 ft.status_id, ft.check_number, ft.to_financial_account_id, ft.from_financial_account_id, ft.trxn_date
c28241be 672FROM civicrm_financial_trxn ft
6a488035
TO
673WHERE ft.status_id = {$cancelledStatus};";
674 CRM_Core_DAO::executeQuery($sql);
675
676 //inserting entity financial trxn entries if its not present in entity_financial_trxn for completed and pending contribution statuses
677 //this also handles +ve and -ve both transaction entries for a cancelled contribution
678 $sql = "
679INSERT INTO civicrm_entity_financial_trxn (entity_table, entity_id, financial_trxn_id, amount)
680SELECT 'civicrm_contribution', ft.contribution_id, ft.id, ft.total_amount as amount
681FROM civicrm_financial_trxn ft
c28241be
DL
682WHERE contribution_id IS NOT NULL AND
683 ft.id NOT IN (SELECT financial_trxn_id
684 FROM civicrm_entity_financial_trxn
6a488035
TO
685 WHERE entity_table = 'civicrm_contribution'
686 AND entity_id = ft.contribution_id)";
687 CRM_Core_DAO::executeQuery($sql);
688 //end of adding financial_trxn records and entity_financial_trxn records related to contribution
689
690 //update all linked line_item rows
691 // set line_item.financial_type_id = contribution.financial_type_id if contribution page id is null and not participant line item
692 // set line_item.financial_type_id = price_field_value.financial_type_id if contribution page id is set and not participant line item
693 // set line_item.financial_type_id = event.financial_type_id if its participant line item and line_item.price_field_value_id is null
694 // set line_item.financial_type_id = price_field_value.financial_type_id if its participant line item and line_item.price_field_value_id is set
695 $updateLineItemSql = "
696UPDATE civicrm_line_item li
697 LEFT JOIN civicrm_contribution con
698 ON (li.entity_id = con.id AND li.entity_table = 'civicrm_contribution')
699 LEFT JOIN civicrm_price_field_value cpfv
700 ON li.price_field_value_id = cpfv.id
701 LEFT JOIN civicrm_participant cp
702 ON (li.entity_id = cp.id AND li.entity_table = 'civicrm_participant')
703 LEFT JOIN civicrm_event ce
c28241be 704 ON ce.id = cp.event_id
6a488035 705SET li.financial_type_id = CASE
c28241be 706 WHEN (con.contribution_page_id IS NULL || li.price_field_value_id IS NULL) AND cp.id IS NULL THEN
6a488035
TO
707 con.financial_type_id
708 WHEN (con.contribution_page_id IS NOT NULL AND cp.id IS NULL) || (cp.id IS NOT NULL AND li.price_field_value_id IS NOT NULL) THEN
709 cpfv.financial_type_id
c28241be 710 WHEN cp.id IS NOT NULL AND li.price_field_value_id IS NULL THEN
6a488035
TO
711 ce.financial_type_id
712 END";
713 CRM_Core_DAO::executeQuery($updateLineItemSql, $queryParams);
c28241be
DL
714
715 //add the financial_item entries
6a488035
TO
716 //add a temp column so that inserting entity_financial_trxn entries gets easy
717 $sql = "ALTER TABLE civicrm_financial_item ADD COLUMN f_trxn_id INT DEFAULT NULL";
718 CRM_Core_DAO::executeQuery($sql);
c28241be 719
6a488035
TO
720 //add financial_item entries for contribution completed / pending pay later / cancelled
721 $contributionlineItemSql = "
c28241be 722INSERT INTO civicrm_financial_item
6a488035
TO
723 (transaction_date, contact_id, amount, currency, entity_table, entity_id, description, status_id, financial_account_id, f_trxn_id)
724
725SELECT REPLACE(REPLACE(REPLACE(ft.trxn_date, '-', ''), ':', ''), ' ', ''), con.contact_id,
c28241be 726 IF(ft.total_amount < 0 AND con.contribution_status_id = %3, -li.line_total, li.line_total) as line_total, con.currency, 'civicrm_line_item',
6a488035
TO
727 li.id as line_item_id, li.label as line_item_label,
728 IF(con.contribution_status_id = {$pendingStatus}, {$unpaidStatus}, {$paidStatus}) as status_id, efa.financial_account_id as financial_account_id,
729 ft.id as f_trxn_id
730FROM civicrm_line_item li
c28241be 731 INNER JOIN civicrm_contribution con
6a488035
TO
732 ON (li.entity_id = con.id AND li.entity_table = 'civicrm_contribution')
733 INNER JOIN civicrm_financial_trxn ft
734 ON (con.id = ft.contribution_id)
735 LEFT JOIN civicrm_entity_financial_account efa
736 ON (li.financial_type_id = efa.entity_id AND efa.entity_table = 'civicrm_financial_type'
737 AND efa.account_relationship = {$incomeAccountIs})
738WHERE con.contribution_status_id IN (%1, %3) OR (con.is_pay_later = 1 AND con.contribution_status_id = %2)";
739 CRM_Core_DAO::executeQuery($contributionlineItemSql, $queryParams);
c28241be 740
6a488035
TO
741 //add financial_item entries for event
742 $participantLineItemSql = "
c28241be 743INSERT INTO civicrm_financial_item
6a488035
TO
744 (transaction_date, contact_id, amount, currency, entity_table, entity_id, description, status_id, financial_account_id, f_trxn_id)
745
746SELECT REPLACE(REPLACE(REPLACE(ft.trxn_date, '-', ''), ':', ''), ' ', ''), con.contact_id,
747 IF(ft.total_amount < 0 AND con.contribution_status_id = %3, -li.line_total, li.line_total) as line_total,
c28241be 748 con.currency, 'civicrm_line_item', li.id as line_item_id, li.label as line_item_label,
6a488035
TO
749 IF(con.contribution_status_id = {$pendingStatus}, {$unpaidStatus}, {$paidStatus}) as status_id,
750 efa.financial_account_id as financial_account_id, ft.id as f_trxn_id
751FROM civicrm_line_item li
752 INNER JOIN civicrm_participant par
753 ON (li.entity_id = par.id AND li.entity_table = 'civicrm_participant')
c28241be
DL
754 INNER JOIN civicrm_participant_payment pp
755 ON (pp.participant_id = par.id)
6a488035
TO
756 INNER JOIN civicrm_contribution con
757 ON (pp.contribution_id = con.id)
c28241be 758 INNER JOIN civicrm_financial_trxn ft
6a488035
TO
759 ON (con.id = ft.contribution_id)
760 LEFT JOIN civicrm_entity_financial_account efa
761 ON (li.financial_type_id = efa.entity_id AND
762 efa.entity_table = 'civicrm_financial_type' AND efa.account_relationship = {$incomeAccountIs})
763WHERE con.contribution_status_id IN (%1, %3) OR (con.is_pay_later = 1 AND con.contribution_status_id = %2)";
764 CRM_Core_DAO::executeQuery($participantLineItemSql, $queryParams);
c28241be 765
6a488035
TO
766 //fee handling for contributions
767 //insert fee entries in financial_trxn for contributions
768 $sql = "ALTER TABLE civicrm_financial_trxn ADD COLUMN is_fee TINYINT DEFAULT NULL";
769 CRM_Core_DAO::executeQuery($sql);
c28241be 770
6a488035 771 $sql = "
c28241be 772INSERT INTO civicrm_financial_trxn
6a488035
TO
773 (contribution_id, payment_instrument_id, currency, total_amount, net_amount, fee_amount, trxn_id, status_id, check_number,
774 to_financial_account_id, from_financial_account_id, trxn_date, payment_processor_id, is_fee)
775
776SELECT con.id, ft.payment_instrument_id, ft.currency, ft.fee_amount, NULL, NULL, ft.trxn_id, %1 as status_id,
777 ft.check_number, efaFT.financial_account_id as to_financial_account_id, CASE
778 WHEN efaPP.financial_account_id IS NOT NULL THEN
779 efaPP.financial_account_id
780 WHEN tpi.financial_account_id IS NOT NULL THEN
c28241be
DL
781 tpi.financial_account_id
782 ELSE
783 {$financialAccountId}
6a488035
TO
784 END as from_financial_account_id, ft.trxn_date, ft.payment_processor_id, 1 as is_fee
785FROM civicrm_contribution con
786 INNER JOIN civicrm_financial_trxn ft
787 ON (ft.contribution_id = con.id)
788 LEFT JOIN civicrm_entity_financial_account efaFT
789 ON (con.financial_type_id = efaFT.entity_id AND efaFT.entity_table = 'civicrm_financial_type'
790 AND efaFT.account_relationship = {$expenseAccountIs})
c28241be 791 LEFT JOIN civicrm_entity_financial_account efaPP
6a488035
TO
792 ON (ft.payment_processor_id = efaPP.entity_id AND efaPP.entity_table = 'civicrm_payment_processor'
793 AND efaPP.account_relationship = {$assetAccountIs})
c28241be 794 LEFT JOIN {$tempTableName1} tpi
6a488035 795 ON ft.payment_instrument_id = tpi.instrument_id
368d2a88 796WHERE ft.fee_amount IS NOT NULL AND ft.fee_amount != 0 AND (con.contribution_status_id IN (%1, %3) OR (con.contribution_status_id =%2 AND con.is_pay_later = 1))
6a488035
TO
797GROUP BY con.id";
798 CRM_Core_DAO::executeQuery($sql, $queryParams);
799
c28241be 800 //link financial_trxn to contribution
6a488035
TO
801 $sql = "
802INSERT INTO civicrm_entity_financial_trxn
803 (entity_table, entity_id, financial_trxn_id, amount)
804SELECT 'civicrm_contribution', ft.contribution_id, ft.id, ft.total_amount
805FROM civicrm_financial_trxn ft
806WHERE ft.is_fee = 1";
807 CRM_Core_DAO::executeQuery($sql);
c28241be 808
6a488035
TO
809 //add fee related entries to financial item table
810 $domainId = CRM_Core_Config::domainID();
811 $domainContactId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Domain', $domainId, 'contact_id');
812 $sql = "
c28241be 813INSERT INTO civicrm_financial_item
6a488035 814 (transaction_date, contact_id, amount, currency, entity_table, entity_id, description, status_id, financial_account_id, f_trxn_id)
c28241be 815SELECT ft.trxn_date, {$domainContactId} as contact_id, ft.total_amount, ft.currency, 'civicrm_financial_trxn', ft.id,
6a488035 816 'Fee', {$paidStatus} as status_id, ft.to_financial_account_id as financial_account_id, ft.id as f_trxn_id
c28241be 817FROM civicrm_financial_trxn ft
6a488035
TO
818WHERE ft.is_fee = 1;";
819 CRM_Core_DAO::executeQuery($sql);
c28241be 820
6a488035
TO
821 //add entries to entity_financial_trxn table
822 $sql = "
823INSERT INTO civicrm_entity_financial_trxn (entity_table, entity_id, financial_trxn_id, amount)
824SELECT 'civicrm_financial_item' as entity_table, fi.id as entity_id, fi.f_trxn_id as financial_trxn_id, fi.amount
825FROM civicrm_financial_item fi";
826 CRM_Core_DAO::executeQuery($sql);
827
828 //drop the temparory columns
829 $sql = "ALTER TABLE civicrm_financial_trxn
830 DROP COLUMN contribution_id,
831 DROP COLUMN is_fee;";
832 CRM_Core_DAO::executeQuery($sql);
833
834 $sql = "ALTER TABLE civicrm_financial_item DROP f_trxn_id";
835 CRM_Core_DAO::executeQuery($sql);
c28241be 836
6a488035
TO
837 return TRUE;
838 }
839
624e56fa
EM
840 /**
841 * @return array
842 */
00be9182 843 public function createDomainContacts() {
6a488035
TO
844 $domainParams = $context = array();
845 $query = "
22bf3365
DL
846ALTER TABLE civicrm_domain ADD contact_id INT( 10 ) UNSIGNED NULL DEFAULT NULL COMMENT 'FK to Contact ID. This is specifically not an FK to avoid circular constraints',
847 ADD CONSTRAINT FK_civicrm_domain_contact_id FOREIGN KEY (contact_id) REFERENCES civicrm_contact(id);";
6a488035 848 CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray, TRUE, NULL, FALSE, FALSE);
c28241be 849
22bf3365
DL
850 $query = '
851SELECT cd.id, cd.name, ce.email FROM civicrm_domain cd
6a488035 852LEFT JOIN civicrm_loc_block clb ON clb.id = cd. loc_block_id
22bf3365
DL
853LEFT JOIN civicrm_email ce ON ce.id = clb.email_id ;
854' ;
6a488035 855 $dao = CRM_Core_DAO::executeQuery($query);
22e263ad 856 while ($dao->fetch()) {
22bf3365
DL
857 $query = "
858SELECT cc.id FROM civicrm_contact cc
6a488035 859LEFT JOIN civicrm_email ce ON ce.contact_id = cc.id
22bf3365
DL
860WHERE cc.contact_type = 'Organization' AND cc.organization_name = %1
861";
862 $params = array(1 => array($dao->name, 'String'));
6a488035 863 if ($dao->email) {
22bf3365
DL
864 $query .= " AND ce.email = %2 ";
865 $params[2] = array($dao->email, 'String');
6a488035 866 }
22bf3365 867 $contactID = CRM_Core_DAO::singleValueQuery($query, $params);
6a488035
TO
868 $context[1] = $dao->name;
869 if (empty($contactID)) {
d8e9fe86
PD
870 $params = array(
871 'sort_name' => $dao->name,
872 'display_name' => $dao->name,
873 'legal_name' => $dao->name,
874 'organization_name' => $dao->name,
875 'contact_type' => 'Organization'
876 );
6a488035
TO
877 $contact = CRM_Contact_BAO_Contact::add($params);
878 $contactID = $contact->id;
879 $context[0] = 'added';
c28241be 880 }
6a488035
TO
881 else {
882 $context[0] = 'merged';
883 }
884 $domainParams['contact_id'] = $contactID;
885 CRM_Core_BAO_Domain::edit($domainParams, $dao->id);
886 }
887 return $context;
888 }
889
00be9182 890 public function task_4_3_alpha1_checkDBConstraints() {
6a488035
TO
891 //checking whether the foreign key exists before dropping it CRM-11260
892 $config = CRM_Core_Config::singleton();
893 $dbUf = DB::parseDSN($config->dsn);
6a488035
TO
894 $tables = array(
895 'autorenewal_msg_id' => array('tableName' => 'civicrm_membership_type', 'fkey' => 'FK_civicrm_membership_autorenewal_msg_id'),
896 'to_account_id' => array('tableName' => 'civicrm_financial_trxn', 'constraintName' => 'civicrm_financial_trxn_ibfk_2'),
897 'from_account_id' => array('tableName' => 'civicrm_financial_trxn', 'constraintName' => 'civicrm_financial_trxn_ibfk_1'),
898 'contribution_type_id' => array('tableName' => 'civicrm_contribution_recur', 'fkey' => 'FK_civicrm_contribution_recur_contribution_type_id'),
899 );
22bf3365
DL
900 $query = "
901SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
6a488035
TO
902WHERE table_name = 'civicrm_contribution_recur'
903AND constraint_name = 'FK_civicrm_contribution_recur_contribution_type_id'
22bf3365
DL
904AND TABLE_SCHEMA = %1
905";
906 $params = array(1 => array($dbUf['database'], 'String'));
6a488035 907 $dao = CRM_Core_DAO::executeQuery($query, $params, TRUE, NULL, FALSE, FALSE);
9b873358 908 foreach ($tables as $columnName => $value) {
6a488035
TO
909 if ($value['tableName'] == 'civicrm_membership_type' || $value['tableName'] == 'civicrm_contribution_recur') {
910 $foreignKeyExists = CRM_Core_DAO::checkConstraintExists($value['tableName'], $value['fkey']);
911 $fKey = $value['fkey'];
0db6c3e1
TO
912 }
913 else {
fbeab178 914 $foreignKeyExists = CRM_Core_DAO::checkFKConstraintInFormat($value['tableName'], $columnName);
6a488035
TO
915 $fKey = "`FK_{$value['tableName']}_{$columnName}`";
916 }
917 if ($foreignKeyExists || $value['tableName'] == 'civicrm_financial_trxn') {
918 if ($value['tableName'] != 'civicrm_contribution_recur' || ($value['tableName'] == 'civicrm_contribution_recur' && $dao->N)) {
919 $constraintName = $foreignKeyExists ? $fKey : $value['constraintName'];
22bf3365
DL
920 $query = "ALTER TABLE {$value['tableName']} DROP FOREIGN KEY {$constraintName}";
921 CRM_Core_DAO::executeQuery($query, $params, TRUE, NULL, FALSE, FALSE);
6a488035 922 }
22bf3365
DL
923 $query = "ALTER TABLE {$value['tableName']} DROP INDEX {$fKey}";
924 CRM_Core_DAO::executeQuery($query, $params, TRUE, NULL, FALSE, FALSE);
6a488035
TO
925 }
926 }
927 // check if column contact_id is present or not in civicrm_financial_account
928 $fieldExists = CRM_Core_DAO::checkFieldExists('civicrm_financial_account', 'contact_id', FALSE);
929 if (!$fieldExists) {
22bf3365
DL
930 $query = "
931ALTER TABLE civicrm_financial_account
932 ADD contact_id int(10) unsigned DEFAULT NULL COMMENT 'Version identifier of financial_type' AFTER name,
933 ADD CONSTRAINT FK_civicrm_financial_account_contact_id FOREIGN KEY (contact_id) REFERENCES civicrm_contact(id);
934";
6a488035
TO
935 CRM_Core_DAO::executeQuery($query, $params, TRUE, NULL, FALSE, FALSE);
936 }
937 }
938
939 /**
940 * Read creation and modification times from civicrm_log; add
941 * them to civicrm_contact.
942 */
00be9182 943 public function convertTimestamps(CRM_Queue_TaskContext $ctx, $startId, $endId) {
6a488035
TO
944 $sql = "
945 SELECT entity_id, min(modified_date) AS created, max(modified_date) AS modified
946 FROM civicrm_log
947 WHERE entity_table = 'civicrm_contact'
948 AND entity_id BETWEEN %1 AND %2
949 GROUP BY entity_id
950 ";
951 $params = array(
952 1 => array($startId, 'Integer'),
953 2 => array($endId, 'Integer'),
954 );
955 $dao = CRM_Core_DAO::executeQuery($sql, $params);
956 while ($dao->fetch()) {
957 // FIXME civicrm_log.modified_date is DATETIME; civicrm_contact.modified_date is TIMESTAMP
958 CRM_Core_DAO::executeQuery(
16aa2ccd 959 'UPDATE civicrm_contact SET created_date = FROM_UNIXTIME(UNIX_TIMESTAMP(%1)), modified_date = FROM_UNIXTIME(UNIX_TIMESTAMP(%2)) WHERE id = %3',
6a488035
TO
960 array(
961 1 => array($dao->created, 'String'),
962 2 => array($dao->modified, 'String'),
963 3 => array($dao->entity_id, 'Integer'),
964 )
965 );
966 }
967
968 return TRUE;
969 }
77b97be7 970
5beb1de0 971 /**
100fef9d 972 * Change index and add missing constraints for civicrm_contribution_recur
5beb1de0 973 */
00be9182 974 public function addMissingConstraints(CRM_Queue_TaskContext $ctx) {
5beb1de0
PN
975 $query = "SHOW KEYS FROM `civicrm_contribution_recur` WHERE key_name = 'UI_contrib_payment_instrument_id'";
976 $dao = CRM_Core_DAO::executeQuery($query);
977 if ($dao->N) {
978 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_contribution_recur DROP INDEX UI_contrib_payment_instrument_id');
979 CRM_Core_DAO::executeQuery('ALTER TABLE civicrm_contribution_recur ADD INDEX UI_contribution_recur_payment_instrument_id (payment_instrument_id)');
980 }
981 $constraintArray = array(
77b97be7
EM
982 'contact_id' => " ADD CONSTRAINT `FK_civicrm_contribution_recur_contact_id` FOREIGN KEY (`contact_id`) REFERENCES `civicrm_contact` (`id`) ON DELETE CASCADE ",
983 'payment_processor_id' => " ADD CONSTRAINT `FK_civicrm_contribution_recur_payment_processor_id` FOREIGN KEY (`payment_processor_id`) REFERENCES `civicrm_payment_processor` (`id`) ON DELETE SET NULL ",
984 'financial_type_id' => " ADD CONSTRAINT `FK_civicrm_contribution_recur_financial_type_id` FOREIGN KEY (`financial_type_id`) REFERENCES `civicrm_financial_type` (`id`) ON DELETE SET NULL ",
5beb1de0
PN
985 'campaign_id' => " ADD CONSTRAINT `FK_civicrm_contribution_recur_campaign_id` FOREIGN KEY (`campaign_id`) REFERENCES `civicrm_campaign` (`id`) ON DELETE SET NULL ",
986 );
987 $constraint = array();
988 foreach ($constraintArray as $constraintKey => $value) {
989 $foreignKeyExists = CRM_Core_DAO::checkFKConstraintInFormat('civicrm_contribution_recur', $constraintKey);
990 if (!$foreignKeyExists) {
991 $constraint[] = $value;
992 }
993 }
994 if (!empty($constraint)) {
995 $query = "ALTER TABLE civicrm_contribution_recur " . implode(' , ', $constraint);
996 CRM_Core_DAO::executeQuery($query);
997 }
77b97be7 998 return TRUE;
5beb1de0
PN
999 }
1000
bf45dbe8
PN
1001 /**
1002 * Update financial_account_id for bad data in financial_trxn table
1003 * CRM-12844
77b97be7 1004 *
bf45dbe8 1005 */
00be9182 1006 public function updateFinancialTrxnData(CRM_Queue_TaskContext $ctx) {
5beb1de0 1007 $upgrade = new CRM_Upgrade_Form();
77b97be7 1008 $sql = "SELECT cc.id contribution_id, cc.contribution_recur_id, cft.payment_processor_id,
bf45dbe8
PN
1009cft.id financial_trxn_id, cfi.entity_table, cft.from_financial_account_id, cft.to_financial_account_id
1010
1011FROM `civicrm_contribution` cc
1012LEFT JOIN civicrm_entity_financial_trxn ceft ON ceft.entity_id = cc.id
1013LEFT JOIN civicrm_financial_trxn cft ON cft.id = ceft.financial_trxn_id
77b97be7 1014LEFT JOIN civicrm_entity_financial_trxn ceft1 ON ceft1.financial_trxn_id = ceft.financial_trxn_id
bf45dbe8
PN
1015LEFT JOIN civicrm_financial_item cfi ON cfi.id = ceft1.entity_id
1016WHERE ceft.entity_table = 'civicrm_contribution' AND cc.contribution_recur_id IS NOT NULL
1017AND ceft1.entity_table = 'civicrm_financial_item' AND cft.id IS NOT NULL AND cft.payment_instrument_id = %1
1018
1019ORDER BY cft.id ";
47b19837 1020 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument('name');
bf45dbe8
PN
1021 $param = array(1 => array(array_search('Credit Card', $paymentInstrument), 'Integer'));
1022 $dao = CRM_Core_DAO::executeQuery($sql, $param);
1023 $financialTrxn = array();
1024 $subsequentPayments = array();
1025 while ($dao->fetch()) {
1026 if (!array_key_exists($dao->contribution_recur_id, $financialTrxn)) {
1027 $financialTrxn[$dao->contribution_recur_id] = array(
1028 'from_financial_account_id' => $dao->to_financial_account_id,
1029 'payment_processor_id' => $dao->payment_processor_id,
1030 $dao->contribution_id => 1,
1031 );
1032 if (!is_null($dao->from_financial_account_id)) {
1033 $sql = 'UPDATE civicrm_financial_trxn SET from_financial_account_id = NULL WHERE id = %1';
1034 $params = array(1 => array($dao->financial_trxn_id, 'Integer'));
1035 CRM_Core_DAO::executeQuery($sql, $params);
1036 }
1037 }
1038 elseif (!array_key_exists($dao->contribution_id, $financialTrxn[$dao->contribution_recur_id])) {
77b97be7 1039 if (($dao->entity_table == 'civicrm_line_item' && $dao->to_financial_account_id == $financialTrxn[$dao->contribution_recur_id]['from_financial_account_id'])
bf45dbe8
PN
1040 || ($dao->entity_table == 'civicrm_financial_trxn' && $dao->from_financial_account_id == $financialTrxn[$dao->contribution_recur_id]['from_financial_account_id'])) {
1041 continue;
1042 }
1043 $subsequentPayments[$dao->contribution_recur_id][$dao->entity_table][] = $dao->financial_trxn_id;
1044 }
1045 }
1046 foreach ($subsequentPayments as $key => $value) {
1047 foreach ($value as $table => $val) {
1048 if ($table == 'civicrm_financial_trxn') {
1049 $field = 'from_financial_account_id';
1050 }
1051 else {
1052 $field = 'to_financial_account_id';
1053 }
77b97be7
EM
1054 $sql = "UPDATE civicrm_financial_trxn SET $field = " . $financialTrxn[$dao->contribution_recur_id]['from_financial_account_id'] . ',
1055payment_processor_id = ' . $financialTrxn[$dao->contribution_recur_id]['payment_processor_id'] . ' WHERE
bf45dbe8
PN
1056id IN (' . implode(',', $val) . ')';
1057 CRM_Core_DAO::executeQuery($sql);
1058 }
1059 }
1060 return TRUE;
1061 }
1062
1063 /**
1064 * Update financial_account_id for bad data in financial_trxn table
1065 * CRM-12844
77b97be7 1066 *
bf45dbe8 1067 */
00be9182 1068 public function updateLineItemData(CRM_Queue_TaskContext $ctx) {
5beb1de0 1069 $sql = "SELECT cc.id contribution_id, cc.contribution_recur_id,
77b97be7 1070cc.financial_type_id contribution_financial_type,
bf45dbe8
PN
1071cli.financial_type_id line_financial_type_id,
1072cli.price_field_id, cli.price_field_value_id, cli.label, cli.id line_item_id,
1073cfi.financial_account_id
1074FROM `civicrm_line_item` cli
1075LEFT JOIN civicrm_contribution cc ON cc.id = cli.entity_id
1076LEFT JOIN civicrm_financial_item cfi ON cfi.entity_id = cli.id
1077LEFT JOIN civicrm_price_field cpf ON cpf.id = cli.price_field_id
1078LEFT JOIN civicrm_price_set cps ON cps.id = cpf.price_set_id
1079LEFT JOIN civicrm_price_field_value cpfv ON cpfv.id = cli.price_field_value_id
77b97be7 1080WHERE cfi.entity_table = 'civicrm_line_item'
bf45dbe8 1081AND cli.entity_table = 'civicrm_contribution'
77b97be7 1082AND cps.is_quick_config = 1 AND cc.contribution_recur_id IS NOT NULL
bf45dbe8
PN
1083ORDER BY cli.id";
1084 $dao = CRM_Core_DAO::executeQuery($sql);
1085 $financialTrxn = $subsequentPayments = array();
1086 while ($dao->fetch()) {
1087 if (!array_key_exists($dao->contribution_recur_id, $financialTrxn)) {
1088 $financialTrxn[$dao->contribution_recur_id] = array(
1089 'price_field_id' => $dao->price_field_id,
1090 'price_field_value_id' => $dao->price_field_value_id,
89fa0610 1091 'label' => strval($dao->label),
bf45dbe8
PN
1092 'financial_account_id' => $dao->financial_account_id,
1093 $dao->contribution_id => 1,
1094 );
1095 }
1096 else {
1097 if ($dao->price_field_value_id == $financialTrxn[$dao->contribution_recur_id]['price_field_value_id']) {
1098 continue;
1099 }
1100 $subsequentPayments[$dao->contribution_recur_id][] = $dao->line_item_id;
1101 }
1102 }
1103 foreach ($subsequentPayments as $key => $value) {
1104 $sql = "UPDATE civicrm_line_item cli
1105LEFT JOIN civicrm_financial_item cfi ON cli.id = cfi.entity_id
77b97be7 1106SET
bf45dbe8
PN
1107cli.label = %1,
1108cli.price_field_id = %2,
1109cli.price_field_value_id = %3,
1110cfi.financial_account_id = %4,
1111cfi.description = %5,
1112cli.financial_type_id = %6
77b97be7 1113WHERE cfi.entity_table = 'civicrm_line_item'
bf45dbe8
PN
1114AND cli.entity_table = 'civicrm_contribution' AND cli.id IN (" . implode(',', $value). ');';
1115 $params = array(
1116 1 => array($financialTrxn[$key]['label'], 'String'),
1117 2 => array($financialTrxn[$key]['price_field_id'], 'Integer'),
1118 3 => array($financialTrxn[$key]['price_field_value_id'], 'Integer'),
1119 4 => array($financialTrxn[$key]['financial_account_id'], 'Integer'),
1120 5 => array($financialTrxn[$key]['label'], 'String'),
1121 6 => array($dao->contribution_financial_type, 'Integer'),
1122 );
1123 CRM_Core_DAO::executeQuery($sql, $params);
1124 }
1125 return TRUE;
1126 }
6a488035 1127
d20145bc 1128 /**
100fef9d 1129 * Replace contribution_type to financial_type in table
d20145bc
PN
1130 * civicrm_saved_search and Structure civicrm_report_instance
1131 */
00be9182 1132 public function replaceContributionTypeId(CRM_Queue_TaskContext $ctx, $query, $table) {
d20145bc
PN
1133 $dao = CRM_Core_DAO::executeQuery($query);
1134 while ($dao->fetch()) {
1135 $formValues = unserialize($dao->form_values);
1136 foreach (array('contribution_type_id_op', 'contribution_type_id_value', 'contribution_type_id') as $value) {
1137 if (array_key_exists($value, $formValues)) {
1138 $key = preg_replace('/contribution/', 'financial', $value);
1139 $formValues[$key] = $formValues[$value];
1140 unset($formValues[$value]);
1141 }
1142 }
1143 if ($table != 'savedSearch') {
1144 foreach (array('fields', 'group_bys') as $value) {
1145 if (array_key_exists($value, $formValues)) {
1146 if (array_key_exists('contribution_type_id', $formValues[$value])) {
1147 $formValues[$value]['financial_type_id'] = $formValues[$value]['contribution_type_id'];
1148 unset($formValues[$value]['contribution_type_id']);
1149 }
1150 else if (array_key_exists('contribution_type', $formValues[$value])) {
1151 $formValues[$value]['financial_type'] = $formValues[$value]['contribution_type'];
1152 unset($formValues[$value]['contribution_type']);
1153 }
1154 }
1155 }
1156 if (array_key_exists('order_bys', $formValues)) {
1157 foreach ($formValues['order_bys'] as $key => $values) {
1158 if (preg_grep('/contribution_type/', $values)) {
1159 $formValues['order_bys'][$key]['column'] = preg_replace('/contribution_type/', 'financial_type', $values['column']);
1160 }
1161 }
1162 }
1163 }
1164
1165 if ($table == 'savedSearch') {
1166 $saveDao = new CRM_Contact_DAO_SavedSearch();
1167 }
1168 else {
0b25329b 1169 $saveDao = new CRM_Report_DAO_ReportInstance();
d20145bc
PN
1170 }
1171 $saveDao->id = $dao->id;
1172
1173 if ($table == 'savedSearch') {
558ccc27 1174 if (array_key_exists('mapper', $formValues)) {
d20145bc
PN
1175 foreach ($formValues['mapper'] as $key => $values) {
1176 foreach ($values as $k => $v) {
1177 if (preg_grep('/contribution_/', $v)) {
1178 $formValues['mapper'][$key][$k] = preg_replace('/contribution_type/', 'financial_type', $v);
1179 }
1180 }
1181 }
1182 }
1183 foreach (array('select_tables', 'where_tables') as $value) {
1184 if (preg_match('/contribution_type/', $dao->$value)) {
1185 $tempValue = unserialize($dao->$value);
1186 if (array_key_exists('civicrm_contribution_type', $tempValue)) {
1187 $tempValue['civicrm_financial_type'] = $tempValue['civicrm_contribution_type'];
1188 unset($tempValue['civicrm_contribution_type']);
1189 }
1190 $saveDao->$value = serialize($tempValue);
1191 }
1192 }
1193 if (preg_match('/contribution_type/', $dao->where_clause)) {
1194 $saveDao->where_clause = preg_replace('/contribution_type/', 'financial_type', $dao->where_clause);
558ccc27 1195 }
d20145bc
PN
1196 }
1197 $saveDao->form_values = serialize($formValues);
1198
1199 $saveDao->save();
1200 }
1201 return TRUE;
1202 }
1203
bdbf899f
PN
1204 /**
1205 * Add ON DELETE options for constraint if not present
1206 * CRM-13088 && CRM-12156
1207 *
77b97be7
EM
1208 * @param CRM_Queue_TaskContext $ctx
1209 *
bdbf899f
PN
1210 * @return bool TRUE for success
1211 */
00be9182 1212 public function task_4_3_x_checkConstraints(CRM_Queue_TaskContext $ctx) {
49ddb59d 1213 CRM_Core_DAO::executeQuery('ALTER TABLE `civicrm_financial_account` CHANGE `contact_id` `contact_id` INT( 10 ) UNSIGNED NULL DEFAULT NULL');
bdbf899f
PN
1214 $config = CRM_Core_Config::singleton();
1215 $dbname = DB::parseDSN($config->dsn);
1216 $constraintArray = array(
1217 "'FK_civicrm_financial_account_contact_id'",
1218 "'FK_civicrm_financial_item_contact_id'",
1219 "'FK_civicrm_contribution_recur_financial_type_id'",
1220 "'FK_civicrm_line_item_financial_type_id'",
1221 "'FK_civicrm_product_financial_type_id'",
1222 "'FK_civicrm_premiums_product_financial_type_id'",
1223 "'FK_civicrm_price_field_value_financial_type_id'",
1224 "'FK_civicrm_contribution_product_financial_type_id'",
1225 "'FK_civicrm_price_set_financial_type_id'",
d4b17c97 1226 "'FK_civicrm_grant_financial_type_id'",
bdbf899f
PN
1227 );
1228
77b97be7 1229 $sql = "SELECT DELETE_RULE, TABLE_NAME, CONSTRAINT_NAME
bdbf899f
PN
1230FROM information_schema.REFERENTIAL_CONSTRAINTS
1231WHERE CONSTRAINT_NAME IN (" . implode(',', $constraintArray) . ")
1232AND CONSTRAINT_SCHEMA = %1";
1233 $params = array(1 => array($dbname['database'], 'String'));
1234 $onDelete = CRM_Core_DAO::executeQuery($sql, $params, TRUE, FALSE);
1235 while ($onDelete->fetch()) {
77b97be7 1236 if (($onDelete->TABLE_NAME != 'civicrm_financial_item' && $onDelete->DELETE_RULE != 'SET NULL') ||
bdbf899f
PN
1237 ($onDelete->TABLE_NAME == 'civicrm_financial_item' && $onDelete->DELETE_RULE != 'CASCADE')) {
1238 $tableName = 'civicrm_financial_type';
1239 $onDeleteOption = ' SET NULL ';
1240 $columnName = 'financial_type_id';
1241 if (preg_match('/contact_id/', $onDelete->CONSTRAINT_NAME)) {
1242 $tableName = 'civicrm_contact';
1243 $columnName = 'contact_id';
1244 if ($onDelete->TABLE_NAME == 'civicrm_financial_item') {
1245 $onDeleteOption = 'CASCADE';
1246 }
1247 }
1248 }
1249 else {
1250 continue;
1251 }
1252 $query = "ALTER TABLE {$onDelete->TABLE_NAME}
1253 DROP FOREIGN KEY {$onDelete->CONSTRAINT_NAME},
1254 DROP INDEX {$onDelete->CONSTRAINT_NAME};";
1255 CRM_Core_DAO::executeQuery($query, array(), TRUE, NULL, FALSE, FALSE);
1256 $query = " ALTER TABLE {$onDelete->TABLE_NAME}
1257 ADD CONSTRAINT {$onDelete->CONSTRAINT_NAME} FOREIGN KEY (`" . $columnName . "`) REFERENCES {$tableName} (`id`) ON DELETE {$onDeleteOption};
1258 ";
1259 CRM_Core_DAO::executeQuery($query, array(), TRUE, NULL, FALSE, FALSE);
1260 }
1261 return TRUE;
1262 }
1263
b676923b
PN
1264 /**
1265 * Check/Add INDEX CRM-12141
1266 *
77b97be7
EM
1267 * @param CRM_Queue_TaskContext $ctx
1268 *
b676923b
PN
1269 * @return bool TRUE for success
1270 */
00be9182 1271 public function task_4_3_x_checkIndexes(CRM_Queue_TaskContext $ctx) {
22bf3365
DL
1272 $query = "
1273SHOW KEYS
1274FROM civicrm_entity_financial_trxn
1275WHERE key_name IN ('UI_entity_financial_trxn_entity_table', 'UI_entity_financial_trxn_entity_id')
1276";
b676923b
PN
1277 $dao = CRM_Core_DAO::executeQuery($query);
1278 if (!$dao->N) {
22bf3365
DL
1279 $query = "
1280ALTER TABLE civicrm_entity_financial_trxn
b676923b 1281ADD INDEX UI_entity_financial_trxn_entity_table (entity_table),
22bf3365
DL
1282ADD INDEX UI_entity_financial_trxn_entity_id (entity_id);
1283";
1284 CRM_Core_DAO::executeQuery($query);
b676923b
PN
1285 }
1286 return TRUE;
1287 }
1288
6a488035
TO
1289 /**
1290 * Update phones CRM-11292
1291 *
77b97be7
EM
1292 * @param CRM_Queue_TaskContext $ctx
1293 *
6a488035
TO
1294 * @return bool TRUE for success
1295 */
00be9182 1296 public static function phoneNumeric(CRM_Queue_TaskContext $ctx) {
6a488035
TO
1297 CRM_Core_DAO::executeQuery(CRM_Contact_BAO_Contact::DROP_STRIP_FUNCTION_43);
1298 CRM_Core_DAO::executeQuery(CRM_Contact_BAO_Contact::CREATE_STRIP_FUNCTION_43);
1299 CRM_Core_DAO::executeQuery("UPDATE civicrm_phone SET phone_numeric = civicrm_strip_non_numeric(phone)");
1300 return TRUE;
1301 }
1302
1303 /**
1304 * (Queue Task Callback)
1305 */
00be9182 1306 public static function task_4_3_x_runSql(CRM_Queue_TaskContext $ctx, $rev) {
6a488035
TO
1307 $upgrade = new CRM_Upgrade_Form();
1308 $upgrade->processSQL($rev);
1309
1310 return TRUE;
1311 }
1312
1313 /**
1314 * Syntatic sugar for adding a task which (a) is in this class and (b) has
1315 * a high priority.
1316 *
1317 * After passing the $funcName, you can also pass parameters that will go to
1318 * the function. Note that all params must be serializable.
1319 */
1320 protected function addTask($title, $funcName) {
1321 $queue = CRM_Queue_Service::singleton()->load(array(
1322 'type' => 'Sql',
1323 'name' => CRM_Upgrade_Form::QUEUE_NAME,
1324 ));
1325
1326 $args = func_get_args();
1327 $title = array_shift($args);
1328 $funcName = array_shift($args);
1329 $task = new CRM_Queue_Task(
1330 array(get_class($this), $funcName),
1331 $args,
1332 $title
1333 );
1334 $queue->createItem($task, array('weight' => -1));
1335 }
10a5be27 1336}